/* Real checkout: contact + address → shipping method → payment → confirmation.
   Reusable for a direct shop order and for the Etsy "Print it" balance.
   props: lineItem {title, sub, design}, subtotal, credit (already paid), entry, bp, onClose, onPlaced(order) */
const { useState: useStateCk, useEffect: useEffectCk } = React;
const { PS_DATA: CK } = window;

const CK_STEPS = [["address", "Details"], ["shipping", "Delivery"], ["payment", "Payment"]];

function Field({ label, value, set, span, ...props }) {
  return (
    <label style={{ display: "block", gridColumn: span ? "1 / -1" : "auto" }}>
      <span style={{ fontSize: 11.5, fontWeight: 700, color: "var(--ink-2)", display: "block", marginBottom: 5 }}>{label}</span>
      <input value={value} onChange={e => set(e.target.value)} {...props}
        style={{ width: "100%", padding: "11px 12px", border: "1.5px solid var(--line-2)", borderRadius: "var(--r-sm)", background: "var(--card)", color: "var(--ink)", fontSize: 14.5, outline: "none" }}
        onFocus={e => e.target.style.borderColor = "var(--clay)"} onBlur={e => e.target.style.borderColor = "var(--line-2)"} />
    </label>
  );
}

function fmt(n) { return "$" + n; }

function CheckoutFlow({ lineItem, subtotal, credit = 0, entry, bp, onClose, onPlaced }) {
  const mobile = bp === "mobile";
  const [step, setStep] = useStateCk("address");
  const [done, setDone] = useStateCk(null);
  const [busy, setBusy] = useStateCk(false);
  const [err, setErr] = useStateCk("");

  const [f, setF] = useStateCk({
    name: entry && entry.buyer && entry.buyer !== "Guest" ? entry.buyer : "",
    email: "", addr: "", city: "", postal: "", country: "GE",
    method: "std", card: "", exp: "", cvc: "",
  });
  const up = patch => { setF(s => ({ ...s, ...patch })); setErr(""); };

  useEffectCk(() => {
    const onKey = e => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, []);

  const q = CK.quote(subtotal, f.country, f.method, credit);
  const idx = CK_STEPS.findIndex(s => s[0] === step);

  const next = () => {
    setErr("");
    if (step === "address") {
      if (!f.name.trim()) return setErr("Please enter your name.");
      if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(f.email)) return setErr("Enter a valid email.");
      if (!f.addr.trim() || !f.city.trim() || !f.postal.trim()) return setErr("Please complete your address.");
      setStep("shipping");
    } else if (step === "shipping") {
      setStep("payment");
    }
  };
  const back = () => idx === 0 ? onClose() : setStep(CK_STEPS[idx - 1][0]);

  const pay = () => {
    setErr("");
    const digits = f.card.replace(/\s/g, "");
    if (digits.length < 15) return setErr("Enter a valid card number.");
    if (!/^\d\d\s*\/\s*\d\d$/.test(f.exp)) return setErr("Expiry must be MM/YY.");
    if (f.cvc.length < 3) return setErr("Enter the 3-digit CVC.");
    setBusy(true);
    setTimeout(() => {
      const base = CK.makeOrder(lineItem.design, entry);
      const order = CK.saveOrder({
        ...base, status: "submitted",
        kind: entry.mode === "etsy" ? "print" : "shop",
        source: entry.mode === "etsy" ? "print" : "shop",
        product: lineItem.title, price: q.total,
        buyer: f.name, email: f.email,
        ship: { addr: f.addr, city: f.city, postal: f.postal, country: f.country, method: q.method.label, eta: q.method.eta },
        totals: { subtotal: q.subtotal, ship: q.ship, tax: q.tax, credit: q.credit, total: q.total },
      });
      setBusy(false);
      if (onPlaced) onPlaced(order);
      setDone(order);
    }, 900);
  };

  const Shell = ({ children, footer }) => (
    <div onClick={onClose} style={{ position: "absolute", inset: 0, zIndex: 60, display: "flex", alignItems: mobile ? "flex-end" : "center", justifyContent: "center", padding: mobile ? 0 : 16, background: "rgba(40,28,16,.5)", backdropFilter: "blur(3px)", animation: "fadeIn .2s" }}>
      <div onClick={e => e.stopPropagation()} role="dialog" aria-modal="true"
        style={{ width: mobile ? "100%" : "min(460px,100%)", maxHeight: mobile ? "92%" : "94%", display: "flex", flexDirection: "column",
          background: "var(--card)", border: "1px solid var(--line)",
          borderRadius: mobile ? "var(--r-xl) var(--r-xl) 0 0" : "var(--r-xl)",
          boxShadow: "var(--sh-lg)", animation: (mobile ? "sheetUp" : "riseIn") + " .28s var(--ease-out)" }}>
        {children}
        {footer}
      </div>
    </div>
  );

  // ---- confirmation ----
  if (done) {
    return (
      <Shell>
        <div style={{ textAlign: "center", padding: "34px 28px 28px" }}>
          <div style={{ width: 60, height: 60, borderRadius: "50%", background: "var(--sage-tint)", color: "#4A5436", display: "flex", alignItems: "center", justifyContent: "center", margin: "0 auto 16px" }}>
            <Icon name="Check" size={32} stroke={2.4} />
          </div>
          <h2 style={{ fontFamily: "var(--serif)", fontSize: 26, fontWeight: 600, margin: "0 0 8px" }}>Order confirmed!</h2>
          <p style={{ color: "var(--ink-2)", fontSize: 14, margin: "0 0 20px", lineHeight: 1.5 }}>Thanks, {f.name.split(" ")[0] || "friend"}. We've emailed your receipt to {f.email}. Your poster ships to {f.city} via {q.method.label} ({q.method.eta}).</p>
          <div style={{ textAlign: "left", background: "var(--paper-2)", borderRadius: "var(--r-md)", padding: "14px 16px", marginBottom: 20 }}>
            <RowK k="Reference" v={done.ref} />
            <RowK k="Ships to" v={`${f.city}, ${CK.COUNTRIES?.find?.(c=>c.code===f.country)?.name || f.country}`} />
            <RowK k="Paid today" v={fmt(q.total)} />
          </div>
          <button className="btn btn-soft" style={{ width: "100%" }} onClick={onClose}><Icon name="ArrowLeft" size={16} /> Back to studio</button>
        </div>
      </Shell>
    );
  }

  // ---- header + stepper ----
  const Header = (
    <div style={{ flex: "none", display: "flex", alignItems: "center", gap: 10, padding: "15px 18px 12px", borderBottom: "1px solid var(--line)" }}>
      <button className="btn-icon btn-ghost" style={{ width: 34, height: 34, minHeight: 34 }} onClick={back}><Icon name={idx === 0 ? "X" : "ArrowLeft"} size={17} /></button>
      <div style={{ flex: 1, display: "flex", alignItems: "center", gap: 6, justifyContent: "center" }}>
        {CK_STEPS.map((s, i) => (
          <React.Fragment key={s[0]}>
            <span style={{ fontSize: 12.5, fontWeight: 700, color: i === idx ? "var(--clay-dark)" : i < idx ? "var(--ink-2)" : "var(--ink-3)" }}>{s[1]}</span>
            {i < CK_STEPS.length - 1 && <span style={{ width: 16, height: 2, borderRadius: 2, background: i < idx ? "var(--clay)" : "var(--line-2)" }} />}
          </React.Fragment>
        ))}
      </div>
      <span style={{ fontFamily: "var(--serif)", fontSize: 17, fontWeight: 600, minWidth: 44, textAlign: "right" }}>{fmt(q.total)}</span>
    </div>
  );

  const errBox = err && (
    <div style={{ display: "flex", gap: 8, alignItems: "center", padding: "9px 12px", background: "#F6E2D2", border: "1px solid #E7C2A6", borderRadius: "var(--r-sm)", color: "#8F4124", fontSize: 12.5, fontWeight: 600, margin: "0 0 14px" }}>
      <Icon name="TriangleAlert" size={14} /> {err}
    </div>
  );

  const Body = (
    <div className="scroll-y" style={{ flex: 1, minHeight: 0, overflowY: "auto", padding: "18px 20px" }}>
      {/* line item */}
      <div style={{ display: "flex", gap: 13, alignItems: "center", padding: "10px 12px", background: "var(--paper-2)", borderRadius: "var(--r-md)", marginBottom: 18 }}>
        <div style={{ flex: "none" }}><Poster d={lineItem.design} maxH={64} maxW={64 * (CK.SIZES.find(s=>s.id===lineItem.design.size)||{ratio:.75}).ratio} shadow={false} /></div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontWeight: 700, fontSize: 14, color: "var(--ink)" }}>{lineItem.title}</div>
          <div style={{ fontSize: 12, color: "var(--ink-3)" }}>{lineItem.sub}</div>
        </div>
        <span style={{ fontWeight: 700, fontSize: 14.5 }}>{fmt(subtotal)}</span>
      </div>

      {errBox}

      {step === "address" && (
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
          <Field label="Full name" value={f.name} set={v => up({ name: v })} span placeholder="Anna Kapanadze" />
          <Field label="Email" value={f.email} set={v => up({ email: v })} span type="email" placeholder="you@email.com" />
          <Field label="Address" value={f.addr} set={v => up({ addr: v })} span placeholder="12 Rustaveli Ave" />
          <Field label="City" value={f.city} set={v => up({ city: v })} placeholder="Tbilisi" />
          <Field label="Postal code" value={f.postal} set={v => up({ postal: v })} placeholder="0108" />
          <label style={{ display: "block", gridColumn: "1 / -1" }}>
            <span style={{ fontSize: 11.5, fontWeight: 700, color: "var(--ink-2)", display: "block", marginBottom: 5 }}>Country</span>
            <select value={f.country} onChange={e => up({ country: e.target.value, method: "std" })}
              style={{ width: "100%", padding: "11px 12px", border: "1.5px solid var(--line-2)", borderRadius: "var(--r-sm)", background: "var(--card)", color: "var(--ink)", fontSize: 14.5, outline: "none", appearance: "none" }}>
              {CK.COUNTRIES.map(c => <option key={c.code} value={c.code}>{c.name}</option>)}
            </select>
          </label>
        </div>
      )}

      {step === "shipping" && (
        <div style={{ display: "flex", flexDirection: "column", gap: 11 }}>
          {CK.shipMethods(f.country).map(m => {
            const active = f.method === m.id;
            const free = m.id === "std" && subtotal >= CK.FREE_SHIP_OVER;
            return (
              <button key={m.id} onClick={() => up({ method: m.id })} className={"tile" + (active ? " is-active" : "")}
                style={{ display: "flex", alignItems: "center", gap: 13, padding: "14px 15px", border: "1.5px solid " + (active ? "var(--clay)" : "var(--line)"), textAlign: "left" }}>
                <span style={{ width: 20, height: 20, borderRadius: "50%", flex: "none", border: "2px solid " + (active ? "var(--clay)" : "var(--line-strong)"), display: "flex", alignItems: "center", justifyContent: "center" }}>
                  {active && <span style={{ width: 9, height: 9, borderRadius: "50%", background: "var(--clay)" }} />}
                </span>
                <span style={{ flex: 1 }}>
                  <span style={{ display: "block", fontWeight: 700, fontSize: 14.5, color: "var(--ink)" }}>{m.label}</span>
                  <span style={{ fontSize: 12, color: "var(--ink-3)" }}>{m.eta}</span>
                </span>
                <span style={{ fontWeight: 700, fontSize: 14, color: free ? "var(--sage)" : "var(--ink)" }}>{free ? "Free" : fmt(m.rate)}</span>
              </button>
            );
          })}
          <div style={{ display: "flex", gap: 8, alignItems: "center", padding: "9px 12px", color: "var(--ink-3)", fontSize: 12 }}>
            <Icon name="Info" size={14} /> Standard shipping is free over {fmt(CK.FREE_SHIP_OVER)}.
          </div>
        </div>
      )}

      {step === "payment" && (
        <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
            <Field label="Card number" value={f.card} set={v => up({ card: v.replace(/[^\d ]/g, "") })} span inputMode="numeric" placeholder="4242 4242 4242 4242" />
            <Field label="Expiry" value={f.exp} set={v => up({ exp: v })} placeholder="08 / 27" />
            <Field label="CVC" value={f.cvc} set={v => up({ cvc: v.replace(/\D/g, "").slice(0,4) })} inputMode="numeric" placeholder="123" />
          </div>
          <div style={{ display: "flex", gap: 8, alignItems: "center", color: "var(--ink-3)", fontSize: 12 }}>
            <Icon name="ShieldCheck" size={14} /> Demo only — no real card is charged.
          </div>
        </div>
      )}

      {/* totals (shipping & payment) */}
      {step !== "address" && (
        <div style={{ marginTop: 18, paddingTop: 14, borderTop: "1px solid var(--line)" }}>
          <RowK k="Subtotal" v={fmt(q.subtotal)} />
          <RowK k={`Shipping · ${q.method.label}`} v={q.shipFree ? "Free" : fmt(q.ship)} />
          <RowK k={q.taxRate ? `Tax (${Math.round(q.taxRate*100)}%)` : "Tax"} v={fmt(q.tax)} />
          {q.credit > 0 && <RowK k="Etsy credit" v={"−" + fmt(q.credit)} accent />}
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", paddingTop: 8 }}>
            <span style={{ fontSize: 14, fontWeight: 700 }}>Total</span>
            <span style={{ fontFamily: "var(--serif)", fontSize: 24, fontWeight: 600 }}>{fmt(q.total)}</span>
          </div>
        </div>
      )}
    </div>
  );

  const Footer = (
    <div style={{ flex: "none", padding: "14px 20px", borderTop: "1px solid var(--line)", background: "var(--card)" }}>
      {step === "payment"
        ? <button className="btn btn-primary" style={{ width: "100%" }} disabled={busy} onClick={pay}>{busy ? <><Icon name="LoaderCircle" size={18} className="spin" /> Processing…</> : <><Icon name="Lock" size={16} /> Pay {fmt(q.total)}</>}</button>
        : <button className="btn btn-primary" style={{ width: "100%" }} onClick={next}>Continue <Icon name="ArrowRight" size={17} /></button>}
    </div>
  );

  return <Shell footer={Footer}>{Header}{Body}</Shell>;
}

function RowK({ k, v, accent }) {
  return (
    <div style={{ display: "flex", justifyContent: "space-between", gap: 12, padding: "5px 0", fontSize: 13.5 }}>
      <span style={{ color: accent ? "var(--sage)" : "var(--ink-3)", fontWeight: 600 }}>{k}</span>
      <span style={{ color: accent ? "var(--sage)" : "var(--ink)", fontWeight: 700 }}>{v}</span>
    </div>
  );
}

Object.assign(window, { CheckoutFlow });
