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

const bullets = [
  "50 ToDo-Karten",
  "Hochwertiges Papier (120 g/m²)",
  "Format: 105 x 148 mm (A6)",
  "Inklusive Mini-Anleitung",
  "Nachhaltig produziert in Deutschland",
];

// Price/photo come from Payload (same "todo-karten" product the shop/cart
// use), not a hardcoded literal — see ProductSpotlight.tsx for the same
// reasoning; the bullet list stays hand-written since it's spec detail,
// not something the Products collection models.
export async function Pricing() {
  const [product, shipping, defaultTaxRate, kleinunternehmer] = await Promise.all([
    getProductBySlug("todo-karten"),
    getShippingSettings(),
    getDefaultTaxRatePercent(),
    getKleinunternehmer(),
  ]);
  if (!product) return null;
  const discount = discountPercent(product.price, product.compareAtPrice);
  const taxRate = effectiveTaxRate(product, defaultTaxRate);
  // Same "any vs. every" split as ProductGrid.tsx/ProductSpotlight.tsx.
  // A deactivated product (product.active === false) isn't caught by
  // either — the shop grid/spotlight filter those out before they'd ever
  // reach this page, but this page resolves a product regardless of
  // active status (existing links to it should still 200, see
  // mapPayloadProduct's own comment in lib/payload.ts) — so it needs its
  // own explicit check here to read as "Ausverkauft" rather than fully
  // buyable (fixed 2026-07-24, feedback: deactivated should look
  // sold-out on its own detail page).
  const fullyOutOfStock =
    !product.active || (product.variants.length > 0 ? product.variants.every((v) => v.outOfStock) : product.outOfStock);
  const anyLowStock = product.active && (product.variants.length > 0 ? product.variants.some((v) => v.lowStock) : product.lowStock);

  return (
    <section className="w-full bg-bg-base px-[var(--layout-padding-x)] py-8">
      {/* Three flex children (photo, info, price/CTA) competing for space
          — same "big image next to text" shape as the Hero/Focus, so the
          same lg:-only structural exception applies here too. */}
      <Reveal className="bg-bg-muted rounded-md flex flex-col lg:flex-row gap-8 lg:gap-12 items-center p-6 lg:pl-8 lg:pr-10 lg:py-6">
        <div className="group relative w-full lg:w-[25.625rem] lg:shrink-0 aspect-[410/227] rounded-sm overflow-hidden">
          <Image
            src={product.image}
            alt="ToDo-Karten Set"
            fill
            sizes="(min-width: 1024px) 410px, 100vw"
            className="object-cover transition-transform duration-500 group-hover:scale-105"
          />
          {fullyOutOfStock ? (
            <span className="absolute top-3 left-3 rounded-full bg-text-muted px-2.5 py-1 text-label font-bold text-bg-base">
              Ausverkauft
            </span>
          ) : (
            discount !== null && (
              <span className="absolute top-3 left-3 rounded-full bg-brand px-2.5 py-1 text-label font-bold text-text-primary">
                -{discount}%
              </span>
            )
          )}
        </div>

        <div className="flex flex-col gap-3 items-start flex-1 min-w-0 w-full">
          <p
            className="font-semibold text-h-small text-text-primary"
            style={{ fontFamily: "var(--font-lora)" }}
          >
            ToDo-Karten – Set
          </p>
          <ul className="flex flex-col gap-[0.375rem] items-start">
            {bullets.map((b) => (
              <li key={b} className="flex gap-2 items-center">
                <Image alt="" src="/icon-bullet-dot.svg" width={4} height={4} className="size-1 shrink-0" />
                <span className="text-body-sm text-text-primary">{b}</span>
              </li>
            ))}
          </ul>
        </div>

        <div className="flex flex-col gap-3 items-start w-full lg:w-[18.75rem] lg:shrink-0">
          {/* MwSt./Versand disclosure on its own line, not crammed into
              the price row itself — "inkl. X% MwSt. zzgl. Versand" is
              long enough (once the rate is spelled out) that sharing a
              row with the price in this panel's narrow fixed-width
              column wrapped it mid-sentence onto a second line. */}
          <div className="flex flex-col gap-1 items-start">
            <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>
            </div>
            <p className="text-label text-text-muted">
              {kleinunternehmer
                ? product.noShippingCost
                  ? "Keine Versandkosten"
                  : "zzgl. Versand"
                : `inkl. ${taxRate}% MwSt. ${product.noShippingCost ? "– keine Versandkosten" : "zzgl. Versand"}`}
            </p>
            {!product.noShippingCost && (
              <p className="text-label text-text-muted">
                Lieferzeit: {shipping.totalDays.min}–{shipping.totalDays.max} Werktage innerhalb Deutschlands
              </p>
            )}
          </div>
          {/* Single product, no grid siblings to stay equal-height with —
              plain conditional line, same reasoning as ProductSpotlight.tsx. */}
          {anyLowStock && <p className="text-label font-bold text-warning">Nur noch wenige verfügbar</p>}
          {/* No "Sichere Zahlung" trust note here (unlike Cart/Checkout) —
              this is an add-to-cart step, not the actual payment step, so
              a payment-security reassurance is premature here and just
              duplicates the one shown later at checkout. */}
          {/* variants={[]} when deactivated — AddToCartButton's own
              outOfStock prop is ignored whenever variants is non-empty (it
              defers to each variant's own outOfStock flag instead, see its
              currentlyOutOfStock calc), so a deactivated product with
              in-stock variants would otherwise still render as buyable. */}
          <AddToCartButton
            label="In den Warenkorb"
            className="w-full inline-flex items-center justify-center px-6 py-[0.8125rem] rounded-sm bg-brand hover:bg-brand-hover active:scale-[0.97] transition-all font-bold text-body text-text-primary text-center focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand focus-visible:ring-offset-2 focus-visible:ring-offset-bg-muted"
            numericId={product.numericId}
            outOfStock={!product.active || product.outOfStock}
            maxQty={product.maxQty}
            variants={product.active ? product.variants : []}
          />
        </div>
      </Reveal>
    </section>
  );
}
