// Checkout.jsx — przedsprzedaż kalendarza w czterech krokach:
// koszyk → dane klienta → Paczkomat na mapie → podsumowanie → płatność Stripe.
// Krok jest w adresie (?krok=…), więc przycisk Wstecz w przeglądarce cofa
// o jeden krok, a powrót ze Stripe trafia prosto do podsumowania.

const CHECKOUT_STEPS = [
  { id: "koszyk", label: "Koszyk" },
  { id: "dane", label: "Dane" },
  { id: "paczkomat", label: "Paczkomat" },
  { id: "podsumowanie", label: "Podsumowanie" },
];

function furthestAllowedStep(order) {
  if (Object.keys(validateCustomer(order)).length > 0) return 1;
  if (!order.locker?.code) return 2;
  return 3;
}

function Stepper({ current, furthest, onSelect }) {
  return (
    <ol className="zc-stepper" aria-label="Kroki zamówienia">
      {CHECKOUT_STEPS.map((step, index) => {
        const done = index < current;
        const active = index === current;
        const reachable = index <= furthest;
        return (
          <li key={step.id}>
            <button
              type="button"
              disabled={!reachable}
              aria-current={active ? "step" : undefined}
              onClick={() => reachable && onSelect(index)}
              className={`zc-step${active ? " is-active" : ""}${done ? " is-done" : ""}`}
            >
              <span className="zc-step-dot">{done ? <Icon.Check size={13} /> : index + 1}</span>
              <span className="zc-step-label">{step.label}</span>
            </button>
          </li>
        );
      })}
    </ol>
  );
}

function QtyStepper({ value, max, onChange }) {
  return (
    <div style={{ display: "inline-flex", alignItems: "center", gap: 14 }}>
      <GlassCircle size={44} ariaLabel="Mniej" disabled={value <= 1} onClick={() => onChange(value - 1)}>
        <CalIcon.Minus />
      </GlassCircle>
      <span aria-live="polite" style={{ minWidth: 28, textAlign: "center", fontSize: 22, fontWeight: 700 }}>
        {value}
      </span>
      <GlassCircle size={44} ariaLabel="Więcej" disabled={value >= max} onClick={() => onChange(value + 1)}>
        <CalIcon.Plus />
      </GlassCircle>
    </div>
  );
}

function OrderSummary({ config, order }) {
  const items = config.unitAmount * order.qty;
  const total = items + config.shippingAmount;
  const row = { display: "flex", justifyContent: "space-between", gap: 12, fontSize: 14.5 };
  return (
    <GlassPanel padding={22} radius={24}>
      <div style={{ display: "flex", gap: 14, alignItems: "center" }}>
        <img src={COVER_SRC} alt="" width="64" height="90" style={{
          width: 64, height: 90, objectFit: "cover", borderRadius: 8, boxShadow: "0 8px 24px rgba(0,0,0,0.45)",
        }}/>
        <div>
          <div style={{ fontWeight: 650, fontSize: 15, lineHeight: 1.35 }}>{config.productName}</div>
          <div style={{ marginTop: 4, fontSize: 13, color: "rgba(255,255,255,0.6)" }}>
            {order.qty} × {formatMoney(config.unitAmount)}
          </div>
        </div>
      </div>
      <div style={{ display: "grid", gap: 10, marginTop: 20, paddingTop: 18, borderTop: "1px solid rgba(255,255,255,0.12)" }}>
        <div style={row}>
          <span style={{ color: "rgba(255,255,255,0.7)" }}>Kalendarze</span>
          <span>{formatMoney(items)}</span>
        </div>
        <div style={row}>
          <span style={{ color: "rgba(255,255,255,0.7)" }}>
            Dostawa{order.locker?.code ? ` · Paczkomat ${order.locker.code}` : " do Paczkomatu"}
          </span>
          <span>{config.shippingAmount > 0 ? formatMoney(config.shippingAmount) : "gratis"}</span>
        </div>
        <div style={{ ...row, marginTop: 6, fontSize: 18, fontWeight: 700 }}>
          <span>Razem</span>
          <span>{formatMoney(total)}</span>
        </div>
      </div>
    </GlassPanel>
  );
}

function StepHeading({ title, children }) {
  return (
    <div style={{ marginBottom: 22 }}>
      <h2 style={{ margin: 0, fontSize: 24, fontWeight: 700, letterSpacing: "-0.02em" }}>{title}</h2>
      {children && (
        <p style={{ margin: "8px 0 0", fontSize: 14.5, lineHeight: 1.6, color: "rgba(255,255,255,0.65)" }}>{children}</p>
      )}
    </div>
  );
}

function StepActions({ onBack, children }) {
  return (
    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 12, marginTop: 28, flexWrap: "wrap" }}>
      {onBack ? (
        <button type="button" className="zc-link-button" onClick={onBack}>
          <CalIcon.ArrowLeft size={16} /> Wstecz
        </button>
      ) : <span />}
      {children}
    </div>
  );
}

function CartStep({ config, order, update, next }) {
  return (
    <>
      <StepHeading title="Ile kalendarzy zamawiasz?">
        Każdy kalendarz to {formatMoney(config.unitAmount)}. Dostawa do Paczkomatu kosztuje{" "}
        {formatMoney(config.shippingAmount)} za całe zamówienie.
      </StepHeading>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 18, flexWrap: "wrap" }}>
        <div>
          <div style={{ fontWeight: 650 }}>{config.productName}</div>
          <div style={{ marginTop: 4, fontSize: 13.5, color: "rgba(255,255,255,0.6)" }}>
            Maksymalnie {config.maxQty} szt. w jednym zamówieniu
          </div>
        </div>
        <QtyStepper value={order.qty} max={config.maxQty} onChange={(qty) => update({ qty })} />
      </div>
      <StepActions>
        <GlassPill active onClick={next} style={NEXT_STYLE}>Dalej: Twoje dane</GlassPill>
      </StepActions>
    </>
  );
}

function CustomerStep({ order, update, next, back }) {
  const [touched, setTouched] = React.useState(false);
  const errors = touched ? validateCustomer(order) : {};
  const submit = (event) => {
    event.preventDefault();
    setTouched(true);
    if (Object.keys(validateCustomer(order)).length === 0) next();
  };
  return (
    <form onSubmit={submit} noValidate>
      <StepHeading title="Twoje dane">
        Imię, nazwisko i telefon trafią na etykietę paczki. InPost wyśle SMS i e-mail z kodem odbioru.
      </StepHeading>
      <div style={{ display: "grid", gap: 18 }}>
        <TextField
          id="name" label="Imię i nazwisko" required autoComplete="name"
          value={order.name} onChange={(name) => update({ name })} error={errors.name}
        />
        <TextField
          id="email" label="E-mail" type="email" required autoComplete="email"
          value={order.email} onChange={(email) => update({ email })} error={errors.email}
          hint="Na ten adres wyślemy potwierdzenie zamówienia."
        />
        <TextField
          id="phone" label="Telefon komórkowy" type="tel" required autoComplete="tel"
          value={order.phone} onChange={(phone) => update({ phone })} error={errors.phone}
          placeholder="np. 600 100 200"
        />
      </div>
      <StepActions onBack={back}>
        <GlassPill active type="submit" style={NEXT_STYLE}>Dalej: wybierz Paczkomat</GlassPill>
      </StepActions>
    </form>
  );
}

function LockerStep({ order, update, next, back }) {
  return (
    <>
      <StepHeading title="Wybierz Paczkomat">
        Wyszukaj Paczkomat na mapie InPost, najbliżej domu lub pracy.
      </StepHeading>
      <PaczkomatPicker value={order.locker} onSelect={(locker) => update({ locker })} />
      <StepActions onBack={back}>
        <GlassPill active disabled={!order.locker?.code} onClick={next} style={NEXT_STYLE}>Dalej: podsumowanie</GlassPill>
      </StepActions>
    </>
  );
}

function SummaryRow({ label, onEdit, children }) {
  return (
    <div className="zc-summary-row">
      <div style={{ ...MONO_LABEL, fontSize: 10 }}>{label}</div>
      <div style={{ fontSize: 15, lineHeight: 1.55 }}>{children}</div>
      <button type="button" className="zc-link-button" onClick={onEdit}>Zmień</button>
    </div>
  );
}

function SummaryStep({ config, order, goTo, back }) {
  const [submitting, setSubmitting] = React.useState(false);
  const [error, setError] = React.useState("");
  const total = config.unitAmount * order.qty + config.shippingAmount;

  const pay = async () => {
    setSubmitting(true);
    setError("");
    try {
      const response = await fetch("/api/calendar-checkout", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          qty: order.qty,
          name: order.name,
          email: order.email,
          phone: order.phone,
          locker: order.locker,
        }),
      });
      const payload = await response.json().catch(() => ({}));
      if (!response.ok || !payload.url) {
        const fieldError = payload.fields ? Object.values(payload.fields)[0] : "";
        throw new Error(fieldError || payload.error || "Nie udało się przejść do płatności.");
      }
      window.location.assign(payload.url);
    } catch (err) {
      setError(err.message);
      setSubmitting(false);
    }
  };

  return (
    <>
      <StepHeading title="Sprawdź zamówienie">
        Po kliknięciu „Zapłać” przejdziesz do bezpiecznej płatności Stripe.
      </StepHeading>
      <div style={{ display: "grid" }}>
        <SummaryRow label="Zamówienie" onEdit={() => goTo(0)}>
          {order.qty} × {config.productName}
        </SummaryRow>
        <SummaryRow label="Odbiorca" onEdit={() => goTo(1)}>
          {order.name.trim()}<br/>
          <span style={{ color: "rgba(255,255,255,0.7)" }}>{order.email.trim()} · {formatPhone(order.phone)}</span>
        </SummaryRow>
        <SummaryRow label="Dostawa" onEdit={() => goTo(2)}>
          Paczkomat InPost {order.locker?.code}<br/>
          <span style={{ color: "rgba(255,255,255,0.7)" }}>
            {[order.locker?.line1, order.locker?.line2].filter(Boolean).join(", ")}
          </span>
        </SummaryRow>
      </div>
      <p style={{ margin: "18px 0 0", fontSize: 13.5, lineHeight: 1.6, color: "rgba(255,255,255,0.6)" }}>
        {config.shippingNote}
      </p>
      {error && (
        <div role="alert" style={{
          marginTop: 18, padding: "12px 14px", borderRadius: 14, fontSize: 14,
          background: "rgba(255,90,90,0.12)", border: "1px solid rgba(255,120,120,0.45)",
        }}>
          {error}
        </div>
      )}
      <StepActions onBack={back}>
        <GlassPill active disabled={submitting || !config.salesOpen} onClick={pay} style={{ ...CTA_STYLE, padding: "14px 28px" }}>
          {submitting ? "Przekierowuję do płatności…" : `Zapłać ${formatMoney(total)}`}
        </GlassPill>
      </StepActions>
      {!config.salesOpen && (
        <div style={{ marginTop: 12, fontSize: 13, textAlign: "right", color: "rgba(255,200,120,0.95)" }}>
          Płatności są chwilowo niedostępne. Spróbuj ponownie później.
        </div>
      )}
      <div style={{ marginTop: 14, display: "flex", gap: 8, alignItems: "center", justifyContent: "flex-end", fontSize: 12.5, color: "rgba(255,255,255,0.5)" }}>
        <CalIcon.Card size={16} /> BLIK, karta lub szybki przelew · obsługuje Stripe
      </div>
    </>
  );
}

function Checkout({ config, step, onStep, onExit }) {
  const [order, setOrder] = React.useState(loadStoredOrder);
  const furthest = furthestAllowedStep(order);
  const current = Math.min(step, furthest);

  React.useEffect(() => {
    if (current !== step) onStep(current, { replace: true });
  }, [current, step, onStep]);

  React.useEffect(() => {
    window.scrollTo({ top: 0 });
  }, [current]);

  const update = (patch) => {
    setOrder((prev) => {
      const nextOrder = { ...prev, ...patch };
      if (nextOrder.qty > config.maxQty) nextOrder.qty = config.maxQty;
      storeOrder(nextOrder);
      return nextOrder;
    });
  };

  const goTo = (index) => onStep(Math.max(0, Math.min(index, CHECKOUT_STEPS.length - 1)));
  const next = () => goTo(current + 1);
  const back = () => goTo(current - 1);
  const props = { config, order, update, next, back, goTo };

  return (
    <div className="zc-shell" style={{ paddingTop: 28, paddingBottom: 64 }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 16 }}>
        <button type="button" className="zc-link-button" onClick={onExit}>
          <CalIcon.ArrowLeft size={16} /> Kalendarz 2027
        </button>
        <img src="/kalendarz/assets/logo.webp" alt="zegrze.co" style={{ height: 20, width: "auto" }} />
      </div>

      <h1 style={{ margin: "32px 0 22px", fontSize: "clamp(28px, 5vw, 40px)", fontWeight: 700, letterSpacing: "-0.03em" }}>
        Zamówienie
      </h1>

      <Stepper current={current} furthest={furthest} onSelect={goTo} />

      <div className={`zc-checkout-grid${current === 2 ? " is-wide" : ""}`}>
        <GlassPanel className="zc-step-panel" padding={28} radius={28} style={{ minWidth: 0 }}>
          {current === 0 && <CartStep {...props} />}
          {current === 1 && <CustomerStep {...props} />}
          {current === 2 && <LockerStep {...props} />}
          {current === 3 && <SummaryStep {...props} />}
        </GlassPanel>
        {current !== 2 && (
          <aside className="zc-checkout-aside">
            <OrderSummary config={config} order={order} />
          </aside>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { CHECKOUT_STEPS, Checkout });
