import Link from "next/link";
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";

// The one bullet list on this page — after feedback that three separate
// lists across Hero/Focus/Pricing was too much, this is the single place
// features get enumerated, everywhere else stays prose. A subset of the
// "Was kann er?" section's four cards (Focus.tsx) — "Für jeden Tag" is a
// use case, not a build fact, so it's covered by the body copy instead.
const features = ["Massives Metallgehäuse", "Lasergravur: „Der Eine.“ & „einfach produktiv.“", "Kompakt genug für jede Tasche"];

// Same fix/reasoning as TodoKartenHero.tsx's IconCheck — icon-check.svg's
// fill can't be recolored from outside the SVG when loaded via <img
// src>/next/image, so this stays an inline stroke path per page.
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 "compact early teaser + delivery-time repeated next to every buy
// button" reasoning as TodoKartenHero.tsx.
export async function Hero() {
  const [product, shipping, defaultTaxRate, kleinunternehmer] = await Promise.all([
    getProductBySlug("stift-kugelschreiber"),
    getShippingSettings(),
    getDefaultTaxRatePercent(),
    getKleinunternehmer(),
  ]);
  const discount = product ? discountPercent(product.price, product.compareAtPrice) : null;
  const taxRate = product ? effectiveTaxRate(product, defaultTaxRate) : null;
  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">
      <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">
          <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} /> : "Der Eine."}</span>
          </p>

          <div className="flex flex-col gap-6 items-start w-full flex-1 lg:justify-center">
            <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)" }}
              >
                Der Eine<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">
              Manchmal reicht ein Stift und ein Stück Papier. Der Eine. ist ein schlichter Kugelschreiber aus Metall — angenehm in der Hand, klein genug für die Tasche und gemacht für alles, was kurz raus aus dem Kopf und irgendwo hin muss.
            </p>

            <ul className="flex flex-col gap-3 items-start w-full">
              {features.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>
              )}
              {anyLowStock && <p className="text-label font-bold text-warning">Nur noch wenige verfügbar</p>}
            </div>

            {product && (
              <AddToCartButton
                label="Der Eine. bestellen"
                productId={product.id}
                numericId={product.numericId}
                outOfStock={!product.active || product.outOfStock}
                maxQty={product.maxQty}
                variants={product.active ? product.variants : []}
              />
            )}
          </div>
        </Reveal>

        {/* max-w cap, not the full lg:col-span-7 width — the source photos
            are only 338×338px (checked directly against the Payload media
            API, no larger size exists), so letting ProductGallery stretch
            to the full column blows them up hard. Capping the display
            width keeps the upscale factor small enough that it doesn't
            look broken; it can't fix the underlying resolution, only hide
            it. Real fix is new source photos, not a layout tweak. */}
        {product && product.gallery.length > 0 && (
          <Reveal className="order-2 lg:order-none lg:col-span-7 flex lg:items-center px-[var(--layout-padding-x)] lg:px-0" delay={0.15}>
            <div className="w-full max-w-[28rem] mx-auto lg:mx-0">
              <ProductGallery image={product.image} gallery={product.gallery} alt={product.name} />
            </div>
          </Reveal>
        )}
      </div>
    </section>
  );
}
