// Pull-City — checkout overlay + WhatsApp confirmation. Global: window.Checkout
const WHATSAPP_NUMBER = "393270156617";

function cpPrice(v) {
  if (typeof v === "number") return Number.isFinite(v) ? v : null;
  let s = String(v == null ? "" : v).replace(/[^0-9.,]/g, "");
  if (!s) return null;
  s = s.replace(/\.(?=\d{3}(\D|$))/g, "").replace(",", ".");
  const n = parseFloat(s);
  return Number.isFinite(n) ? n : null;
}
function cpEur(n) { return "€ " + Number(n).toLocaleString("it-IT", { minimumFractionDigits: 0, maximumFractionDigits: 2 }); }

function Checkout({ open, items, onClose, onDone }) {
  const SHIP = (typeof window !== "undefined" && window.PC_SHIPPING) || [];
  const [form, setForm] = React.useState({ name: "", email: "", email2: "", phone: "", address: "", note: "", hp: "" });
  const [shipId, setShipId] = React.useState(SHIP[0] ? SHIP[0].id : "");
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState("");
  const [ref, setRef] = React.useState(null);
  const [coupon, setCoupon] = React.useState("");
  const [couponState, setCouponState] = React.useState(null); // null | {ok, discount, error}

  React.useEffect(() => {
    if (open) { setRef(null); setErr(""); setForm({ name: "", email: "", email2: "", phone: "", address: "", note: "", hp: "" }); setShipId(SHIP[0] ? SHIP[0].id : ""); setCoupon(""); setCouponState(null); }
  }, [open]);

  if (!open) return null;
  const set = (k) => (e) => setForm((f) => ({ ...f, [k]: e.target.value }));

  const FREE_SHIP_EUR = 200;
  const ship = SHIP.find((s) => s.id === shipId) || null;
  const baseCost = ship ? ship.price : 0;
  const nums = items.map((it) => cpPrice(it.price));
  const allNum = items.length > 0 && nums.every((n) => n != null);
  const itemsTotal = allNum ? nums.reduce((s, n, i) => s + n * items[i].qty, 0) : null;
  const freeShip = itemsTotal != null && itemsTotal >= FREE_SHIP_EUR;
  const shipCost = freeShip ? 0 : baseCost;
  const discount = (couponState && couponState.ok) ? couponState.discount : 0;
  const grand = itemsTotal == null ? null : Math.max(0, itemsTotal - discount + shipCost);

  async function applyCoupon() {
    const code = coupon.trim();
    if (!code) return;
    setCouponState({ busy: true });
    const r = await fetch("/api/coupon/check", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ code, subtotal: itemsTotal }) }).then((x) => x.json()).catch(() => ({ ok: false, error: "errore" }));
    setCouponState(r.ok ? { ok: true, discount: r.discount } : { ok: false, error: r.error || "codice non valido" });
  }

  async function submit(e) {
    e.preventDefault();
    setErr("");
    if (form.email.trim() !== form.email2.trim()) { setErr("Le email non coincidono"); return; }
    setBusy(true);
    try {
      const res = await fetch("/api/order", {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify({
          customer: { name: form.name, email: form.email, phone: form.phone, address: form.address },
          items: items.map((it) => ({ id: it.id, name: it.name, sub: it.sub, qty: it.qty, price: it.price })),
          shipping_id: shipId,
          note: form.note,
          coupon: (couponState && couponState.ok) ? coupon.trim() : "",
          hp: form.hp,
        }),
      });
      const data = await res.json();
      if (!res.ok || !data.ok) { setErr(data.error || "Errore invio ordine"); setBusy(false); return; }
      setRef(data.ref);
      onDone && onDone();
    } catch {
      setErr("Errore di rete. Riprova.");
    }
    setBusy(false);
  }

  const waText = encodeURIComponent(`Ciao! Ho effettuato l'ordine ${ref} su Pull-City e vorrei procedere col pagamento.`);
  const waHref = `https://wa.me/${WHATSAPP_NUMBER}?text=${waText}`;

  return (
    <div className="qv-overlay open" onClick={onClose}>
      <div className="co-modal" onClick={(e) => e.stopPropagation()}>
        <button className="qv-close" onClick={onClose} aria-label="Chiudi">
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none"><path d="M6 6l12 12M18 6L6 18" stroke="currentColor" strokeWidth="1.6" /></svg>
        </button>

        <div className="co-head">
          <img src="media/logo-header.png" alt="Pull-City TCG" />
        </div>

        {!ref ? (
          <form className="co-body" onSubmit={submit}>
            <span className="eyebrow"><span className="dot" />Checkout</span>
            <h2 className="co-title">Completa l'ordine</h2>
            <p className="co-lead">Pagamento tramite contatto diretto dopo l'ordine. Nessun pagamento online.</p>

            <div className="co-grid">
              <input required placeholder="Nome e cognome" value={form.name} onChange={set("name")} className="co-input" />
              <input required type="email" placeholder="Email" value={form.email} onChange={set("email")} className="co-input" />
              <input required type="email" placeholder="Conferma email" value={form.email2} onChange={set("email2")} className="co-input" onPaste={(e) => e.preventDefault()} />
              <input required placeholder="Telefono" value={form.phone} onChange={set("phone")} className="co-input" />
              <textarea required placeholder="Indirizzo di spedizione completo" value={form.address} onChange={set("address")} className="co-input" rows={2} />
              <textarea placeholder="Note (opzionale)" value={form.note} onChange={set("note")} className="co-input" rows={2} />
              <input tabIndex={-1} autoComplete="off" value={form.hp} onChange={set("hp")} style={{ position: "absolute", left: "-9999px", width: 1, height: 1 }} aria-hidden="true" />
            </div>

            <div className="co-section-label">Spedizione</div>
            <div className="co-ship">
              {SHIP.map((s) => (
                <label key={s.id} className={"co-ship-opt" + (shipId === s.id ? " on" : "")}>
                  <input type="radio" name="ship" value={s.id} checked={shipId === s.id} onChange={() => setShipId(s.id)} />
                  <span className="co-ship-main">
                    <span className="co-ship-name">{s.label}</span>
                    <span className="co-ship-eta">{s.eta}</span>
                  </span>
                  <span className="co-ship-price">{freeShip && s.price ? <span><s style={{ opacity: .5 }}>{cpEur(s.price)}</s> Gratis</span> : (s.price ? cpEur(s.price) : "Gratis")}</span>
                </label>
              ))}
              <p className="co-note" style={{ margin: "8px 2px 0" }}>{freeShip ? "✓ Spedizione gratuita applicata (ordine ≥ 200€)" : "Spedizione gratuita per ordini ≥ 200€"}</p>
            </div>

            <div className="co-section-label">Codice sconto</div>
            <div className="co-coupon" style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
              <input className="co-input" placeholder="Inserisci codice" value={coupon} onChange={(e) => { setCoupon(e.target.value); setCouponState(null); }} style={{ flex: 1, minWidth: 160, textTransform: "uppercase" }} />
              <button type="button" className="btn btn-ghost" onClick={applyCoupon} disabled={!coupon.trim() || (couponState && couponState.busy)}>{couponState && couponState.busy ? "…" : "Applica"}</button>
            </div>
            {couponState && couponState.ok && <p className="co-note" style={{ color: "#22c55e", margin: "6px 2px 0" }}>✓ Coupon applicato: −{cpEur(couponState.discount)}</p>}
            {couponState && couponState.ok === false && <p className="co-note" style={{ color: "#ff6b6b", margin: "6px 2px 0" }}>{couponState.error}</p>}

            <div className="co-summary">
              <div className="row"><span>Articoli ({items.reduce((s, i) => s + i.qty, 0)})</span><span>{itemsTotal == null ? "da concordare" : cpEur(itemsTotal)}</span></div>
              {discount > 0 && <div className="row"><span>Sconto {coupon.trim().toUpperCase()}</span><span style={{ color: "#22c55e" }}>−{cpEur(discount)}</span></div>}
              <div className="row"><span>Spedizione</span><span>{shipCost ? cpEur(shipCost) : "Gratis"}</span></div>
              <div className="row tot"><span>Totale</span><span>{grand == null ? "da concordare" : cpEur(grand)}</span></div>
              {itemsTotal == null && <p className="co-note">Il totale finale ti verrà confermato al contatto per il pagamento.</p>}
            </div>

            {err && <div className="co-err">{err}</div>}
            <button className="btn btn-gold co-submit" type="submit" disabled={busy}>
              {busy ? "Invio…" : "Invia ordine"}
            </button>
          </form>
        ) : (
          <div className="co-body" style={{ textAlign: "center" }}>
            <div style={{ fontSize: 40 }}>✦</div>
            <h2 className="co-title">Ordine ricevuto</h2>
            <p style={{ color: "var(--accent-2)", fontWeight: 700, fontSize: 20, fontFamily: "var(--mono)" }}>{ref}</p>
            <p className="co-lead">Ti abbiamo inviato un'email di conferma. Per completare il pagamento contattaci su WhatsApp con il riferimento dell'ordine.</p>
            <a className="btn btn-gold co-submit" href={waHref} target="_blank" rel="noopener">Contatta su WhatsApp per il pagamento</a>
            <button className="btn btn-ghost co-submit" onClick={onClose} style={{ marginTop: 10 }}>Chiudi</button>
          </div>
        )}
      </div>
    </div>
  );
}

window.Checkout = Checkout;
