"use client";

import { useRef, useState } from "react";
import Link from "next/link";
import Image from "next/image";
import { useRouter } from "next/navigation";
import { useCart, clearCart, mergeServerCartIntoLocal } from "../../lib/cart";
import { useProducts } from "../../lib/products";
import { useDiscount, clearDiscount } from "../../lib/discount";
import { computeSubtotal, computeCartTotals } from "../../lib/cartTotals";
import { formatPrice } from "../../lib/format";
import { Reveal } from "../../components/Reveal";
import { VersandModal } from "../../components/VersandModal";
import { CheckoutSteps } from "../../components/CheckoutSteps";
import { ORDER_KEY, type OrderSnapshot } from "../../lib/order";
import type { ShippingMethod, PaymentMethod, TrustBadge, ShippingSettings } from "../../lib/payload";
import type { CustomerProfile } from "../../lib/customerAuth";

function FormField({
  label,
  wrapperClassName = "flex-1 min-w-0",
  ...props
}: { label: string; wrapperClassName?: string } & React.InputHTMLAttributes<HTMLInputElement>) {
  return (
    <label className={`flex flex-col gap-2 items-start ${wrapperClassName}`}>
      <span className="text-label text-text-muted">{label}</span>
      <input
        {...props}
        className="w-full border border-border rounded-sm px-4 py-3 text-body-sm text-text-primary outline-none focus:border-brand transition-colors"
      />
    </label>
  );
}

export function CheckoutContent({
  shippingMethods,
  paymentMethods,
  trustBadges,
  shippingSettings,
  customerEmail,
  savedProfile,
}: {
  shippingMethods: ShippingMethod[];
  paymentMethods: PaymentMethod[];
  trustBadges: TrustBadge[];
  /** Delivery-time disclosure (Payload's Shipping Settings) — named
   * "shippingSettings", not "shipping", since that name is already the
   * local computed shipping-cost value below. */
  shippingSettings: ShippingSettings;
  /** From the checkout page's own session read (app/lib/customerAuth.ts) —
   * null means no account is logged in yet, which flips "1. Rechnungsadresse"
   * into inline-registration mode (password field shown, account created on
   * submit) since an account is required to buy. */
  customerEmail: string | null;
  /** Full profile (name + saved address) — null when logged out, pre-fills
   * Card 1's fields for a returning customer instead of leaving them blank. */
  savedProfile: CustomerProfile | null;
}) {
  const router = useRouter();
  const cart = useCart();
  const products = useProducts();
  const discount = useDiscount();
  const [shippingMethodId, setShippingMethodId] = useState<number | null>(shippingMethods[0]?.id ?? null);
  const [paymentMethodId, setPaymentMethodId] = useState<number | null>(paymentMethods[0]?.id ?? null);
  const [versandOpen, setVersandOpen] = useState(false);
  const [deliveryMethod, setDeliveryMethod] = useState<"address" | "packstation">(savedProfile?.deliveryMethod ?? "address");
  const [purchaseError, setPurchaseError] = useState<string | null>(null);
  const [purchasing, setPurchasing] = useState(false);
  const [showLogin, setShowLogin] = useState(false);
  const accountGateRef = useRef<HTMLDivElement>(null);
  const [loginEmail, setLoginEmail] = useState("");
  const [loginPassword, setLoginPassword] = useState("");
  const [loginError, setLoginError] = useState<string | null>(null);
  const [loggingIn, setLoggingIn] = useState(false);

  const productsLoading = products.length === 0 && cart.length > 0;
  const items = cart
    .map((entry) => ({ entry, product: products.find((p) => p.id === entry.id) }))
    .filter((row): row is { entry: typeof cart[number]; product: NonNullable<(typeof row)["product"]> } => Boolean(row.product));

  const subtotal = computeSubtotal(items);
  const selectedShipping = shippingMethods.find((m) => m.id === shippingMethodId) ?? null;
  const freeShipping =
    selectedShipping?.freeShippingThreshold !== null &&
    selectedShipping?.freeShippingThreshold !== undefined &&
    subtotal >= selectedShipping.freeShippingThreshold;
  const shipping = items.length === 0 || freeShipping ? 0 : selectedShipping?.price ?? 0;
  const { totalSavings, discountAmount, total } = computeCartTotals(items, shipping, discount);

  // Logs into an existing account inline, without leaving /checkout —
  // router.refresh() re-runs the page's Server Component, which re-reads
  // the now-set session cookie and passes the resolved customerEmail back
  // down, flipping this form out of registration mode.
  async function handleLogin() {
    setLoggingIn(true);
    setLoginError(null);
    try {
      const res = await fetch("/api/account/login", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email: loginEmail, password: loginPassword }),
      });
      const data = await res.json();
      if (!data.ok) {
        setLoginError(data.reason || "Login fehlgeschlagen.");
        setLoggingIn(false);
        return;
      }
      await mergeServerCartIntoLocal();
      router.refresh();
    } catch {
      setLoginError("Login ist gerade nicht möglich.");
      setLoggingIn(false);
    }
  }

  async function handleLogout() {
    await fetch("/api/account/logout", { method: "POST" });
    router.refresh();
  }

  // Checks whether the email just typed into Card 1 already has an
  // account — proactively, on blur, rather than only finding out after a
  // registration attempt fails (see handleSubmit's own emailExists
  // handling, which still applies as a fallback if this check is skipped
  // or the account was created in the meantime). Silent when there's no
  // match — the account gate simply stays empty; nothing is shown "just
  // in case", only once actually relevant.
  async function handleEmailBlur(e: React.FocusEvent<HTMLInputElement>) {
    const email = e.target.value.trim();
    if (!email || customerEmail || showLogin) return;
    try {
      const res = await fetch("/api/account/check-email", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email }),
      });
      const data = await res.json();
      if (data.exists) {
        setLoginEmail(email);
        setShowLogin(true);
      }
    } catch {
      // Best-effort — worst case, the registration attempt itself catches
      // the collision at submit time instead (handleSubmit).
    }
  }

  // Always goes through /api/checkout now — that route re-prices
  // everything server-side, re-validates+redeems a discount code exactly
  // once (see its own comment), registers a new account inline when no
  // session exists yet ("Konto Pflicht"), and only then persists the order
  // in Payload. Replaces the old client-only sessionStorage snapshot.
  async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setPurchasing(true);
    setPurchaseError(null);

    const form = new FormData(e.currentTarget);
    const body = {
      cart,
      shippingMethodId,
      paymentMethodId,
      discountCode: discount?.code ?? null,
      firstName: String(form.get("firstName") ?? ""),
      lastName: String(form.get("lastName") ?? ""),
      email: String(form.get("email") ?? ""),
      password: customerEmail ? undefined : String(form.get("password") ?? ""),
      deliveryMethod,
      street: String(form.get("street") ?? "") || undefined,
      packstationNumber: String(form.get("packstationNumber") ?? "") || undefined,
      postNumber: String(form.get("postNumber") ?? "") || undefined,
      zip: String(form.get("zip") ?? ""),
      city: String(form.get("city") ?? ""),
      country: String(form.get("country") ?? ""),
      newsletterOptIn: form.get("newsletterOptIn") === "on",
    };

    try {
      const res = await fetch("/api/checkout", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(body),
      });
      const data = await res.json();
      if (!data.ok) {
        // The email typed into Card 1 already belongs to an existing
        // account — registering was never going to work here. Switch
        // straight to the login toggle with that email pre-filled instead
        // of just showing an error with no clear next step; the customer
        // only needs to add their password and resubmit.
        if (data.emailExists) {
          setLoginEmail(body.email);
          setShowLogin(true);
          accountGateRef.current?.scrollIntoView({ behavior: "smooth", block: "center" });
        }
        setPurchaseError(data.reason || "Die Bestellung konnte nicht abgeschlossen werden.");
        setPurchasing(false);
        return;
      }

      const snapshot: OrderSnapshot = {
        items: cart,
        orderNumber: data.orderNumber,
        orderDateIso: data.orderDateIso,
        shippingCost: data.shippingCost,
        paymentMethodTitle: data.paymentMethodTitle,
        discountCode: data.discountCode,
        discountAmount: data.discountAmount,
      };
      try {
        window.sessionStorage.setItem(ORDER_KEY, JSON.stringify(snapshot));
      } catch {
        // sessionStorage unavailable (private browsing etc.) — the
        // confirmation page falls back to its own empty state.
      }
      clearCart();
      clearDiscount();
      router.push("/bestellbestaetigung");
    } catch {
      setPurchaseError("Die Bestellung konnte gerade nicht abgeschlossen werden.");
      setPurchasing(false);
    }
  }

  if (!productsLoading && items.length === 0) {
    return (
      <Reveal className="flex flex-col gap-6 items-start pt-10 pb-16 px-[var(--layout-padding-x)] w-full">
        <p
          className="font-semibold text-h-feature text-text-primary"
          style={{ fontFamily: "var(--font-lora)" }}
        >
          Checkout
        </p>
        <p className="text-body text-text-muted">
          Dein Warenkorb ist leer — es gibt noch nichts zum Abschließen.
        </p>
        <Link
          href="/shop"
          className="flex items-center gap-2 px-7 py-4 rounded-sm bg-brand text-h4 font-bold text-text-primary hover:bg-brand-hover active:scale-[0.97] transition-all"
        >
          Zum Shop
        </Link>
      </Reveal>
    );
  }

  return (
    <>
      {/* Header — breadcrumb, stepper, title */}
      <Reveal className="flex flex-col gap-8 items-start pt-8 pb-6 px-[var(--layout-padding-x)] w-full">
        <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="/cart" className="hover:text-brand transition-colors">Warenkorb</Link>
          <span>›</span>
          <span className="text-text-primary">Checkout</span>
        </p>

        <CheckoutSteps current={2} />

        <div className="flex flex-col gap-2">
          <p
            className="font-semibold text-h-feature text-text-primary"
            style={{ fontFamily: "var(--font-lora)" }}
          >
            Checkout
          </p>
          <p className="text-body text-text-muted">Fast geschafft! Nur noch ein paar Angaben.</p>
        </div>

        {/* Account gate — an account is required to buy. Not a persistent
            "already a customer? log in" prompt anymore (removed —
            Nutzer-Entscheidung: don't show it unless actually relevant):
            stays empty by default, and only shows the login form once
            handleEmailBlur (Card 1's email field) or handleSubmit's own
            emailExists fallback actually detects that the typed email
            belongs to an existing account. Ref used to scroll this into
            view when that happens after a submit attempt specifically. */}
        <div ref={accountGateRef} className="w-full">
        {customerEmail ? (
          <p className="text-body-sm text-text-primary">
            Eingeloggt als <span className="font-bold">{customerEmail}</span>{" "}
            <button type="button" onClick={handleLogout} className="underline hover:text-brand transition-colors">
              Abmelden
            </button>
          </p>
        ) : showLogin ? (
          <div className="flex flex-col gap-3 items-start w-full">
            <p className="text-body-sm text-text-primary">
              Für diese E-Mail-Adresse existiert bereits ein Konto — bitte einloggen, um fortzufahren.
            </p>
            <div className="flex flex-col sm:flex-row gap-3 items-start sm:items-end w-full sm:w-auto">
              <FormField
                label="E-Mail-Adresse"
                type="email"
                value={loginEmail}
                onChange={(e) => setLoginEmail(e.target.value)}
                autoComplete="email"
                wrapperClassName="w-full sm:w-56"
              />
              <FormField
                label="Passwort"
                type="password"
                value={loginPassword}
                onChange={(e) => setLoginPassword(e.target.value)}
                autoComplete="current-password"
                wrapperClassName="w-full sm:w-56"
              />
              <button
                type="button"
                onClick={handleLogin}
                disabled={loggingIn}
                className={`px-5 py-3 rounded-sm bg-brand hover:bg-brand-hover font-bold text-body-sm text-text-primary transition-colors ${loggingIn ? "opacity-70 pointer-events-none" : ""}`}
              >
                {loggingIn ? "…" : "Einloggen"}
              </button>
            </div>
            {loginError && <p className="text-label text-red-600 w-full">{loginError}</p>}
            <button
              type="button"
              onClick={() => {
                setShowLogin(false);
                setLoginError(null);
              }}
              className="text-label text-text-muted underline hover:text-text-primary transition-colors"
            >
              Andere E-Mail-Adresse verwenden
            </button>
          </div>
        ) : null}
        </div>
      </Reveal>

      <form onSubmit={handleSubmit} className="flex flex-col lg:flex-row gap-8 lg:gap-10 items-start pb-10 pt-2 px-[var(--layout-padding-x)] w-full">
        {/* Form column */}
        <div className="w-full lg:flex-1 flex flex-col gap-6 items-start min-w-0">
          {/* 1. Rechnungsadresse */}
          <Reveal className="w-full bg-bg-base border border-border rounded-md p-7 flex flex-col gap-5 items-start">
            <p
              className="font-semibold text-h-small text-text-primary"
              style={{ fontFamily: "var(--font-lora)" }}
            >
              1. Rechnungsadresse
            </p>
            <div className="flex flex-col sm:flex-row gap-4 w-full">
              <FormField label="Vorname" name="firstName" type="text" defaultValue={savedProfile?.firstName} placeholder="Max" autoComplete="given-name" required />
              <FormField label="Nachname" name="lastName" type="text" defaultValue={savedProfile?.lastName} placeholder="Mustermann" autoComplete="family-name" required />
            </div>
            {/* w-[calc(50%-0.5rem)] at sm: — exactly matches Vorname's
                actual rendered width in the 2-col row above (each half of
                a gap-4 flex row), instead of stretching full-width. */}
            <FormField
              label="E-Mail-Adresse"
              name="email"
              type="email"
              defaultValue={savedProfile?.email ?? customerEmail ?? undefined}
              placeholder="max@beispiel.de"
              autoComplete="email"
              required
              onBlur={handleEmailBlur}
              wrapperClassName="w-full sm:w-[calc(50%-0.5rem)] sm:flex-none min-w-0"
            />
            {/* Only needed for the inline-registration path — an existing
                session already has an account, no password to collect. */}
            {!customerEmail && (
              <div className="flex flex-col gap-2 w-full sm:w-[calc(50%-0.5rem)] sm:flex-none min-w-0">
                <FormField
                  label="Passwort (für dein neues Konto)"
                  name="password"
                  type="password"
                  placeholder="Mind. 8 Zeichen"
                  autoComplete="new-password"
                  required
                  minLength={8}
                  wrapperClassName="w-full"
                />
                <p className="text-label text-text-muted">
                  Mit dem Kauf legen wir automatisch ein Konto für dich an — damit du deine Bestellungen später
                  einsehen und bei Bedarf stornieren oder zurücksenden kannst.
                </p>
              </div>
            )}
            {/* Segmented control, same sm:w-[calc(50%-0.5rem)] half-row
                width as the field(s) below it — Lieferadresse keeps
                Straße und Hausnummer, Packstation swaps it out for
                Packstationnummer + Postnummer (DHL's two Packstation
                identifiers; there's no house number to give). */}
            <div className="w-full sm:w-[calc(50%-0.5rem)] flex flex-col gap-2 items-start">
              <span className="text-label text-text-muted">Lieferart</span>
              <div className="flex w-full rounded-sm border border-border overflow-hidden">
                <button
                  type="button"
                  onClick={() => setDeliveryMethod("address")}
                  aria-pressed={deliveryMethod === "address"}
                  className={`flex-1 py-3 text-body-sm font-bold transition-colors ${
                    deliveryMethod === "address"
                      ? "bg-brand text-text-primary"
                      : "text-text-muted hover:text-text-primary"
                  }`}
                >
                  Lieferadresse
                </button>
                <button
                  type="button"
                  onClick={() => setDeliveryMethod("packstation")}
                  aria-pressed={deliveryMethod === "packstation"}
                  className={`flex-1 py-3 text-body-sm font-bold border-l border-border transition-colors ${
                    deliveryMethod === "packstation"
                      ? "bg-brand text-text-primary"
                      : "text-text-muted hover:text-text-primary"
                  }`}
                >
                  Packstation
                </button>
              </div>
            </div>

            {deliveryMethod === "address" ? (
              <FormField
                label="Straße und Hausnummer"
                name="street"
                type="text"
                defaultValue={savedProfile?.street ?? undefined}
                placeholder="Musterstraße 1"
                autoComplete="street-address"
                required
                wrapperClassName="w-full sm:w-[calc(50%-0.5rem)] sm:flex-none min-w-0"
              />
            ) : (
              <div className="flex flex-col sm:flex-row gap-4 w-full">
                <FormField
                  label="Packstationnummer"
                  name="packstationNumber"
                  type="text"
                  defaultValue={savedProfile?.packstationNumber ?? undefined}
                  inputMode="numeric"
                  placeholder="123"
                  autoComplete="off"
                  required
                />
                <FormField
                  label="Postnummer"
                  name="postNumber"
                  type="text"
                  defaultValue={savedProfile?.postNumber ?? undefined}
                  inputMode="numeric"
                  placeholder="1234567"
                  autoComplete="off"
                  required
                />
              </div>
            )}
            <div className="flex flex-col sm:flex-row gap-4 w-full">
              <FormField label="PLZ" name="zip" type="text" defaultValue={savedProfile?.zip ?? undefined} placeholder="10115" autoComplete="postal-code" required />
              <FormField label="Ort" name="city" type="text" defaultValue={savedProfile?.city ?? undefined} placeholder="Berlin" autoComplete="address-level2" required />
            </div>
            <label className="flex flex-col gap-2 items-start w-full">
              <span className="text-label text-text-muted">Land</span>
              <select
                name="country"
                defaultValue={savedProfile?.country ?? "Deutschland"}
                required
                className="w-full border border-border rounded-sm px-4 py-3 text-body-sm text-text-primary outline-none focus:border-brand transition-colors bg-bg-base"
              >
                <option>Deutschland</option>
                <option>Österreich</option>
                <option>Schweiz</option>
              </select>
            </label>
            <label className="flex gap-3 items-start w-full cursor-pointer">
              <input
                type="checkbox"
                name="newsletterOptIn"
                className="size-5 shrink-0 mt-0.5 rounded-xs border border-border accent-brand"
              />
              <span className="flex flex-col gap-1 text-body-sm text-text-primary">
                Ich möchte regelmäßig Impulse &amp; Tipps per E-Mail erhalten.
                <span className="text-label text-text-muted">Du kannst dich jederzeit mit einem Klick abmelden.</span>
              </span>
            </label>
          </Reveal>

          {/* 2. Versandart */}
          <Reveal delay={0.05} className="w-full bg-bg-base border border-border rounded-md p-7 flex flex-col gap-5 items-start">
            <p
              className="font-semibold text-h-small text-text-primary"
              style={{ fontFamily: "var(--font-lora)" }}
            >
              2. Versandart
            </p>
            {shippingMethods.map((method) => {
              const methodFree = method.freeShippingThreshold !== null && subtotal >= method.freeShippingThreshold;
              return (
                <label key={method.id} className="flex items-center gap-3 w-full cursor-pointer">
                  <input
                    type="radio"
                    name="shipping"
                    checked={shippingMethodId === method.id}
                    onChange={() => setShippingMethodId(method.id)}
                    className="size-5 shrink-0 accent-brand"
                  />
                  <span className="flex-1 flex flex-col gap-0.5">
                    <span className="text-body-sm text-text-primary">{method.title}</span>
                    <span className="text-label text-text-muted">{method.description}</span>
                  </span>
                  <span className="text-body-sm text-text-primary whitespace-nowrap">
                    {methodFree ? "Kostenlos" : formatPrice(method.price)}
                  </span>
                </label>
              );
            })}
          </Reveal>

          {/* 3. Zahlungsart */}
          <Reveal delay={0.1} className="w-full bg-bg-base border border-border rounded-md p-7 flex flex-col gap-5 items-start">
            <p
              className="font-semibold text-h-small text-text-primary"
              style={{ fontFamily: "var(--font-lora)" }}
            >
              3. Zahlungsart
            </p>

            {paymentMethods.map((method) => (
              <label key={method.id} className="flex items-center gap-3 w-full cursor-pointer">
                <input
                  type="radio"
                  name="payment"
                  checked={paymentMethodId === method.id}
                  onChange={() => setPaymentMethodId(method.id)}
                  className="size-5 shrink-0 accent-brand"
                />
                <span className="flex-1 text-body-sm text-text-primary">{method.title}</span>
                <span className="flex items-center gap-2 shrink-0">
                  {method.icons.map((icon, i) => (
                    <div key={i} className="relative h-5 w-8 shrink-0">
                      <Image src={icon} alt="" fill sizes="32px" className="object-contain" />
                    </div>
                  ))}
                </span>
              </label>
            ))}

            <button
              type="submit"
              disabled={purchasing}
              className={`w-full flex items-center justify-center py-4 rounded-sm bg-brand hover:bg-brand-hover active:scale-[0.97] transition-all font-bold text-body text-text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand focus-visible:ring-offset-2 focus-visible:ring-offset-bg-base ${purchasing ? "pointer-events-none opacity-70" : ""}`}
            >
              {purchasing ? "Einen Moment…" : "Jetzt kaufen (zahlungspflichtig)"}
            </button>

            {purchaseError && (
              <p className="text-label text-red-600 text-center w-full">{purchaseError}</p>
            )}

            <p className="text-label text-text-muted text-center w-full">
              Mit dem Kauf akzeptierst du unsere{" "}
              <Link href="/agb" target="_blank" rel="noopener noreferrer" className="underline hover:text-brand">
                AGB
              </Link>{" "}
              und die{" "}
              <Link href="/datenschutz" target="_blank" rel="noopener noreferrer" className="underline hover:text-brand">
                Datenschutzerklärung
              </Link>.
            </p>

            <div className="flex gap-2 items-center justify-center w-full">
              <Image alt="" src="/icon-lock.svg" width={14} height={16} className="w-3.5 h-4" />
              <span className="text-body-sm text-text-muted">Sichere SSL-Verschlüsselung</span>
            </div>
          </Reveal>
        </div>

        {/* Sidebar */}
        <Reveal delay={0.15} className="w-full lg:w-[24.375rem] lg:shrink-0 flex flex-col gap-6 items-start">
          <div className="bg-bg-base border border-border rounded-md p-7 flex flex-col gap-5 items-start w-full">
            <p
              className="font-semibold text-h-small text-text-primary"
              style={{ fontFamily: "var(--font-lora)" }}
            >
              Deine Bestellung
            </p>

            {items.map(({ entry, product }) => (
              <div key={product.id} className="flex gap-4 items-center w-full">
                <div className="relative size-16 shrink-0 rounded-sm overflow-hidden">
                  <Image src={product.image} alt={product.name} fill sizes="64px" className="object-cover" />
                </div>
                <div className="flex-1 min-w-0 flex flex-col gap-0.5">
                  <p className="text-body-sm text-text-primary">{product.name}</p>
                  <p className="text-label text-text-muted">
                    {entry.qty} × {formatPrice(product.price)} <span>inkl. MwSt.</span>
                  </p>
                </div>
                <p className="text-body-sm text-text-primary whitespace-nowrap">{formatPrice(entry.qty * product.price)}</p>
              </div>
            ))}

            <div className="h-px bg-border w-full" />

            <div className="flex items-center w-full">
              <span className="text-body-sm text-text-primary">Zwischensumme</span>
              <span className="flex-1" />
              <span className="text-body-sm text-text-primary">{formatPrice(subtotal)}</span>
            </div>

            {totalSavings > 0 && (
              <div className="flex items-center w-full">
                <span className="text-body-sm text-success">Du sparst</span>
                <span className="flex-1" />
                <span className="font-bold text-body-sm text-success">-{formatPrice(totalSavings)}</span>
              </div>
            )}

            {/* Display-only — applied in /cart, this page has no input of
                its own (see lib/discount.ts). */}
            {discount && (
              <div className="flex items-center w-full">
                <span className="text-body-sm text-success">Rabattcode ({discount.code})</span>
                <span className="flex-1" />
                <span className="font-bold text-body-sm text-success">-{formatPrice(discountAmount)}</span>
              </div>
            )}

            <div className="flex flex-col gap-0.5 w-full">
              <div className="flex items-center w-full">
                <span className="flex items-center gap-1.5 text-body-sm text-text-primary">
                  Versand
                  <button
                    type="button"
                    onClick={() => setVersandOpen(true)}
                    className="text-text-muted hover:text-brand transition-colors"
                    aria-label="Alle Informationen zu Versandkosten und Lieferzeiten"
                  >
                    <span aria-hidden>ⓘ</span>
                  </button>
                </span>
                <span className="flex-1" />
                <span className="text-body-sm text-text-primary">
                  {shipping === 0 ? "Kostenlos" : formatPrice(shipping)}
                </span>
              </div>
              <p className="text-label text-text-muted">
                {shipping === 0 && selectedShipping?.freeShippingThreshold != null
                  ? `ab ${formatPrice(selectedShipping.freeShippingThreshold)} innerhalb Deutschlands`
                  : (selectedShipping?.description ?? "innerhalb Deutschlands")}
              </p>
              <p className="text-label text-text-muted">
                Lieferzeit {shippingSettings.totalDays.min}–{shippingSettings.totalDays.max} Werktage
              </p>
            </div>

            <div className="h-px bg-border w-full" />

            <div className="flex flex-col gap-0.5 w-full">
              <div className="flex items-center w-full">
                <span
                  className="font-semibold text-h4 text-text-primary"
                  style={{ fontFamily: "var(--font-lora)" }}
                >
                  Gesamtsumme
                </span>
                <span className="flex-1" />
                <span className="font-bold text-h-small text-text-primary">{formatPrice(total)}</span>
              </div>
              <p className="text-label text-text-muted">inkl. MwSt.</p>
            </div>
          </div>

          {/* title + description here — /cart's sidebar renders the same
              CartTrustBadges docs with title only, see CartContent.tsx. */}
          <div className="flex flex-col gap-4 items-start w-full">
            {trustBadges.map((b) => (
              <div key={b.id} className="flex gap-3 items-start w-full">
                <Image alt="" src={b.icon} width={20} height={20} className="size-5 shrink-0 object-contain mt-0.5" />
                <div className="flex-1 flex flex-col gap-0.5">
                  <p className="text-body-sm font-semibold text-text-primary">{b.title}</p>
                  <p className="text-label text-text-muted">{b.description}</p>
                </div>
              </div>
            ))}
          </div>

          {/* Newsletter hint — divider under the TEXT, not the icon, per
              this page's own Figma spec (different from /cart's version,
              which puts the divider under the icon — the two aren't meant
              to be identical, see project notes on this pattern). */}
          <div className="bg-bg-muted flex gap-5 items-start p-6 rounded-md w-full">
            <Image alt="" src="/icon-envelope-hint.png" width={40} height={32} className="h-8 w-10 shrink-0 object-contain" />
            <div className="flex flex-col gap-2 items-start flex-1 min-w-0 text-text-primary">
              {/* Conditional on the (unchecked-by-default) consent
                  checkbox above, not stated as a given — a pre-ticked
                  opt-in would be unlawful (UWG/DSGVO, see the ECJ's
                  Planet49 ruling on pre-checked consent), and this copy
                  shouldn't promise emails as if opting in were already
                  decided either. */}
              <p className="text-body-sm leading-[1.45]">
                Wenn du zustimmst, bekommst du nach deiner Bestellung regelmäßig Impulse &amp; Tipps per E-Mail.
              </p>
              <p className="text-body-sm leading-[1.45]">
                Für mehr Klarheit, Fokus und Struktur – jede Woche.
              </p>
              <div className="flex gap-1.5 items-center">
                <div className="h-[0.1875rem] w-5 bg-brand" />
                <div className="h-[0.1875rem] w-2.5 bg-brand" />
              </div>
            </div>
          </div>
        </Reveal>
      </form>

      <VersandModal open={versandOpen} onClose={() => setVersandOpen(false)} shipping={shippingSettings} />
    </>
  );
}
