// ===== Page: Beli Tiket (Multi-step flow) =====
function PageTiket() {
  const [step, setStep] = useState(1);
  const [date, setDate] = useState(() => {
    const d = new Date();
    d.setDate(d.getDate() + 2);
    return d.toISOString().split("T")[0];
  });
  const [qtys, setQtys] = useState({});
  const [buyer, setBuyer] = useState({ nama: "", email: "", phone: "" });
  const [pay, setPay] = useState("qris");
  const [toast, setToast] = useState(null);
  const [code] = useState(() => "BZ-" + Math.floor(100000 + Math.random() * 900000));

  const total = TICKETS.reduce((sum, t) => sum + (qtys[t.nama] || 0) * t.harga, 0);
  const totalQty = Object.values(qtys).reduce((a, b) => a + (b || 0), 0);

  const canNext = () => {
    if (step === 1) return totalQty > 0 && date;
    if (step === 2) return buyer.nama && buyer.email && buyer.phone;
    return true;
  };

  return (
    <>
      <PageHead
        crumb="Beranda · Beli Tiket"
        title="Beli Tiket BatamZoo"
        sub="Tiket online berlaku 14 hari dari tanggal kunjungan. Refundable sampai H-1, scan QR di gate."
      />
      <section className="section">
        <div className="container">
          <div className="steps">
            <div className={"step " + (step === 1 ? "active" : step > 1 ? "done" : "")}>
              <span className="step-n">{step > 1 ? <i className="fa-solid fa-check"></i> : "1"}</span>
              Pilih Tiket
            </div>
            <div className={"step " + (step === 2 ? "active" : step > 2 ? "done" : "")}>
              <span className="step-n">{step > 2 ? <i className="fa-solid fa-check"></i> : "2"}</span>
              Data Pengunjung
            </div>
            <div className={"step " + (step === 3 ? "active" : step > 3 ? "done" : "")}>
              <span className="step-n">{step > 3 ? <i className="fa-solid fa-check"></i> : "3"}</span>
              Pembayaran
            </div>
            <div className={"step " + (step === 4 ? "active" : "")}>
              <span className="step-n">4</span>
              Selesai
            </div>
          </div>

          <div style={{ display: "grid", gridTemplateColumns: "1.6fr 1fr", gap: 32 }} className="tiket-grid">
            <div>
              {step === 1 && <StepPilih qtys={qtys} setQtys={setQtys} date={date} setDate={setDate} />}
              {step === 2 && <StepData buyer={buyer} setBuyer={setBuyer} />}
              {step === 3 && <StepBayar pay={pay} setPay={setPay} total={total} />}
              {step === 4 && <StepSelesai code={code} date={date} qtys={qtys} buyer={buyer} total={total} />}
            </div>

            <aside>
              <div className="card" style={{ padding: 24, position: "sticky", top: 100 }}>
                <h4 style={{ fontSize: 13, color: "var(--ink-2)", letterSpacing: ".1em", marginBottom: 18 }}>RINGKASAN PESANAN</h4>
                {totalQty === 0 ? (
                  <p style={{ color: "var(--ink-2)", fontSize: 14, margin: 0 }}>Belum ada tiket dipilih.</p>
                ) : (
                  <>
                    <div style={{ marginBottom: 16, fontSize: 14 }}>
                      <div style={{ color: "var(--ink-2)", fontSize: 12, marginBottom: 4 }}>Tanggal Kunjungan</div>
                      <div style={{ fontWeight: 600 }}>{formatDate(date)}</div>
                    </div>
                    <div style={{ borderTop: "1px solid var(--line)", paddingTop: 14 }}>
                      {TICKETS.filter(t => qtys[t.nama]).map(t => (
                        <div key={t.nama} style={{ display: "flex", justifyContent: "space-between", marginBottom: 10, fontSize: 14 }}>
                          <span>{qtys[t.nama]} × {t.nama}</span>
                          <span style={{ fontWeight: 600 }}>{rupiah(qtys[t.nama] * t.harga)}</span>
                        </div>
                      ))}
                    </div>
                    <div style={{ borderTop: "1px dashed var(--line)", marginTop: 14, paddingTop: 14, display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
                      <span style={{ fontSize: 13, color: "var(--ink-2)" }}>Total</span>
                      <span style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 28, color: "var(--navy)" }}>
                        {rupiah(total)}
                      </span>
                    </div>
                  </>
                )}

                {step < 4 && (
                  <div style={{ display: "flex", gap: 10, marginTop: 24 }}>
                    {step > 1 && (
                      <button className="btn btn-ghost" style={{ flex: 1 }} onClick={() => setStep(step - 1)}><i className="fa-solid fa-arrow-left"></i> Kembali</button>
                    )}
                    {step < 3 && (
                      <button
                        className="btn btn-primary"
                        style={{ flex: 1, opacity: canNext() ? 1 : 0.5 }}
                        disabled={!canNext()}
                        onClick={() => setStep(step + 1)}
                      >
                        Lanjut →
                      </button>
                    )}
                    {step === 3 && (
                      <button
                        className="btn btn-primary"
                        style={{ flex: 1 }}
                        onClick={() => { setStep(4); setToast("Pembayaran berhasil!"); }}
                      >
                        Bayar {rupiah(total)} →
                      </button>
                    )}
                  </div>
                )}

                <div style={{
                  marginTop: 20, paddingTop: 18, borderTop: "1px solid var(--line)",
                  fontSize: 12, color: "var(--ink-2)", display: "flex", gap: 10
                }}>
                  <i className="fa-solid fa-lock" style={{ color: "var(--green)", marginTop: 2 }}></i>
                  <span>Pembayaran aman dengan enkripsi SSL. Tiket akan dikirim ke email Anda.</span>
                </div>
              </div>
            </aside>
          </div>
        </div>
      </section>

      {toast && <Toast text={toast} onDone={() => setToast(null)} />}
      <style>{`@media (max-width: 900px) { .tiket-grid { grid-template-columns: 1fr !important; } }`}</style>
    </>
  );
}

function StepPilih({ qtys, setQtys, date, setDate }) {
  return (
    <div>
      <h2 style={{ marginBottom: 8 }}>Pilih tanggal & tiket</h2>
      <p className="muted" style={{ marginBottom: 32 }}>Tiket berlaku 14 hari ke depan. Anda bisa reschedule H-1.</p>

      <div className="card" style={{ padding: 24, marginBottom: 24 }}>
        <div className="field" style={{ marginBottom: 0 }}>
          <label>Tanggal Kunjungan</label>
          <input
            type="date"
            value={date}
            min={new Date().toISOString().split("T")[0]}
            onChange={e => setDate(e.target.value)}
          />
        </div>
      </div>

      <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
        {TICKETS.map(t => (
          <div key={t.nama} className={"ticket-card" + (t.featured ? " featured" : "")}>
            {t.featured && <span className="ribbon">PALING HEMAT</span>}
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 24 }}>
              <div style={{ flex: 1 }}>
                <div style={{ display: "flex", gap: 8, marginBottom: 10 }}>
                  <span className={"chip " + (t.cat === "weekday" ? "blue" : t.cat === "weekend" ? "green" : "yellow")}>
                    {t.cat === "weekday" ? "Weekday" : t.cat === "weekend" ? "Weekend" : "Bundle"}
                  </span>
                </div>
                <h3 style={{ marginBottom: 6 }}>{t.nama}</h3>
                <p style={{ color: "var(--ink-2)", fontSize: 14, margin: 0 }}>{t.desc}</p>
                <ul className="ticket-features" style={{ marginTop: 16, marginBottom: 0 }}>
                  {t.fitur.map((f, i) => (
                    <li key={i}><i className="fa-solid fa-circle-check check" style={{color: "var(--green)", marginTop: 4}}></i>{f}</li>
                  ))}
                </ul>
              </div>
              <div style={{ textAlign: "right", minWidth: 160 }}>
                <div className="price">{rupiah(t.harga)}</div>
                {t.asli && (
                  <div style={{ textDecoration: "line-through", color: "var(--ink-2)", fontSize: 14, marginTop: 2 }}>
                    {rupiah(t.asli)}
                  </div>
                )}
                <div style={{ fontSize: 13, color: "var(--ink-2)", marginTop: 4, marginBottom: 16 }}>
                  per {t.cat === "bundle" ? "paket" : "orang"}
                </div>
                <Counter
                  value={qtys[t.nama] || 0}
                  onChange={(v) => setQtys({ ...qtys, [t.nama]: v })}
                />
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

function StepData({ buyer, setBuyer }) {
  return (
    <div>
      <h2 style={{ marginBottom: 8 }}>Data pengunjung utama</h2>
      <p className="muted" style={{ marginBottom: 32 }}>Tiket dan QR code akan dikirim ke email yang Anda isi.</p>
      <div className="card" style={{ padding: 32 }}>
        <div className="field">
          <label>Nama Lengkap *</label>
          <input
            placeholder="Sesuai KTP/Identitas"
            value={buyer.nama}
            onChange={e => setBuyer({ ...buyer, nama: e.target.value })}
          />
        </div>
        <div className="field">
          <label>Email *</label>
          <input
            type="email"
            placeholder="nama@email.com"
            value={buyer.email}
            onChange={e => setBuyer({ ...buyer, email: e.target.value })}
          />
        </div>
        <div className="field" style={{ marginBottom: 24 }}>
          <label>Nomor WhatsApp *</label>
          <input
            placeholder="081xxxxxxxxx"
            value={buyer.phone}
            onChange={e => setBuyer({ ...buyer, phone: e.target.value })}
          />
        </div>
        <div style={{
          padding: 16, background: "var(--cream-warm)",
          borderRadius: 12, fontSize: 13, color: "var(--navy-soft)",
          display: "flex", gap: 12, alignItems: "flex-start"
        }}>
          <i className="fa-solid fa-circle-info" style={{ fontSize: 16, color: "var(--blue)", marginTop: 2 }}></i>
          <span>Data ini hanya digunakan untuk pengiriman tiket dan konfirmasi kunjungan. Kami tidak membagikan ke pihak ketiga.</span>
        </div>
      </div>
    </div>
  );
}

function StepBayar({ pay, setPay, total }) {
  const methods = [
    { id: "qris", label: "QRIS", desc: "Scan dengan aplikasi e-wallet apa saja", ic: "qrcode" },
    { id: "va", label: "Virtual Account", desc: "BCA, BNI, Mandiri, BRI", ic: "building-columns" },
    { id: "card", label: "Kartu Kredit/Debit", desc: "Visa, Mastercard, JCB", ic: "credit-card" },
    { id: "ewallet", label: "E-Wallet", desc: "GoPay, OVO, DANA, ShopeePay", ic: "wallet" }
  ];
  return (
    <div>
      <h2 style={{ marginBottom: 8 }}>Metode pembayaran</h2>
      <p className="muted" style={{ marginBottom: 32 }}>Pembayaran diproses melalui gateway tersertifikasi PCI-DSS.</p>
      <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
        {methods.map(m => (
          <label key={m.id} className="card" style={{
            padding: 20, display: "flex", gap: 16, alignItems: "center", cursor: "pointer",
            borderColor: pay === m.id ? "var(--blue)" : "var(--line)",
            background: pay === m.id ? "var(--blue-soft)" : "white"
          }}>
            <input
              type="radio"
              name="pay"
              checked={pay === m.id}
              onChange={() => setPay(m.id)}
              style={{ accentColor: "var(--blue)" }}
            />
            <Icon name={m.ic} box="cream" boxSize={44} fontSize={18} style={{ borderRadius: 12 }} />
            <div style={{ flex: 1 }}>
              <div style={{ fontWeight: 700, fontSize: 16 }}>{m.label}</div>
              <div style={{ fontSize: 13, color: "var(--ink-2)" }}>{m.desc}</div>
            </div>
          </label>
        ))}
      </div>

      {pay === "qris" && (
        <div style={{
          marginTop: 24, padding: 32,
          background: "white", borderRadius: "var(--r-lg)",
          border: "1px dashed var(--blue)", textAlign: "center"
        }}>
          <div style={{
            width: 180, height: 180, margin: "0 auto 16px",
            background: `
              radial-gradient(circle, var(--navy) 30%, transparent 30%) 0 0/30px 30px,
              white
            `,
            border: "8px solid var(--navy)", borderRadius: 16,
            backgroundImage: `
              linear-gradient(45deg, var(--navy) 25%, transparent 25%),
              linear-gradient(-45deg, var(--navy) 25%, transparent 25%),
              linear-gradient(45deg, transparent 75%, var(--navy) 75%),
              linear-gradient(-45deg, transparent 75%, var(--navy) 75%)
            `,
            backgroundSize: "16px 16px",
            backgroundPosition: "0 0, 0 8px, 8px -8px, -8px 0px"
          }}></div>
          <div style={{ fontSize: 13, color: "var(--ink-2)" }}>Scan QR untuk membayar {rupiah(total)}</div>
        </div>
      )}
    </div>
  );
}

function StepSelesai({ code, date, qtys, buyer, total }) {
  return (
    <div>
      <Icon name="check" box="green-solid" boxSize={80} fontSize={32} className="ic-circle" style={{ margin: "0 auto 20px" }} />
      <h2 style={{ textAlign: "center", marginBottom: 12 }}>Pesanan berhasil!</h2>
      <p style={{ textAlign: "center", color: "var(--ink-2)", marginBottom: 32, fontSize: 16 }}>
        Tiket telah dikirim ke <strong style={{ color: "var(--navy)" }}>{buyer.email}</strong>.<br />
        Scan QR di bawah ini di gate utama BatamZoo.
      </p>

      <div className="card" style={{ padding: 40, textAlign: "center", marginBottom: 24 }}>
        <div style={{
          fontFamily: "var(--font-mono)", fontSize: 13,
          color: "var(--ink-2)", marginBottom: 12
        }}>KODE PESANAN</div>
        <div style={{
          fontFamily: "var(--font-display)", fontSize: 32,
          fontWeight: 700, letterSpacing: "0.05em", marginBottom: 28
        }}>{code}</div>
        <div style={{
          width: 200, height: 200, margin: "0 auto 24px",
          background: "var(--navy)", borderRadius: 16,
          backgroundImage: `
            linear-gradient(45deg, white 25%, transparent 25%),
            linear-gradient(-45deg, white 25%, transparent 25%),
            linear-gradient(45deg, transparent 75%, white 75%),
            linear-gradient(-45deg, transparent 75%, white 75%)
          `,
          backgroundSize: "16px 16px",
          backgroundPosition: "0 0, 0 8px, 8px -8px, -8px 0px",
          border: "8px solid var(--navy)"
        }}></div>
        <div style={{ fontSize: 14, color: "var(--ink-2)" }}>
          {formatDate(date)} · {Object.values(qtys).reduce((a, b) => a + (b || 0), 0)} tiket · {rupiah(total)}
        </div>
      </div>

      <div style={{ display: "flex", gap: 12, justifyContent: "center", flexWrap: "wrap" }}>
        <button className="btn btn-primary">Unduh PDF Tiket</button>
        <button className="btn btn-ghost">Kirim ulang ke email</button>
        <L to="beranda" className="btn btn-ghost">Kembali ke Beranda</L>
      </div>
    </div>
  );
}

function formatDate(iso) {
  const d = new Date(iso);
  return d.toLocaleDateString("id-ID", { weekday: "long", day: "numeric", month: "long", year: "numeric" });
}

Object.assign(window, { PageTiket });
