/* trips — customer-facing "My Trips": view, reschedule and cancel real bookings. */

function TripCard({ b }) {
  const { t } = useLang();
  const { cancelBooking, modifyBooking, setNotice } = useStore();
  const [mode, setMode] = React.useState(null); // null | 'details' | 'cancel' | 'modify'
  const [newDate, setNewDate] = React.useState(b.date || "");
  const [dateErr, setDateErr] = React.useState(null);
  const refund = Math.round((b.amount || 0) * (b.type === "flight" ? 0.8 : 0.9));
  const cancellable = b.status === "Confirmed";
  const today = new Date().toISOString().slice(0, 10);
  const saveModify = () => {
    if (!newDate || newDate < today) { setDateErr("trips.err.pastDate"); return; }
    modifyBooking(b.id, { date: newDate, status: "Confirmed", note: "Rescheduled" });
    setDateErr(null); setMode(null);
  };

  return (
    <div className="card" style={{ overflow: "hidden" }}>
      <div style={{ display: "flex", alignItems: "center", gap: 16, padding: "20px 24px", flexWrap: "wrap" }}>
        <div style={{ width: 46, height: 46, borderRadius: 12, background: "var(--emerald-wash)", color: "var(--emerald)", display: "grid", placeItems: "center", flexShrink: 0 }}>
          <Icon name={b.type === "hotel" ? "hotel" : b.type === "package" ? "spark" : "plane"} size={22} />
        </div>
        <div style={{ flex: 1, minWidth: 200 }}>
          <div style={{ fontWeight: 700, fontSize: 15.5 }}>{b.title}</div>
          <div className="muted" style={{ fontSize: 12.5, marginTop: 3, display: "flex", gap: 12, flexWrap: "wrap" }}>
            <span style={{ fontFamily: "monospace" }}>{b.id}</span>
            {b.date && <span><Icon name="cal" size={12} style={{ verticalAlign: "-1px" }} /> {b.date}</span>
            }<span className="chip" style={{ fontSize: 11, padding: "1px 8px" }}>{b.channel}</span>
          </div>
        </div>
        <div style={{ textAlign: "end" }}>
          <div style={{ fontWeight: 700 }}><Money value={b.amount} /></div>
          <div style={{ marginTop: 4 }}><StatusPill status={b.status} /></div>
        </div>
      </div>

      {b.refunded != null && <div style={{ padding: "0 24px 14px" }}><span className="chip chip-emerald" style={{ fontSize: 12 }}><Icon name="check" size={13} /> {t("trips.refunded", { amount: "SAR " + b.refunded.toLocaleString() })}</span></div>}

      <div style={{ display: "flex", gap: 10, padding: "0 24px 18px", flexWrap: "wrap" }}>
        <button className="btn btn-ghost btn-sm" onClick={() => setMode(mode === "details" ? null : "details")}><Icon name="info" size={14} /> {t("trips.details")}</button>
        {cancellable && b.type !== "flight" && <button className="btn btn-ghost btn-sm" onClick={() => setMode(mode === "modify" ? null : "modify")}><Icon name="cal" size={14} /> {t("trips.modify")}</button>}
        {cancellable && <button className="btn btn-ghost btn-sm" onClick={() => setMode(mode === "cancel" ? null : "cancel")} style={{ borderColor: "var(--danger)", color: "var(--danger)" }}><Icon name="x" size={14} /> {t("trips.cancel")}</button>}
      </div>

      {mode === "details" && (
        <div style={{ padding: 18, background: "var(--paper)", borderTop: "1px solid var(--line)" }}>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
            <div><span className="muted" style={{ fontSize: 12, textTransform: "uppercase", letterSpacing: ".08em" }}>{t("trips.detail.id")}</span><div style={{ fontWeight: 600, fontFamily: "monospace", marginTop: 4 }}>{b.id}</div></div>
            <div><span className="muted" style={{ fontSize: 12, textTransform: "uppercase", letterSpacing: ".08em" }}>{t("trips.detail.type")}</span><div style={{ fontWeight: 600, marginTop: 4 }}>{b.type ? b.type.charAt(0).toUpperCase() + b.type.slice(1) : "—"}</div></div>
            <div><span className="muted" style={{ fontSize: 12, textTransform: "uppercase", letterSpacing: ".08em" }}>{t("trips.detail.date")}</span><div style={{ fontWeight: 600, marginTop: 4 }}>{b.date || "—"}</div></div>
            <div><span className="muted" style={{ fontSize: 12, textTransform: "uppercase", letterSpacing: ".08em" }}>{t("trips.detail.amount")}</span><div style={{ fontWeight: 600, marginTop: 4 }}><Money value={b.amount} /></div></div>
            <div><span className="muted" style={{ fontSize: 12, textTransform: "uppercase", letterSpacing: ".08em" }}>{t("trips.detail.status")}</span><div style={{ marginTop: 4 }}><StatusPill status={b.status} /></div></div>
            <div><span className="muted" style={{ fontSize: 12, textTransform: "uppercase", letterSpacing: ".08em" }}>{t("trips.detail.channel")}</span><div style={{ fontWeight: 600, marginTop: 4 }}>{b.channel || "—"}</div></div>
            {b.note && <div style={{ gridColumn: "1/3" }}><span className="muted" style={{ fontSize: 12, textTransform: "uppercase", letterSpacing: ".08em" }}>{t("trips.detail.note")}</span><div style={{ fontWeight: 600, marginTop: 4 }}>{b.note}</div></div>}
            {b.refunded != null && <div style={{ gridColumn: "1/3" }}><span className="muted" style={{ fontSize: 12, textTransform: "uppercase", letterSpacing: ".08em" }}>{t("trips.detail.refunded")}</span><div style={{ fontWeight: 600, marginTop: 4, color: "var(--ok)" }}><Money value={b.refunded} /></div></div>}
          </div>
          <div style={{ marginTop: 14 }}><button className="btn btn-ghost btn-sm" onClick={() => setMode(null)}>{t("common.cancel")}</button></div>
        </div>
      )}

      {mode === "modify" && (
        <div style={{ padding: 18, background: "var(--paper)", borderTop: "1px solid var(--line)", display: "flex", gap: 10, alignItems: "flex-end", flexWrap: "wrap" }}>
          <div className="field" style={{ flex: 1, minWidth: 180 }}><label>{t("trips.newDate")}</label><input type="date" className="input" min={today} value={newDate} onChange={e => { setNewDate(e.target.value); setDateErr(null); }} aria-invalid={!!dateErr} />{dateErr && <div style={{ color: "var(--danger)", fontSize: 12.5, marginTop: 5 }}>{t(dateErr)}</div>}</div>
          <button className="btn btn-primary btn-sm" onClick={saveModify}>{t("trips.save")}</button>
          <button className="btn btn-ghost btn-sm" onClick={() => { setMode(null); setDateErr(null); }}>{t("common.cancel")}</button>
        </div>
      )}

      {mode === "cancel" && (
        <div style={{ padding: 18, background: "var(--danger-wash)", borderTop: "1px solid var(--line)" }}>
          <div style={{ fontWeight: 700, color: "var(--danger)", marginBottom: 4 }}>{t("trips.confirmCancel")}</div>
          <p style={{ fontSize: 13.5, color: "var(--ink-2)", marginBottom: 12 }}>{t("trips.confirmCancelBody", { amount: "SAR " + refund.toLocaleString() })}</p>
          <div style={{ display: "flex", gap: 10 }}>
            <button className="btn btn-dark btn-sm" onClick={() => { cancelBooking(b.id); setMode(null); setNotice && setNotice({ type: "ok", key: "notice.cancelled", vars: { amount: "SAR " + refund.toLocaleString() } }); }}><Icon name="x" size={14} /> {t("trips.cancel")}</button>
            <button className="btn btn-ghost btn-sm" onClick={() => setMode(null)}>{t("trips.keepIt")}</button>
          </div>
        </div>
      )}
    </div>
  );
}

function TripsPage() {
  const { t } = useLang();
  const { bookings, nav } = useStore();
  const today = new Date().toISOString().slice(0, 10);
  const upcoming = bookings.filter(b => b.status !== "Cancelled" && (!b.date || b.date >= today));
  const past = bookings.filter(b => b.status === "Cancelled" || (b.date && b.date < today));

  return (
    <main style={{ paddingTop: 96, background: "var(--paper)", minHeight: "100vh" }}>
      <div className="wrap" style={{ paddingTop: 36, paddingBottom: 80, maxWidth: 920 }}>
        <span className="eyebrow">{t("nav.trips")}</span>
        <h1 style={{ fontFamily: "var(--serif)", fontSize: 42, fontWeight: 600, marginTop: 14 }}>{t("trips.title")}</h1>
        <p className="lead" style={{ marginTop: 12 }}>{t("trips.sub")}</p>

        {bookings.length === 0 ? (
          <div className="card card-pad center" style={{ marginTop: 36, padding: 56 }}>
            <Icon name="bag" size={36} color="var(--ink-3)" />
            <p className="muted" style={{ marginTop: 14, marginBottom: 18 }}>{t("trips.empty")}</p>
            <button className="btn btn-primary" onClick={() => nav("flights")}>{t("trips.browse")} <Icon name="arrow" size={16} className="flip-rtl" /></button>
          </div>
        ) : (
          <div style={{ marginTop: 34, display: "flex", flexDirection: "column", gap: 32 }}>
            {upcoming.length > 0 && (
              <section>
                <h2 style={{ fontFamily: "var(--serif)", fontSize: 22, fontWeight: 600, marginBottom: 16 }}>{t("trips.upcoming")} <span className="muted" style={{ fontSize: 15 }}>· {upcoming.length}</span></h2>
                <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>{upcoming.map(b => <TripCard key={b.id} b={b} />)}</div>
              </section>
            )}
            {past.length > 0 && (
              <section>
                <h2 style={{ fontFamily: "var(--serif)", fontSize: 22, fontWeight: 600, marginBottom: 16 }}>{t("trips.past")} <span className="muted" style={{ fontSize: 15 }}>· {past.length}</span></h2>
                <div style={{ display: "flex", flexDirection: "column", gap: 14, opacity: 0.92 }}>{past.map(b => <TripCard key={b.id} b={b} />)}</div>
              </section>
            )}
          </div>
        )}
      </div>
    </main>
  );
}

Object.assign(window, { TripsPage, TripCard });
