/* Sea La Vie — Guest portal UI (account.html).
   Account helpers + useAccount hook live in data.jsx so they're available
   site-wide; this file is just the page-specific UI.
*/
const { useState: useAc, useEffect: useAcEf, useMemo: useAcMm } = React;

// ─── UI: HEADER FOR ACCOUNT PAGE ───────────────────────────────────────────
function AccountHeader({ onBack }) {
  return (
    <div style={{
      borderBottom: "1px solid var(--line-soft)",
      background: "var(--paper)",
      padding: "18px 40px",
      display: "flex", justifyContent: "space-between", alignItems: "center",
      position: "sticky", top: 0, zIndex: 20
    }}>
      <a href="index.html" style={{textDecoration: "none"}}>
        <BrandLogo compact />
      </a>
      <a href="index.html" style={{
        fontFamily: "var(--sans)", fontSize: 11, letterSpacing: "0.24em",
        textTransform: "uppercase", color: "var(--ink-mute)", textDecoration: "none"
      }}>← Back to site</a>
    </div>
  );
}

// ─── UI: SIGN-IN GATE ──────────────────────────────────────────────────────
function SignInGate() {
  const [mode, setMode] = useAc("signin");
  const [form, setForm] = useAc({ name: "", email: "", password: "" });
  const [err, setErr] = useAc("");
  const [busy, setBusy] = useAc(false);
  const up = (k, v) => setForm(f => ({ ...f, [k]: v }));

  async function submit(e) {
    e.preventDefault();
    setBusy(true); setErr("");
    const r = mode === "signin"
      ? await acctLogin({ email: form.email, password: form.password })
      : await acctRegister({ name: form.name, email: form.email, password: form.password });
    setBusy(false);
    if (!r.ok) setErr(r.error || "Something went wrong.");
    // session change triggers a re-render via useAccount
  }

  return (
    <div style={{
      maxWidth: 520, margin: "0 auto", padding: "80px 40px 120px"
    }}>
      <div className="eyebrow" style={{textAlign: "center"}}>Guest portal</div>
      <h1 style={{
        fontFamily: "var(--serif)", fontWeight: 300, fontSize: 56,
        textAlign: "center", margin: "16px 0 8px", lineHeight: 1.05
      }}>
        {mode === "signin" ? <>Welcome <em style={{color: "var(--sky-deep)"}}>back</em></> : <>Open your <em style={{color: "var(--sky-deep)"}}>chapter</em></>}
      </h1>
      <p style={{
        textAlign: "center", color: "var(--ink-soft)", fontSize: 15, maxWidth: 420,
        margin: "8px auto 40px"
      }}>
        {mode === "signin"
          ? "Sign in to see your stays, track your loyalty, and unlock perks reserved for returning guests."
          : "Create your account in twenty seconds. The first night you book is the start of Karibu."}
      </p>

      <form onSubmit={submit} className="acct-form">
        {mode === "register" && (
          <div className="field-group">
            <label>Full name</label>
            <input type="text" value={form.name} onChange={e => up("name", e.target.value)} autoFocus placeholder="As on your passport" />
          </div>
        )}
        <div className="field-group">
          <label>Email</label>
          <input type="email" value={form.email} onChange={e => up("email", e.target.value)} placeholder="you@example.com" autoFocus={mode === "signin"} />
        </div>
        <div className="field-group">
          <label>Password</label>
          <input type="password" value={form.password} onChange={e => up("password", e.target.value)} placeholder={mode === "register" ? "Choose a password" : "Your password"} />
        </div>

        {err && <div className="err-msg">{err}</div>}

        <button className="submit" type="submit" disabled={busy}>
          {busy ? "One moment…" : mode === "signin" ? "Sign in" : "Create my account"}
        </button>

        <div style={{
          marginTop: 24, textAlign: "center", fontSize: 12, letterSpacing: "0.12em",
          textTransform: "uppercase", color: "var(--ink-mute)"
        }}>
          {mode === "signin" ? (
            <>New here? <button type="button" onClick={() => { setMode("register"); setErr(""); }}
              style={{background: "none", border: "none", color: "var(--sky-deep)", cursor: "pointer", letterSpacing: "0.12em", textTransform: "uppercase", fontSize: 12, fontFamily: "var(--sans)"}}>Create an account</button></>
          ) : (
            <>Already with us? <button type="button" onClick={() => { setMode("signin"); setErr(""); }}
              style={{background: "none", border: "none", color: "var(--sky-deep)", cursor: "pointer", letterSpacing: "0.12em", textTransform: "uppercase", fontSize: 12, fontFamily: "var(--sans)"}}>Sign in</button></>
          )}
        </div>

        <div style={{
          marginTop: 36, padding: 18, background: "var(--ivory-deep)",
          fontSize: 12, lineHeight: 1.7, color: "var(--ink-soft)", textAlign: "center"
        }}>
          <strong style={{fontFamily: "var(--serif)", fontStyle: "italic"}}>Try the demo:</strong> <br/>
          <code style={{fontFamily: "JetBrains Mono, monospace", fontSize: 11}}>demo@sealaviediani.com</code> / <code style={{fontFamily: "JetBrains Mono, monospace", fontSize: 11}}>demo</code>
        </div>
      </form>
    </div>
  );
}

// ─── UI: LOYALTY LADDER ────────────────────────────────────────────────────
function LoyaltyLadder({ nights }) {
  const current = tierForNights(nights);
  const next = nextTierFor(nights);

  return (
    <section className="acct-loyalty">
      <div className="acct-section-head">
        <div className="eyebrow">Sea La Vie · Loyalty</div>
        <h2>The deeper you stay, the <em>further</em> we go.</h2>
      </div>

      {/* Progress strip */}
      <div className="ladder-rail">
        <div className="ladder-fill" style={{
          width: next
            ? `${Math.min(100, (nights / next.minNights) * 100)}%`
            : "100%"
        }}></div>
        {TIERS.map(t => {
          const reached = nights >= t.minNights;
          const isCurrent = t.id === current.id;
          const pos = next
            ? (t.minNights === 0 ? 0 : t.minNights === 10 ? 50 : 100)
            : (t.minNights === 0 ? 0 : t.minNights === 10 ? 50 : 100);
          return (
            <div key={t.id} className={`ladder-node ${reached ? "reached" : ""} ${isCurrent ? "current" : ""}`}
                 style={{left: `${pos}%`}}>
              <div className="dot"></div>
              <div className="lbl">
                <div className="n">{t.name}</div>
                <div className="m">{t.minNights === 0 ? "from night 1" : `${t.minNights} nights`}</div>
              </div>
            </div>
          );
        })}
      </div>

      {/* Status callout */}
      <div className="ladder-status">
        <div>
          <div className="eyebrow">Your tier</div>
          <div className="tier-name"><span className="serif">{current.name}</span> <span className="sub">· {current.sub}</span></div>
        </div>
        <div className="divider"></div>
        <div>
          <div className="eyebrow">Nights with us</div>
          <div className="tier-name"><span className="serif">{nights}</span></div>
        </div>
        <div className="divider"></div>
        <div>
          <div className="eyebrow">{next ? "Next tier" : "All unlocked"}</div>
          <div className="tier-name">
            {next ? <>
              <span className="serif">{next.name}</span>{" "}
              <span className="sub">in {next.minNights - nights} night{next.minNights - nights === 1 ? "" : "s"}</span>
            </> : <span className="sub">You've reached Mwenyeji. Asante sana.</span>}
          </div>
        </div>
      </div>

      {/* Tier cards */}
      <div className="tier-grid">
        {TIERS.map(t => {
          const reached = nights >= t.minNights;
          const isCurrent = t.id === current.id;
          return (
            <div key={t.id} className={`tier-card ${reached ? "reached" : "locked"} ${isCurrent ? "current" : ""}`}>
              <div className="tc-head" style={{background: t.accent, color: t.accentInk}}>
                <div className="eyebrow" style={{color: t.accentInk, opacity: 0.7}}>
                  {t.minNights === 0 ? "From your first night" : `Unlocks at ${t.minNights} nights`}
                </div>
                <h3>{t.name}</h3>
                <div className="tc-sub">— {t.sub}</div>
                {isCurrent && <div className="tc-badge">Your tier</div>}
                {!reached && <div className="tc-lock">◇</div>}
              </div>
              <div className="tc-body">
                <p className="tc-summary">{t.summary}</p>
                <ul className="tc-perks">
                  {t.perks.map((p, i) => (
                    <li key={i}>
                      <div className="p-l">{p.l}</div>
                      <div className="p-s">{p.s}</div>
                    </li>
                  ))}
                  {Array.from({length: t.hiddenCount}).map((_, i) => (
                    <li key={`h${i}`} className="hidden-perk">
                      <div className="p-l">
                        <span className="seal">✦</span>
                        {reached ? <span>A perk discovered on arrival.</span> : <span>A perk you'll discover here, one day.</span>}
                      </div>
                      <div className="p-s">
                        {reached
                          ? "Reserved for your eyes only — your travel curator will share details when you next check in."
                          : "We don't write our best gestures down. They're how we say thank you for staying."}
                      </div>
                    </li>
                  ))}
                </ul>
              </div>
            </div>
          );
        })}
      </div>
    </section>
  );
}

// ─── UI: STAYS LIST ────────────────────────────────────────────────────────
function StayCard({ b, villa, onCancel }) {
  const arr = new Date(b.arrival);
  const dep = new Date(b.departure);
  const monthName = MONTHS[arr.getMonth()];
  const today = new Date(); today.setHours(0,0,0,0);
  const isPast = b.status === "completed" || dep < today;
  const canCancel = !isPast && b.status !== "cancelled" && arr > today;
  const daysUntil = Math.ceil((arr - today) / 86400000);

  const statusLabel = {
    confirmed: "Confirmed",
    held: "Holding · pending confirmation",
    completed: "Completed",
    cancelled: "Cancelled",
    enquiry: "Enquiry"
  }[b.status] || b.status;

  return (
    <article className={`stay-card ${isPast ? "past" : "future"} ${b.status === "cancelled" ? "is-cancelled" : ""}`}>
      <div className="sc-date">
        <div className="month">{monthName.slice(0,3).toUpperCase()}</div>
        <div className="day">{arr.getDate()}</div>
        <div className="year">{arr.getFullYear()}</div>
      </div>
      <div className="sc-body">
        <div className="eyebrow" style={{marginBottom: 4}}>{b.ref}</div>
        <h4>
          {villa ? villa.name.join(" ") : (b.villaId || "").toUpperCase()}
          <span className="badge">{villa ? villa.badge : ""}</span>
        </h4>
        <div className="sc-meta">
          <span>{fmtDate(arr)} → {fmtDate(dep)}</span>
          <span className="dot">·</span>
          <span>{b.nights} night{b.nights !== 1 ? "s" : ""}</span>
          <span className="dot">·</span>
          <span>{b.guests} guest{b.guests !== 1 ? "s" : ""}</span>
          {!isPast && b.status !== "cancelled" && daysUntil > 0 && (
            <>
              <span className="dot">·</span>
              <span style={{color: "var(--sky-deep)"}}>in {daysUntil} day{daysUntil !== 1 ? "s" : ""}</span>
            </>
          )}
        </div>
        {b.totalUSD ? <div className="sc-total">USD {b.totalUSD.toLocaleString()}</div> : null}
      </div>
      <div className="sc-status">
        <span className={`pill ${b.status}`}>{statusLabel}</span>
        <div className="sc-actions">
          {canCancel && (
            <button className="sc-cancel" onClick={() => onCancel && onCancel(b)}>Cancel…</button>
          )}
          {!isPast && b.status !== "cancelled" && (
            <a href={`contact.html`} className="sc-link">Manage →</a>
          )}
        </div>
      </div>
    </article>
  );
}

function StaysSection({ bookings, onCancel }) {
  const villaIndex = useAcMm(() => {
    const map = {};
    VILLAS.forEach(v => { map[v.id] = v; });
    return map;
  }, []);

  const sorted = [...(bookings || [])].sort((a, b) => (a.arrival || "").localeCompare(b.arrival || ""));
  const today = new Date(); today.setHours(0,0,0,0);
  const upcoming = sorted.filter(b => b.status !== "cancelled" && b.status !== "completed" && new Date(b.departure) >= today);
  const past = sorted.filter(b => b.status === "completed" || (b.status !== "cancelled" && new Date(b.departure) < today)).reverse();
  const cancelled = sorted.filter(b => b.status === "cancelled");

  return (
    <section className="acct-stays">
      <div className="acct-section-head">
        <div className="eyebrow">Your stays</div>
        <h2>Time you've spent <em>at home</em> with us.</h2>
      </div>

      {upcoming.length === 0 && past.length === 0 && (
        <div className="empty-state">
          <div className="eyebrow">No stays yet</div>
          <p>Your first reservation is one click away.</p>
          <a href="availability.html" className="btn-solid" style={{display: "inline-block", marginTop: 18}}>
            Check availability →
          </a>
        </div>
      )}

      {upcoming.length > 0 && (
        <>
          <h3 className="stays-h">Upcoming · {upcoming.length}</h3>
          <div className="stays-list">
            {upcoming.map(b => <StayCard key={b.ref} b={b} villa={villaIndex[b.villaId]} onCancel={onCancel} />)}
          </div>
        </>
      )}

      {past.length > 0 && (
        <>
          <h3 className="stays-h" style={{marginTop: 36}}>Previous · {past.length}</h3>
          <div className="stays-list">
            {past.map(b => <StayCard key={b.ref} b={b} villa={villaIndex[b.villaId]} />)}
          </div>
        </>
      )}

      {cancelled.length > 0 && (
        <>
          <h3 className="stays-h" style={{marginTop: 36, color: "var(--ink-mute)"}}>Cancelled · {cancelled.length}</h3>
          <div className="stays-list">
            {cancelled.map(b => <StayCard key={b.ref} b={b} villa={villaIndex[b.villaId]} />)}
          </div>
        </>
      )}
    </section>
  );
}

// ─── UI: CANCEL MODAL ─────────────────────────────────────────────────────
function CancelModal({ booking, villa, onClose, onConfirm }) {
  const [busy, setBusy] = useAc(false);
  const [err, setErr] = useAc("");
  if (!booking) return null;

  const arr = new Date(booking.arrival);
  const today = new Date(); today.setHours(0,0,0,0);
  const daysAhead = Math.ceil((arr - today) / 86400000);

  // Policy tiers, mirroring typical luxury-coast practice. Adjust on the
  // server if you have a real Ts&Cs document.
  let refundPct, policyNote;
  if (daysAhead >= 60)      { refundPct = 100; policyNote = "Full refund — you're more than sixty days out."; }
  else if (daysAhead >= 30) { refundPct = 50;  policyNote = "50% refund — between thirty and sixty days before arrival."; }
  else if (daysAhead >= 14) { refundPct = 25;  policyNote = "25% refund — between fourteen and thirty days before arrival."; }
  else                      { refundPct = 0;   policyNote = "No refund within fourteen days. Your travel curator may still be able to help — reach us first."; }

  const refundAmt = booking.totalUSD ? Math.round(booking.totalUSD * refundPct / 100) : null;

  async function confirm() {
    setBusy(true); setErr("");
    const r = await acctCancelBooking({ ref: booking.ref });
    setBusy(false);
    if (!r.ok) { setErr(r.error || "Could not cancel. Please reach us."); return; }
    onConfirm && onConfirm();
  }

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="cancel-modal" onClick={e => e.stopPropagation()}>
        <button className="modal-close" onClick={onClose}>×</button>
        <div className="eyebrow">Cancel reservation</div>
        <h2>Are you sure you want to <em>release</em> these dates?</h2>

        <div className="cancel-summary">
          <div className="cs-row"><span className="l">Reference</span><span className="v ref">{booking.ref}</span></div>
          <div className="cs-row"><span className="l">Residence</span><span className="v">{villa ? villa.name.join(" ") : booking.villaId}</span></div>
          <div className="cs-row"><span className="l">Arrival</span><span className="v">{fmtDate(arr)}</span></div>
          <div className="cs-row"><span className="l">Departure</span><span className="v">{fmtDate(new Date(booking.departure))}</span></div>
          <div className="cs-row"><span className="l">Nights</span><span className="v">{booking.nights}</span></div>
        </div>

        <div className="cancel-policy">
          <div className="eyebrow" style={{color: "var(--sky-deep)"}}>Cancellation policy</div>
          <div className="refund-line">
            <span className="pct">{refundPct}%</span>
            <span className="of">refund of {booking.totalUSD ? `USD ${booking.totalUSD.toLocaleString()}` : "reservation"}</span>
            {refundAmt !== null && refundAmt > 0 && (
              <span className="amt">≈ USD {refundAmt.toLocaleString()}</span>
            )}
          </div>
          <p className="note">{policyNote}</p>
          <p className="note small">A confirmation will go to {(currentSession() && currentSession().email) || "your email"} within twenty-four hours. Refunds reach the original payment method in five to seven working days.</p>
        </div>

        {err && <div className="err-msg">{err}</div>}

        <div className="cancel-actions">
          <button className="ghost" onClick={onClose} disabled={busy}>Keep my reservation</button>
          <button className="submit danger" onClick={confirm} disabled={busy}>
            {busy ? "Releasing…" : `Cancel & request ${refundPct}% refund`}
          </button>
        </div>

        <p className="reach-line">
          Rather speak to a human? <a href={`mailto:${CONTACT.email}?subject=Cancellation%20—%20${booking.ref}`}>{CONTACT.email}</a> · <a href={`tel:${CONTACT.phoneRaw}`}>{CONTACT.phone}</a>
        </p>
      </div>
    </div>
  );
}

// ─── UI: ACCOUNT APP ───────────────────────────────────────────────────────
function AccountApp() {
  const { session, account, loading, refresh } = useAccount();
  const [cancelling, setCancelling] = useAc(null); // booking to cancel

  if (loading) {
    return (
      <div style={{padding: "120px 40px", textAlign: "center", color: "var(--ink-mute)"}}>
        <AccountHeader />
        <div style={{marginTop: 80}} className="eyebrow">Loading…</div>
      </div>
    );
  }

  if (!session || !account) {
    return (
      <div>
        <AccountHeader />
        <SignInGate />
      </div>
    );
  }

  const stats = deriveStats(account.bookings);
  const tier = tierForNights(stats.nights);
  const next = nextTierFor(stats.nights);

  const villaIdx = {};
  VILLAS.forEach(v => { villaIdx[v.id] = v; });

  return (
    <div className="acct-page">
      <AccountHeader />

      {/* Hero greeting */}
      <section className="acct-hero" style={{background: "var(--ink)"}}>
        <div className="acct-hero-inner">
          <div className="eyebrow" style={{color: "var(--sky-pale)"}}>{tier.name} · {tier.sub}</div>
          <h1>
            Karibu, <em>{account.name.split(" ")[0]}</em>.
          </h1>
          <p>{stats.nights > 0
              ? <>You've spent <strong>{stats.nights} night{stats.nights === 1 ? "" : "s"}</strong> with us. {next
                  ? <>Another <strong>{next.minNights - stats.nights}</strong> and {next.name} opens its quieter doors.</>
                  : <>You've reached every door we have. Asante sana.</>}
              </>
              : <>Your first stay will begin your Karibu chapter — and start the clock toward Rafiki and Mwenyeji.</>}
          </p>

          <div className="hero-stats">
            <div>
              <div className="n">{stats.nights}</div>
              <div className="l">Nights</div>
            </div>
            <div className="vd"></div>
            <div>
              <div className="n">{stats.stays}</div>
              <div className="l">Stays</div>
            </div>
            <div className="vd"></div>
            <div>
              <div className="n">{stats.upcoming}</div>
              <div className="l">Upcoming</div>
            </div>
            <div className="vd"></div>
            <div>
              <div className="n serif">{tier.name}</div>
              <div className="l">Tier</div>
            </div>
          </div>

          <div className="hero-actions">
            <a href="availability.html" className="btn-solid" style={{background: "var(--ivory)", color: "var(--ink)"}}>Book another stay</a>
            <button onClick={() => { acctSignOut(); }} className="btn-line" style={{color: "var(--ivory)", borderBottomColor: "var(--ivory)"}}>
              Sign out
            </button>
          </div>
        </div>
      </section>

      <div className="acct-body">
        <LoyaltyLadder nights={stats.nights} />
        <StaysSection bookings={account.bookings} onCancel={setCancelling} />

        {/* Profile / settings */}
        <section className="acct-profile">
          <div className="acct-section-head">
            <div className="eyebrow">Your details</div>
            <h2>Profile</h2>
          </div>
          <div className="profile-grid">
            <div className="profile-row">
              <div className="label">Name</div>
              <div className="value">{account.name}</div>
            </div>
            <div className="profile-row">
              <div className="label">Email</div>
              <div className="value">{account.email}</div>
            </div>
            <div className="profile-row">
              <div className="label">Joined</div>
              <div className="value">{fmtDate(new Date(account.joinedAt))}</div>
            </div>
            <div className="profile-row">
              <div className="label">Curator</div>
              <div className="value">Asha Mwakio · <a href={`mailto:${CONTACT.email}`}>{CONTACT.email}</a></div>
            </div>
          </div>
          <p style={{marginTop: 24, fontSize: 12, color: "var(--ink-mute)", maxWidth: 640, lineHeight: 1.7}}>
            To update your name, dietary preferences or stored passport details, write to your curator. We keep
            this lightweight by design — every Sea La Vie guest has a named human, not a form.
          </p>
        </section>
      </div>

      <footer className="acct-footer">
        <div className="eyebrow" style={{color: "var(--sky-pale)"}}>Sea La Vie · Diani Beach</div>
        <p>Built and run by a Kenyan family. <a href="contact.html">Reach us</a>.</p>
      </footer>

      {cancelling && (
        <CancelModal
          booking={cancelling}
          villa={villaIdx[cancelling.villaId]}
          onClose={() => setCancelling(null)}
          onConfirm={() => { setCancelling(null); refresh(); }}
        />
      )}
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<AccountApp />);
