import Link from "next/link";
import Image from "next/image";
import { AddToCartButton } from "../../components/AddToCartButton";
import { ProductGallery } from "../../components/ProductGallery";
import { Reveal } from "../../components/Reveal";
import { ProductName } from "../../components/ProductName";
import { getProductBySlug, getShippingSettings, getDefaultTaxRatePercent, getKleinunternehmer } from "../../lib/payload";
import { formatPrice, discountPercent } from "../../lib/format";
import { effectiveTaxRate } from "../../lib/cartTotals";

const checklist = [
  "Klarer Fokus auf das, was wirklich zählt",
  "Flexibel einsetzbar – jeden Tag",
  "Minimalistisch, analog, effektiv",
];

// Inline, brand-orange stroke — icon-check.svg's fill is hardcoded to
// #222221 via an internal CSS var that only resolves inside the SVG's own
// document, so it can't be recolored from the host page when loaded via
// <img src>/next/image. Same simple checkmark path as Challenge's own
// Check() component, for the same orange-checkmark look (fixed 2026-07-24).
function IconCheck() {
  return (
    <svg width="20" height="20" viewBox="0 0 20 20" fill="none" className="size-5 shrink-0 mt-1">
      <path d="M4 10.5l4.5 4.5L16 5.5" stroke="#f6a701" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}

// Same "todo-karten" product Pricing.tsx reads further down the page —
// this is just a compact early teaser so the hero's CTA isn't asking for
// a click without saying what it costs. Delivery time is repeated here too
// (not just in Pricing.tsx) since this is also a purchase CTA — Art. 246a
// §1 Abs.1 Nr.8 EGBGB's delivery-date disclosure needs to sit next to every
// buy button, not just one of them.
export async function TodoKartenHero() {
  const [product, shipping, defaultTaxRate, kleinunternehmer] = await Promise.all([
    getProductBySlug("todo-karten"),
    getShippingSettings(),
    getDefaultTaxRatePercent(),
    getKleinunternehmer(),
  ]);
  const discount = product ? discountPercent(product.price, product.compareAtPrice) : null;
  const taxRate = product ? effectiveTaxRate(product, defaultTaxRate) : null;
  // Same "any vs. every" split as ProductGrid.tsx/Pricing.tsx.
  const anyLowStock = product
    ? product.active && (product.variants.length > 0 ? product.variants.some((v) => v.lowStock) : product.lowStock)
    : false;

  return (
    <section className="bg-bg-base w-full overflow-hidden">
      {/* Same lg:-only structural exception as the Home Hero (see
          figma-to-nextjs skill Gotcha #5) — a wide fixed-ratio photo next
          to a text column is exactly the shape that gets too cramped at
          Tablet widths even under the site-wide sm: (640px) structural
          consolidation. lg:items-center
          removed (default grid align-items is stretch) — that's what lets
          the breadcrumb below sit at a fixed Y position across every hero
          section on the site instead of shifting per page depending on how
          much content each one has above the fold. */}
      {/* pt-10 md:pt-12, no lg override — with lg:items-center gone, this
          padding is now the ONLY thing positioning the breadcrumb
          vertically at every tier (previously lg:pt-0 relied on centering
          to add its own implicit offset instead). Kept flat past md so it
          matches /newsletter's and /challenge's identical top offset. */}
      <div className="flex flex-col lg:grid lg:grid-cols-12 gap-8 lg:gap-[var(--layout-grid-gap)] pt-10 md:pt-12">
        <Reveal className="order-1 lg:order-none lg:col-span-5 flex flex-col gap-6 items-start pl-[var(--layout-padding-x)] pr-10 lg:pr-0">
          {/* Breadcrumb — 3 levels (Startseite › Werkzeuge › ToDo-Karten),
              matching /newsletter's pattern; was missing "Startseite" as
              the first crumb. Deliberately NOT part of the centered block
              below — see the wrapper's comment. */}
          <p className="flex items-center gap-2 text-body-sm text-text-muted">
            <Link href="/" className="hover:text-brand transition-colors">
              Startseite
            </Link>
            <span>›</span>
            <Link href="/#werkzeuge" className="hover:text-brand transition-colors">
              Werkzeuge
            </Link>
            <span>›</span>
            <span className="text-text-primary">{product ? <ProductName name={product.name} /> : "ToDo-Karten"}</span>
          </p>

          {/* Everything else — centered in the remaining vertical space at
              lg+ (the column now stretches to match the image's height,
              since lg:items-center was removed above; flex-1 + justify-center
              here centers this block within that leftover space instead of
              the breadcrumb-inclusive whole column, which is what made the
              breadcrumb's Y position drift per page depending on total
              content height). */}
          <div className="flex flex-col gap-6 items-start w-full flex-1 lg:justify-center">
            {/* Heading — 48px Desktop doesn't match any existing type-scale
                step, uses the new --text-h-page token (see globals.css). */}
            <div className="flex flex-col gap-2 items-start w-full">
              <p
                className="font-semibold text-h-page text-text-primary"
                style={{ fontFamily: "var(--font-playfair)" }}
              >
                ToDo-Karten<span className="text-brand">.</span>
              </p>
              {product?.subline && (
                <p
                  className="font-semibold text-h3 text-text-primary"
                  style={{ fontFamily: "var(--font-lora)" }}
                >
                  {product.subline}
                </p>
              )}
            </div>

            <p className="text-body text-text-body">
              Ein einfaches Werkzeug, das dir hilft, deinen Kopf frei zu bekommen und das Wesentliche zu sehen.
            </p>

            <ul className="flex flex-col gap-3 items-start w-full">
              {checklist.map((item) => (
                <li key={item} className="flex gap-[0.625rem] items-start w-full">
                  <IconCheck />
                  <span className="flex-1 text-body text-text-primary">{item}</span>
                </li>
              ))}
            </ul>

            <div className="flex flex-col gap-1 items-start">
              {product && (
                <div className="flex gap-2 items-baseline">
                  {discount !== null && (
                    <p className="text-body text-text-muted line-through">{formatPrice(product.compareAtPrice!)}</p>
                  )}
                  <p className="font-bold text-h3 text-text-primary">{formatPrice(product.price)}</p>
                  <p className="text-label text-text-muted">
                    {kleinunternehmer
                      ? product.noShippingCost
                        ? "Keine Versandkosten"
                        : "zzgl. Versand"
                      : `inkl. ${taxRate}% MwSt. ${product.noShippingCost ? "– keine Versandkosten" : "zzgl. Versand"}`}
                  </p>
                </div>
              )}
              {!product?.noShippingCost && (
                <p className="text-label text-text-muted">
                  Lieferzeit: {shipping.totalDays.min}–{shipping.totalDays.max} Werktage innerhalb Deutschlands
                </p>
              )}
              {/* Single product, no grid siblings to stay equal-height with —
                  plain conditional line, same reasoning as ProductSpotlight.tsx/Pricing.tsx. */}
              {anyLowStock && <p className="text-label font-bold text-warning">Nur noch wenige verfügbar</p>}
            </div>

            {product && (
              // variants={[]} when deactivated — see Pricing.tsx's own
              // comment on why AddToCartButton's outOfStock prop alone
              // isn't enough once variants is non-empty.
              <AddToCartButton
                label="ToDo-Karten bestellen"
                numericId={product.numericId}
                outOfStock={!product.active || product.outOfStock}
                maxQty={product.maxQty}
                variants={product.active ? product.variants : []}
              />
            )}
          </div>
        </Reveal>

        {/* group + subtle scale-on-hover — a common, restrained "photo
            feels alive" micro-interaction; overflow-hidden on the wrapper
            (not the image) keeps the zoom from spilling past the rounded
            corners. delay={0.15} matches the Home Hero's text→image
            stagger — both fire ~immediately since Hero is already in the
            initial viewport, so this doubles as the page's entrance.
            Falls back to the curated static hero photo (a lifestyle shot,
            "in Anwendung, mit Notizbuch und Kaffee" — deliberately not
            just the plain catalog image) whenever this product has no
            `gallery` entries — the common case, and zero visual change
            from before ProductGallery existed. Only switches to the
            gallery once someone actually adds extra photos in the admin. */}
        {product && product.gallery.length > 0 ? (
          <Reveal className="order-2 lg:order-none lg:col-span-7" delay={0.15}>
            <ProductGallery image={product.image} gallery={product.gallery} alt={product.name} />
          </Reveal>
        ) : (
          <Reveal
            className="order-2 lg:order-none lg:col-span-7 group relative w-full aspect-[3/2] rounded-md overflow-hidden"
            delay={0.15}
          >
            <Image
              src="/hero-todo-karten.png"
              alt="ToDo-Karten in Anwendung, mit Notizbuch und Kaffee"
              fill
              priority
              sizes="(min-width: 1024px) 58vw, 100vw"
              className="object-cover transition-transform duration-500 group-hover:scale-105"
            />
          </Reveal>
        )}
      </div>
    </section>
  );
}
