// Multi-step checkout: Contact → Delivery → Review

function Checkout({ go, items, onSubmit }) {
  const [step, setStep] = React.useState(0);
  const [form, setForm] = React.useState({
    name: "", phone: "",
    zone: "", city: "", postal: "", address: "",
    email: "", notes: "",
    method: SHIPPING.defaultCourier, // courier code or "pickup"
  });

  const lines = items.map((it) => ({ ...it, p: PRODUCTS.find((x) => x.id === it.id) })).filter((l) => l.p);
  const subtotal = lines.reduce((s, l) => s + l.p.price * l.qty, 0);
  const isPickup = form.method === "pickup";
  const courier = SHIPPING.couriers.find((c) => c.code === form.method);
  const destination = form.zone === OTHER_ZONE ? form.city : form.zone;
  const shipping = isPickup ? 0 : shippingFee(form.method, form.zone); // null = to be confirmed
  const total = subtotal + (shipping || 0);
  const shippingLabel = isPickup
    ? `Ambil di toko (${SHIPPING.origin})`
    : `${courier ? courier.name : form.method} ke ${destination || "-"}`;
  const shippingText = shipping == null ? "Dikonfirmasi via WA" : shipping === 0 ? "Gratis" : formatIDR(shipping);

  const update = (k, v) => setForm({ ...form, [k]: v });

  const stepValid = () => {
    if (step === 0) return form.name && form.phone;
    if (step === 1) return isPickup || (form.zone && destination && form.address);
    return true;
  };

  const next = () => {
    if (step < 2) setStep(step + 1);
    else onSubmit({ ...form, shippingLabel, shippingFee: shipping }, total);
  };

  const labels = ["Kontak", "Pengiriman", "Tinjau"];

  return (
    <div className="screen" data-screen-label="05 Checkout">
      {/* Header */}
      <div style={{
        padding: "var(--safe-top) 20px 14px",
        borderBottom: "1px solid var(--line)",
        background: "var(--bg)",
        position: "sticky", top: 0, zIndex: 5,
      }}>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 16 }}>
          <button className="btn-icon" onClick={() => step > 0 ? setStep(step - 1) : go("cart")}>
            <Icon name="back" size={18} />
          </button>
          <div style={{ fontFamily: "var(--font-display)", fontStyle: "italic", fontSize: 20 }}>
            Checkout
          </div>
          <div style={{ width: 40 }} />
        </div>
        {/* Steps */}
        <div className="steps">
          {labels.map((l, i) => (
            <React.Fragment key={l}>
              <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 4 }}>
                <div className="step-dot" data-state={i < step ? "done" : i === step ? "active" : ""}>
                  {i < step ? <Icon name="check" size={14} /> : i + 1}
                </div>
                <div style={{
                  fontSize: 10, fontFamily: "var(--font-mono)", letterSpacing: "0.05em",
                  color: i === step ? "var(--ink)" : "var(--ink-muted)",
                  fontWeight: i === step ? 600 : 400,
                }}>{l}</div>
              </div>
              {i < labels.length - 1 && (
                <div className="step-line" data-state={i < step ? "done" : ""} style={{ marginBottom: 16 }}/>
              )}
            </React.Fragment>
          ))}
        </div>
      </div>

      {/* Body */}
      <div className="anim-fade" key={step} style={{ padding: "24px 20px 120px" }}>
        {step === 0 && (
          <div style={{ display: "grid", gap: 16 }}>
            <div>
              <div className="eyebrow" style={{ marginBottom: 12 }}>Kontak</div>
              <h2 className="h-display" style={{ fontSize: 28, margin: 0 }}>Siapa yang kami sapa?</h2>
            </div>
            <div>
              <label className="field-label">Nama lengkap</label>
              <input className="field" placeholder="Nama Anda"
                value={form.name} onChange={(e) => update("name", e.target.value)} />
            </div>
            <div>
              <label className="field-label">No. WhatsApp</label>
              <input className="field" placeholder="08123456789"
                value={form.phone} onChange={(e) => update("phone", e.target.value)} />
              <div style={{ fontSize: 11, color: "var(--ink-muted)", marginTop: 6 }}>
                Kami akan konfirmasi pesanan via WhatsApp.
              </div>
            </div>
            <div>
              <label className="field-label">Email <span style={{ color: "var(--ink-muted)" }}>(opsional)</span></label>
              <input className="field" placeholder="kamu@email.com"
                value={form.email} onChange={(e) => update("email", e.target.value)} />
            </div>
          </div>
        )}

        {step === 1 && (
          <div style={{ display: "grid", gap: 16 }}>
            <div>
              <div className="eyebrow" style={{ marginBottom: 12 }}>Alamat</div>
              <h2 className="h-display" style={{ fontSize: 28, margin: 0 }}>Kemana kami antar?</h2>
            </div>
            {/* Delivery vs pickup */}
            <div style={{ display: "grid", gap: 8, gridTemplateColumns: "1fr 1fr" }}>
              {[
                { id: "courier", label: "Kirim", desc: `Kurir dari ${SHIPPING.origin}` },
                { id: "pickup", label: "Ambil di toko", desc: `${SHIPPING.origin}, Bali · Gratis` },
              ].map((opt) => {
                const on = opt.id === "pickup" ? isPickup : !isPickup;
                return (
                  <button key={opt.id} type="button"
                    onClick={() => update("method", opt.id === "pickup" ? "pickup" : SHIPPING.defaultCourier)}
                    style={{
                      textAlign: "left", padding: 14, borderRadius: 12, cursor: "pointer",
                      background: "var(--surface)", fontFamily: "var(--font-body)", color: "var(--ink)",
                      border: on ? "1.5px solid var(--cocoa-deep)" : "1px solid var(--line)",
                    }}>
                    <div style={{ fontSize: 14, fontWeight: 600 }}>{opt.label}</div>
                    <div style={{ fontSize: 11, color: "var(--ink-muted)", marginTop: 2 }}>{opt.desc}</div>
                  </button>
                );
              })}
            </div>

            {!isPickup && (
              <>
                <div>
                  <label className="field-label">Kota tujuan</label>
                  <select className="field" value={form.zone} onChange={(e) => update("zone", e.target.value)}>
                    <option value="">Pilih…</option>
                    {SHIPPING.zones.map((z) => <option key={z}>{z}</option>)}
                    <option>{OTHER_ZONE}</option>
                  </select>
                </div>
                {form.zone === OTHER_ZONE && (
                  <div>
                    <label className="field-label">Kota / Kabupaten</label>
                    <input className="field" placeholder="Denpasar"
                      value={form.city} onChange={(e) => update("city", e.target.value)} />
                    <div style={{ fontSize: 11, color: "var(--ink-muted)", marginTop: 6 }}>
                      Ongkir ke kota ini akan kami konfirmasi via WhatsApp.
                    </div>
                  </div>
                )}
                <div>
                  <label className="field-label">Alamat lengkap</label>
                  <textarea className="field" placeholder="Nama jalan, nomor, RT/RW, patokan…"
                    value={form.address} onChange={(e) => update("address", e.target.value)} />
                </div>
                <div>
                  <label className="field-label">Kode pos <span style={{ color: "var(--ink-muted)" }}>(opsional)</span></label>
                  <input className="field" placeholder="80361"
                    value={form.postal} onChange={(e) => update("postal", e.target.value)} />
                </div>

                <div>
                  <label className="field-label">Kurir</label>
                  <div style={{ display: "grid", gap: 8 }}>
                    {SHIPPING.couriers.map((c) => {
                      const fee = shippingFee(c.code, form.zone);
                      return (
                        <label key={c.code} style={{
                          display: "flex", alignItems: "center", gap: 12,
                          padding: 14, borderRadius: 12,
                          background: "var(--surface)",
                          border: form.method === c.code ? "1.5px solid var(--cocoa-deep)" : "1px solid var(--line)",
                          cursor: "pointer",
                        }}>
                          <input type="radio" name="method" checked={form.method === c.code}
                            onChange={() => update("method", c.code)}
                            style={{ accentColor: "var(--cocoa-deep)" }} />
                          <div style={{ flex: 1 }}>
                            <div style={{ fontSize: 14, fontWeight: 600 }}>{c.name}</div>
                            <div style={{ fontSize: 11, color: "var(--ink-muted)" }}>
                              {c.code === SHIPPING.defaultCourier ? "Kurir utama · " : ""}per {SHIPPING.assumedKg} kg
                            </div>
                          </div>
                          <div style={{ fontFamily: "var(--font-mono)", fontSize: 13 }}>
                            {!form.zone ? "—" : fee == null ? "Via WA" : formatIDR(fee)}
                          </div>
                        </label>
                      );
                    })}
                  </div>
                </div>
              </>
            )}

            <div>
              <label className="field-label">Catatan untuk kurir <span style={{ color: "var(--ink-muted)" }}>(opsional)</span></label>
              <textarea className="field" placeholder="Tolong simpan di shade, jangan kena matahari…"
                value={form.notes} onChange={(e) => update("notes", e.target.value)} />
            </div>
          </div>
        )}

        {step === 2 && (
          <div style={{ display: "grid", gap: 22 }}>
            <div>
              <div className="eyebrow" style={{ marginBottom: 12 }}>Tinjau</div>
              <h2 className="h-display" style={{ fontSize: 28, margin: 0 }}>Sudah benar semua?</h2>
            </div>

            {/* Items */}
            <div style={{ background: "var(--surface)", border: "1px solid var(--line)", borderRadius: "var(--r-lg)", padding: 16 }}>
              <div className="eyebrow" style={{ marginBottom: 10 }}>Pesanan</div>
              {lines.map((l) => (
                <div key={l.id} style={{ display: "flex", justifyContent: "space-between", padding: "8px 0", fontSize: 14 }}>
                  <div>
                    <div style={{ fontWeight: 500 }}>{l.p.name} <span style={{ color: "var(--ink-muted)" }}>× {l.qty}</span></div>
                    <div style={{ fontSize: 11, color: "var(--ink-muted)" }}>{l.p.weight}</div>
                  </div>
                  <div style={{ fontFamily: "var(--font-mono)" }}>{formatIDR(l.p.price * l.qty)}</div>
                </div>
              ))}
              <hr className="hr-dot" style={{ margin: "10px 0" }} />
              <div style={{ display: "flex", justifyContent: "space-between", fontSize: 13, color: "var(--ink-soft)" }}>
                <span>Subtotal</span>
                <span style={{ fontFamily: "var(--font-mono)" }}>{formatIDR(subtotal)}</span>
              </div>
              <div style={{ display: "flex", justifyContent: "space-between", fontSize: 13, color: "var(--ink-soft)", marginTop: 4 }}>
                <span>Pengiriman</span>
                <span style={{ fontFamily: "var(--font-mono)" }}>{shippingText}</span>
              </div>
              <hr className="hr-dot" style={{ margin: "10px 0" }} />
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
                <span style={{ fontFamily: "var(--font-display)", fontStyle: "italic", fontSize: 20 }}>Total</span>
                <span style={{ fontFamily: "var(--font-mono)", fontSize: 18, fontWeight: 700 }}>{formatIDR(total)}</span>
              </div>
            </div>

            {/* Recap */}
            <div style={{ background: "var(--surface)", border: "1px solid var(--line)", borderRadius: "var(--r-lg)", padding: 16 }}>
              <div className="eyebrow" style={{ marginBottom: 10 }}>Detail</div>
              <div style={{ display: "grid", gap: 10, fontSize: 13 }}>
                <div>
                  <div style={{ color: "var(--ink-muted)", fontSize: 11, fontFamily: "var(--font-mono)", letterSpacing: "0.05em" }}>NAMA</div>
                  <div>{form.name || "—"}</div>
                </div>
                <div>
                  <div style={{ color: "var(--ink-muted)", fontSize: 11, fontFamily: "var(--font-mono)", letterSpacing: "0.05em" }}>WHATSAPP</div>
                  <div>{form.phone || "—"}</div>
                </div>
                <div>
                  <div style={{ color: "var(--ink-muted)", fontSize: 11, fontFamily: "var(--font-mono)", letterSpacing: "0.05em" }}>ALAMAT</div>
                  <div>{isPickup ? `Ambil di toko, ${SHIPPING.origin}` : `${form.address || "—"}, ${destination || "—"} ${form.postal}`}</div>
                </div>
                <div>
                  <div style={{ color: "var(--ink-muted)", fontSize: 11, fontFamily: "var(--font-mono)", letterSpacing: "0.05em" }}>METODE</div>
                  <div>{shippingLabel}</div>
                </div>
              </div>
            </div>

            <div style={{
              padding: 14, background: "var(--bg-alt)",
              borderRadius: 12, fontSize: 12, color: "var(--ink-soft)",
              display: "flex", gap: 10, alignItems: "flex-start",
            }}>
              <Icon name="leaf" size={16} />
              <div>
                Pesanan akan dikirim via WhatsApp untuk konfirmasi. Pembayaran dilakukan saat barang sampai atau via transfer.
              </div>
            </div>
          </div>
        )}
      </div>

      {/* Bottom */}
      <div style={{
        position: "sticky", bottom: 0,
        background: "var(--bg)", borderTop: "1px solid var(--line)",
        padding: "14px 20px 18px",
      }}>
        <button className="btn btn-primary" onClick={next} disabled={!stepValid()}
          style={{ opacity: stepValid() ? 1 : 0.4 }}>
          {step === 2 ? <><Icon name="wa" size={16} /> Kirim pesanan via WhatsApp</> : <>Lanjut <Icon name="chevron" size={14} /></>}
        </button>
      </div>
    </div>
  );
}

window.Checkout = Checkout;
