/* Sentosa Marketplace - Buyer Portal: My bookings, eTickets, revalidation
   S/No. 3   Comprehensive inventory tracking (purchase history, payment method, transaction status,
             order listings, validity status, redemption status, revalidation options, reservation status)
   S/No. 4   Automated redemption tracking with date/time stamps
   S/No. 16-20 Revalidation - SnApp is source of truth for eligibility, grace period and fee;
             the B2B Marketplace surfaces and enforces it, and processes the fee payment (Reply 4 Q4, Q26)
   S/No. 132 Quick reorder */

const BOOKING_TONE = { Confirmed: "success", "Partially redeemed": "info", Completed: "neutral", Revalidated: "warning" };

/* order ref | product | redemption | total | status | chevron
   Widest status label is "Partially redeemed", so the status track is sized for it
   and every row aligns regardless of which badge it carries. */
const BOOKING_COLS = "210px minmax(0,1fr) 168px 128px 172px 18px";

function BookingsScreen({ onOpen, onReorder }) {
  const [tab, setTab] = React.useState("all");
  const tabs = [["all", "All orders"], ["active", "Active"], ["completed", "Completed"]];
  const rows = window.BOOKINGS.filter(b =>
    tab === "all" ? true : tab === "active" ? ["Confirmed", "Partially redeemed"].includes(b.status) : ["Completed", "Revalidated"].includes(b.status));

  return (
    <div style={{ maxWidth: "var(--maxw)", margin: "0 auto", padding: "24px 24px 8px" }}>
      <h1 style={{ fontSize: "1.8rem", marginBottom: 6 }}>My bookings</h1>
      <p className="caption" style={{ marginBottom: 20 }}>
        Every order placed by your organisation, with live validity and redemption status synchronised from the SnApp Ticketing System.
      </p>

      <div style={{ display: "flex", gap: 6, marginBottom: 18, borderBottom: "1px solid var(--border)" }}>
        {tabs.map(([k, label]) => (
          <button key={k} onClick={() => setTab(k)}
            style={{ background: "none", border: 0, cursor: "pointer", fontFamily: "var(--font-sans)", fontSize: 14.5,
              fontWeight: tab === k ? 600 : 500, color: tab === k ? "var(--fg1)" : "var(--fg2)", padding: "10px 14px",
              borderBottom: tab === k ? "2px solid var(--action)" : "2px solid transparent", marginBottom: -1 }}>{label}</button>
        ))}
      </div>

      {/* Column header, on the same tracks as the rows */}
      <div className="sm-bookings-head" style={{ display: "grid", gridTemplateColumns: BOOKING_COLS, gap: 20,
        padding: "0 21px 10px", fontSize: 11.5, fontWeight: 600, letterSpacing: ".05em",
        textTransform: "uppercase", color: "var(--fg3)" }}>
        <span>Order</span>
        <span>Product</span>
        <span>Redemption</span>
        <span style={{ textAlign: "right" }}>Total</span>
        <span>Status</span>
        <span></span>
      </div>

      <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
        {rows.map(b => {
          const pct = Math.round((b.tickets.redeemed / b.tickets.issued) * 100);
          return (
            <Card key={b.ref} pad={0} hover onClick={() => onOpen(b)}>
              {/* Fixed grid tracks so every row lines up. A flex row let the status badge,
                  whose width varies with its label, push the other columns around. */}
              <div className="sm-bookings-row" style={{ padding: "16px 20px", display: "grid", alignItems: "center", gap: 20,
                gridTemplateColumns: BOOKING_COLS }}>
                <div style={{ minWidth: 0 }}>
                  <div style={{ fontFamily: "var(--font-mono)", fontWeight: 700, fontSize: 15 }}>{b.ref}</div>
                  <div style={{ fontSize: 12.5, color: "var(--fg2)", marginTop: 2 }}>Placed {b.placed} · {b.method}</div>
                </div>
                <div style={{ minWidth: 0 }}>
                  <div style={{ fontSize: 14.5, fontWeight: 600, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{b.lines[0].name}{b.lines.length > 1 && <span style={{ color: "var(--fg2)", fontWeight: 400 }}> +{b.lines.length - 1} more</span>}</div>
                  <div style={{ fontSize: 12.5, color: "var(--fg2)", marginTop: 2 }}>Travel date {b.travel} · {b.pax} pax</div>
                </div>
                <div style={{ minWidth: 0 }}>
                  <div style={{ fontSize: 12, color: "var(--fg2)", marginBottom: 5 }}>Redemption {b.tickets.redeemed}/{b.tickets.issued}</div>
                  <div style={{ height: 7, background: "var(--neutral-100)", borderRadius: 999, overflow: "hidden" }}>
                    <div style={{ width: `${pct}%`, height: "100%", background: pct === 100 ? "var(--success)" : "var(--action)" }}></div>
                  </div>
                </div>
                <div style={{ textAlign: "right", fontWeight: 700, fontSize: 15.5, fontVariantNumeric: "tabular-nums" }}>S${b.total.toLocaleString(undefined, { minimumFractionDigits: 2 })}</div>
                <div style={{ justifySelf: "start" }}><Badge tone={BOOKING_TONE[b.status]}>{b.status}</Badge></div>
                <Icon name="chevron-right" size={18} color="var(--fg3)" />
              </div>
            </Card>
          );
        })}
      </div>
    </div>
  );
}

function BookingDetailScreen({ b, onBack, onRevalidate, onReorder, revalidated }) {
  const [invoice, setInvoice] = React.useState(false);
  const pct = Math.round((b.tickets.redeemed / b.tickets.issued) * 100);
  const expiring = b.status === "Partially redeemed";
  return (
    <div style={{ maxWidth: "var(--maxw)", margin: "0 auto", padding: "24px 24px 8px" }}>
      <Breadcrumb items={[{ label: "My bookings", onClick: onBack }, { label: b.ref }]} />
      <div style={{ display: "flex", alignItems: "flex-start", gap: 16, flexWrap: "wrap", marginBottom: 22 }}>
        <div style={{ flex: 1, minWidth: 260 }}>
          <h1 style={{ fontSize: "1.8rem", marginBottom: 6 }}>Order {b.ref}</h1>
          <p className="caption" style={{ margin: 0 }}>Placed {b.placed} · travel date {b.travel} · paid by {b.method}</p>
        </div>
        <Badge tone={revalidated ? "warning" : BOOKING_TONE[b.status]}>{revalidated ? "Revalidated" : b.status}</Badge>
        <Btn size="sm" variant="secondary" icon="rotate-ccw" onClick={onReorder}>Reorder</Btn>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 340px", gap: 26, alignItems: "start" }}>
        <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
          {/* Line items */}
          <Card pad={0}>
            <div style={{ padding: "14px 18px", borderBottom: "1px solid var(--border)", fontWeight: 600 }}>Items</div>
            {b.lines.map((l, i) => (
              <div key={i} style={{ display: "flex", justifyContent: "space-between", gap: 16, padding: "13px 18px", borderBottom: i < b.lines.length - 1 ? "1px solid var(--border)" : 0 }}>
                <div>
                  <div style={{ fontSize: 14.5, fontWeight: 600 }}>{l.name}</div>
                  <div style={{ fontSize: 12.5, color: "var(--fg2)" }}>{l.partner} · {l.qty} × S${l.unit.toFixed(2)}</div>
                </div>
                <div style={{ fontWeight: 600 }}>S${(l.qty * l.unit).toLocaleString(undefined, { minimumFractionDigits: 2 })}</div>
              </div>
            ))}
          </Card>

          {/* Validity & redemption - S/No. 3, 4 */}
          <Card pad={20}>
            <div style={{ fontWeight: 600, fontSize: 16, marginBottom: 4 }}>Validity &amp; redemption</div>
            <p className="caption" style={{ marginBottom: 16 }}>Redemption status updates automatically with date and time stamps as tickets are validated at the gate.</p>
            <div style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 14, marginBottom: 18 }}>
              {[["Issued", b.tickets.issued, "ticket"], ["Redeemed", b.tickets.redeemed, "check-circle"], ["Unredeemed", b.tickets.issued - b.tickets.redeemed, "clock"]].map(([l, v, ic]) => (
                <div key={l} style={{ padding: 14, border: "1px solid var(--border)", borderRadius: "var(--radius-md)" }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 7, fontSize: 12.5, color: "var(--fg2)" }}><Icon name={ic} size={15} color="var(--fg3)" />{l}</div>
                  <div style={{ fontSize: 22, fontWeight: 700, marginTop: 5 }}>{v}</div>
                </div>
              ))}
            </div>
            <div style={{ height: 8, background: "var(--neutral-100)", borderRadius: 999, overflow: "hidden", marginBottom: 8 }}>
              <div style={{ width: `${pct}%`, height: "100%", background: pct === 100 ? "var(--success)" : "var(--action)" }}></div>
            </div>
            <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12.5, color: "var(--fg2)" }}>
              <span>{pct}% redeemed</span>
              <span>Valid until {revalidated ? "24 Jan 2027" : "24 Oct 2026"}{revalidated && <strong style={{ color: "var(--warning)" }}> · extended</strong>}</span>
            </div>
          </Card>

          {/* Revalidation - S/No. 16-20 */}
          {expiring && (
            <Card pad={20} style={{ borderColor: revalidated ? "var(--success)" : "var(--warning)" }}>
              <div style={{ display: "flex", alignItems: "flex-start", gap: 12 }}>
                <Icon name={revalidated ? "check-circle" : "alert-triangle"} size={22} color={revalidated ? "var(--success)" : "var(--warning)"} style={{ marginTop: 1 }} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontWeight: 600, fontSize: 15.5 }}>{revalidated ? "Revalidation complete" : "Revalidation available"}</div>
                  {revalidated ? (
                    <p style={{ fontSize: 13.5, color: "var(--fg2)", lineHeight: 1.55, margin: "5px 0 0" }}>
                      {b.tickets.issued - b.tickets.redeemed} unredeemed tickets extended to <strong style={{ color: "var(--fg1)" }}>24 Jan 2027</strong>.
                      Updated validity and new QR codes have been synchronised to the SnApp Ticketing System, and the fee is recorded in the revalidation tracking report.
                    </p>
                  ) : (
                    <>
                      <p style={{ fontSize: 13.5, color: "var(--fg2)", lineHeight: 1.55, margin: "5px 0 12px" }}>
                        {b.tickets.issued - b.tickets.redeemed} unredeemed tickets expire on 24 Oct 2026. This product is enabled for revalidation -
                        eligibility, grace period and fee are configured in SnApp and enforced here.
                      </p>
                      <div style={{ display: "flex", gap: 20, flexWrap: "wrap", fontSize: 13, marginBottom: 14 }}>
                        <span><span style={{ color: "var(--fg2)" }}>Extension</span> <strong>90 days</strong></span>
                        <span><span style={{ color: "var(--fg2)" }}>Fee</span> <strong>S$2.00 per ticket</strong></span>
                        <span><span style={{ color: "var(--fg2)" }}>Payable</span> <strong>S${((b.tickets.issued - b.tickets.redeemed) * 2).toFixed(2)}</strong></span>
                      </div>
                      <Btn variant="primary" icon="refresh-cw" onClick={onRevalidate}>Request revalidation</Btn>
                    </>
                  )}
                </div>
              </div>
            </Card>
          )}

          {/* eTickets */}
          <Card pad={20}>
            <div style={{ fontWeight: 600, fontSize: 16, marginBottom: 4 }}>eTickets</div>
            <p className="caption" style={{ marginBottom: 16 }}>Distributed to your organisation and its authorised sub-users. QR codes are issued by the SnApp Ticketing System.</p>
            <TicketStub product={{ name: b.lines[0].name, partner: b.lines[0].partner }} serial={`${b.ref}-0001`} />
            <div style={{ display: "flex", gap: 10, marginTop: 16, flexWrap: "wrap" }}>
              <Btn size="sm" variant="secondary" icon="download"
                onClick={() => window.toast(`${b.tickets.issued} eTickets downloaded`, "success", `${b.ref}-etickets.pdf · issued via SnApp`)}>
                Download all ({b.tickets.issued})</Btn>
              <Btn size="sm" variant="secondary" icon="file-text" onClick={() => setInvoice(true)}>GST tax invoice</Btn>
            </div>
          </Card>
        </div>

        {/* Side */}
        <div style={{ display: "flex", flexDirection: "column", gap: 16, position: "sticky", top: 96 }}>
          <Card pad={20}>
            <div style={{ fontWeight: 600, fontSize: 15, marginBottom: 14 }}>Order summary</div>
            <div style={{ display: "flex", flexDirection: "column", gap: 9, fontSize: 14 }}>
              <Row l="Subtotal" r={`S$${b.total.toLocaleString(undefined, { minimumFractionDigits: 2 })}`} />
              <Row l="GST" r="Excluded" sub />
              <Row l="Payment method" r={b.method} sub />
              <Row l="Transaction status" r="Settled" sub />
            </div>
            <div style={{ borderTop: "1px solid var(--border)", marginTop: 12, paddingTop: 12, display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
              <span style={{ fontWeight: 600 }}>Total paid</span>
              <span style={{ fontSize: 20, fontWeight: 700 }}>S${b.total.toLocaleString(undefined, { minimumFractionDigits: 2 })}</span>
            </div>
          </Card>

          <Card pad={20}>
            <div style={{ fontWeight: 600, fontSize: 15, marginBottom: 12 }}>Authorised sub-users</div>
            {b.tickets.subusers.length === 0
              ? <p className="caption" style={{ margin: 0 }}>No sub-users on this order.</p>
              : <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                  {b.tickets.subusers.map(u => (
                    <div key={u} style={{ display: "flex", alignItems: "center", gap: 9, fontSize: 13.5 }}>
                      <Icon name="user-check" size={16} color="var(--success)" />{u}
                    </div>
                  ))}
                </div>}
          </Card>

          <Card pad={20}>
            <div style={{ fontWeight: 600, fontSize: 15, marginBottom: 12 }}>Correspondence</div>
            <div style={{ display: "flex", flexDirection: "column", gap: 11, fontSize: 13 }}>
              {[["Order confirmation sent", b.placed], ["eTickets released to sub-users", b.placed], ["Expiry reminder scheduled", "24 Sep 2026"]].map(([t, d]) => (
                <div key={t} style={{ display: "flex", gap: 9 }}>
                  <Icon name="mail" size={15} color="var(--fg3)" style={{ marginTop: 2 }} />
                  <div><div style={{ fontWeight: 500 }}>{t}</div><div style={{ color: "var(--fg2)", fontSize: 12 }}>{d}</div></div>
                </div>
              ))}
            </div>
          </Card>
        </div>
      </div>

      <TaxInvoiceModal open={invoice} onClose={() => setInvoice(false)}
        items={b.lines.map(l => ({ id: l.name, name: l.name, qty: l.qty, trade: l.unit }))}
        total={b.total} method={b.method} />
    </div>
  );
}

/* Revalidation payment step - B2B processes the fee (Reply 4 Q26) */
function RevalidationScreen({ b, onBack, onDone }) {
  const qty = b.tickets.issued - b.tickets.redeemed;
  const fee = qty * 2;
  const [method, setMethod] = React.useState("ewallet");
  return (
    <div style={{ maxWidth: 720, margin: "0 auto", padding: "32px 24px 8px" }}>
      <Breadcrumb items={[{ label: "My bookings", onClick: onBack }, { label: b.ref, onClick: onBack }, { label: "Revalidation" }]} />
      <h1 style={{ fontSize: "1.7rem", marginBottom: 6 }}>Request revalidation</h1>
      <p className="caption" style={{ marginBottom: 22 }}>
        Extending validity for {qty} unredeemed tickets on order {b.ref}. Eligibility and fee are configured in SnApp; the fee is processed here and recorded in the financial sub-ledger.
      </p>

      <Card pad={0} style={{ marginBottom: 16 }}>
        {[["Product", b.lines[0].name], ["Unredeemed tickets", String(qty)], ["Current expiry", "24 Oct 2026"],
          ["Extension", "90 days"], ["New expiry", "24 Jan 2027"], ["Fee per ticket", "S$2.00"]].map(([k, v]) => (
          <div key={k} style={{ display: "flex", justifyContent: "space-between", padding: "12px 18px", borderBottom: "1px solid var(--border)", fontSize: 14.5 }}>
            <span style={{ color: "var(--fg2)" }}>{k}</span><span style={{ fontWeight: 600 }}>{v}</span>
          </div>
        ))}
        <div style={{ display: "flex", justifyContent: "space-between", padding: "14px 18px", fontSize: 16 }}>
          <span style={{ fontWeight: 600 }}>Total revalidation fee</span><strong>S${fee.toFixed(2)}</strong>
        </div>
      </Card>

      <Card pad={20} style={{ marginBottom: 18 }}>
        <div style={{ fontWeight: 600, marginBottom: 12 }}>Pay the revalidation fee</div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
          {[["ewallet", "Island eWallet", "wallet", "Balance S$24,180.50"], ["paynow", "PayNow", "qr-code", "Dynamic QR"]].map(([k, label, ic, sub]) => {
            const sel = method === k;
            return (
              <button key={k} onClick={() => setMethod(k)} aria-pressed={sel}
                style={{ display: "flex", alignItems: "center", gap: 10, padding: "13px 14px", textAlign: "left", cursor: "pointer",
                  border: `1.5px solid ${sel ? "var(--orange-700)" : "var(--border)"}`, borderRadius: "var(--radius-md)",
                  background: sel ? "var(--orange-50)" : "#fff", fontFamily: "var(--font-sans)" }}>
                <Icon name={ic} size={19} color={sel ? "var(--orange-900)" : "var(--fg2)"} />
                <span><span style={{ display: "block", fontSize: 14, fontWeight: 600 }}>{label}</span>
                  <span style={{ display: "block", fontSize: 12, color: "var(--fg2)" }}>{sub}</span></span>
              </button>
            );
          })}
        </div>
        {method === "paynow" && <div style={{ marginTop: 16 }}><PayNowPanel amount={fee} /></div>}
      </Card>

      <div style={{ display: "flex", gap: 12 }}>
        <Btn variant="primary" icon="check" onClick={onDone}>Confirm and pay S${fee.toFixed(2)}</Btn>
        <Btn variant="ghost" onClick={onBack}>Cancel</Btn>
      </div>
    </div>
  );
}

Object.assign(window, { BookingsScreen, BookingDetailScreen, RevalidationScreen });
