/* account — Sign in / Create account, Profile (personal info, travel prefs,
   saved cards, security), and the header account menu. */

function initials(name) {
  const p = String(name || "").trim().split(/\s+/);
  return ((p[0] || "")[0] || "") + ((p[1] || "")[0] || "");
}

function AccountMenu({ solid }) {
  const { t, lang } = useLang();
  const { user, logout, nav, route } = useStore();
  const [open, setOpen] = React.useState(false);
  const ref = React.useRef();
  React.useEffect(() => {
    const h = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener("mousedown", h); return () => document.removeEventListener("mousedown", h);
  }, []);
  if (!user) {
    return (
      <button className="btn btn-ghost btn-sm hide-mobile" onClick={() => nav("auth")}
        style={{ borderColor: solid ? "var(--line-2)" : "rgba(255,255,255,.4)", color: solid ? "var(--ink)" : "#fff" }}>
        <Icon name="user" size={15} /> {t("nav.signin")}
      </button>
    );
  }
  const items = [["profile", t("nav.profile"), "user"], ["trips", t("nav.trips"), "bag"]];
  return (
    <div ref={ref} style={{ position: "relative" }} className="hide-mobile">
      <button onClick={() => setOpen(o => !o)} aria-haspopup="true" aria-expanded={open} aria-label={t("nav.account")}
        style={{ width: 38, height: 38, borderRadius: "50%", border: "none", cursor: "pointer", background: "var(--emerald)", color: "#fff", fontWeight: 700, fontSize: 13.5, textTransform: "uppercase", fontFamily: "var(--sans)" }}>
        {initials(user.name) || "•"}
      </button>
      {open && (
        <div className="card" style={{ position: "absolute", insetInlineEnd: 0, top: "calc(100% + 10px)", width: 230, padding: 8, boxShadow: "var(--shadow-lg)", zIndex: 120 }}>
          <div style={{ padding: "10px 12px 12px" }}>
            <div style={{ fontWeight: 700, fontSize: 14 }}>{user.name}</div>
            <div className="muted" style={{ fontSize: 12.5, overflow: "hidden", textOverflow: "ellipsis" }}>{user.email}</div>
          </div>
          <div className="hr"></div>
          {items.map(([id, label, icon]) => (
            <button key={id} onClick={() => { nav(id); setOpen(false); }} style={{ display: "flex", alignItems: "center", gap: 11, width: "100%", padding: "10px 12px", border: "none", background: route === id ? "var(--paper-2)" : "transparent", borderRadius: 10, cursor: "pointer", textAlign: "start", fontSize: 14, fontFamily: "var(--sans)", color: "var(--ink)" }}
              onMouseEnter={e => e.currentTarget.style.background = "var(--paper-2)"} onMouseLeave={e => e.currentTarget.style.background = route === id ? "var(--paper-2)" : "transparent"}>
              <Icon name={icon} size={16} color="var(--ink-3)" /> {label}
            </button>
          ))}
          <div className="hr"></div>
          <button onClick={() => { logout(); setOpen(false); }} style={{ display: "flex", alignItems: "center", gap: 11, width: "100%", padding: "10px 12px", border: "none", background: "transparent", borderRadius: 10, cursor: "pointer", textAlign: "start", fontSize: 14, fontFamily: "var(--sans)", color: "var(--danger)" }}>
            <Icon name="arrowL" size={16} className="flip-rtl" /> {t("nav.signout")}
          </button>
        </div>
      )}
    </div>
  );
}

function AuthPage() {
  const { t } = useLang();
  const { user, signup, login, nav, params } = useStore();
  const [mode, setMode] = React.useState(params.mode === "signup" ? "signup" : "signin");
  const [form, setForm] = React.useState({ name: "", email: "", password: "", confirm: "" });
  const [err, setErr] = React.useState(null);
  const [busy, setBusy] = React.useState(false);
  const upd = (k, v) => setForm(f => ({ ...f, [k]: v }));
  React.useEffect(() => { if (user) nav("profile"); }, [user]);

  const submit = async (e) => {
    e.preventDefault(); setErr(null);
    if (mode === "signup" && form.password !== form.confirm) { setErr("password_mismatch"); return; }
    setBusy(true);
    const r = mode === "signup"
      ? await signup({ name: form.name, email: form.email, password: form.password })
      : await login({ email: form.email, password: form.password });
    setBusy(false);
    if (r.ok) nav("profile"); else setErr(r.error || "no_account");
  };

  return (
    <main style={{ paddingTop: 72, minHeight: "100vh", background: "var(--paper-2)" }}>
      <div className="wrap" style={{ paddingTop: 40, paddingBottom: 80, maxWidth: 980 }}>
        <div className="card split auth-card" style={{ overflow: "hidden", display: "grid", gridTemplateColumns: "1fr 1.05fr", boxShadow: "var(--shadow-lg)" }}>
          <div className="auth-aside" style={{ background: "linear-gradient(160deg,#352617,#1f160c)", color: "#fff", padding: 40, position: "relative", overflow: "hidden" }}>
            <div style={{ position: "absolute", inset: 0, background: "radial-gradient(70% 60% at 90% 0%,rgba(216,184,120,.22),transparent 60%)" }}></div>
            <div style={{ position: "relative" }}>
              <Logo size={22} dark />
              <h2 style={{ fontFamily: "var(--serif)", fontSize: 30, fontWeight: 600, marginTop: 28 }}>{mode === "signup" ? t("auth.createTitle") : t("auth.welcome")}</h2>
              <p style={{ color: "rgba(255,255,255,.74)", marginTop: 12, fontSize: 14.5, lineHeight: 1.6 }}>{mode === "signup" ? t("auth.createSub") : t("auth.signinSub")}</p>
              <div style={{ marginTop: 28, display: "flex", flexDirection: "column", gap: 14, fontSize: 14 }}>
                {["auth.b1", "auth.b2", "auth.b3", "auth.b4"].map(k => (
                  <div key={k} style={{ display: "flex", gap: 11, alignItems: "center" }}><Icon name="check" size={16} color="var(--gold-l)" /> {t(k)}</div>
                ))}
              </div>
            </div>
          </div>
          <div style={{ padding: 40 }}>
            <form onSubmit={submit} style={{ display: "flex", flexDirection: "column", gap: 15 }} noValidate>
              {mode === "signup" && <div className="field"><label>{t("auth.name")}</label><input className="input" value={form.name} onChange={e => upd("name", e.target.value)} autoComplete="name" /></div>}
              <div className="field"><label>{t("auth.email")}</label><input className="input" type="email" value={form.email} onChange={e => upd("email", e.target.value)} autoComplete="email" /></div>
              <div className="field"><label>{t("auth.password")}</label><input className="input" type="password" value={form.password} onChange={e => upd("password", e.target.value)} autoComplete={mode === "signup" ? "new-password" : "current-password"} />{mode === "signup" && <div className="muted" style={{ fontSize: 12, marginTop: 4 }}>{t("auth.pwHint")}</div>}</div>
              {mode === "signup" && <div className="field"><label>{t("auth.confirm")}</label><input className="input" type="password" value={form.confirm} onChange={e => upd("confirm", e.target.value)} autoComplete="new-password" /></div>}
              {err && <div style={{ color: "var(--danger)", fontSize: 13.5, padding: "10px 14px", background: "var(--danger-wash)", borderRadius: 10 }}>{t("auth.err." + err)}</div>}
              <button className="btn btn-primary btn-lg btn-block" type="submit" disabled={busy}>{busy ? <Spinner /> : (mode === "signup" ? t("auth.signupBtn") : t("auth.signinBtn"))}</button>
            </form>
            <div className="hr" style={{ margin: "22px 0" }}></div>
            <button onClick={() => { setMode(m => m === "signup" ? "signin" : "signup"); setErr(null); }} style={{ width: "100%", background: "none", border: "none", cursor: "pointer", color: "var(--emerald)", fontWeight: 600, fontSize: 14, fontFamily: "var(--sans)" }}>
              {mode === "signup" ? t("auth.toSignin") : t("auth.toSignup")}
            </button>
          </div>
        </div>
      </div>
    </main>
  );
}

function ProfileSection({ title, children, action }) {
  return (
    <section className="card card-pad">
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 18, flexWrap: "wrap", gap: 10 }}>
        <h3 style={{ fontFamily: "var(--serif)", fontSize: 22, fontWeight: 600 }}>{title}</h3>
        {action}
      </div>
      {children}
    </section>
  );
}

function ProfilePage() {
  const { t, lang } = useLang();
  const store = useStore();
  const { user, nav, updateProfile, changePassword, deleteAccount, cards, addCard, removeCard, makePrimaryCard, AIRPORTS } = store;
  React.useEffect(() => { if (!user) nav("auth"); }, [user]);
  if (!user) return <main style={{ paddingTop: 120, minHeight: "60vh" }} className="wrap"><div className="card card-pad center">…</div></main>;

  const [p, setP] = React.useState({ name: user.name, org: user.org || "", phone: user.phone || "", country: user.country || "SA", homeAirport: user.homeAirport || "RUH", prefCabin: user.prefCabin || "any", newsletter: user.newsletter !== false });
  const [saved, setSaved] = React.useState(false);
  const upd = (k, v) => setP(s => ({ ...s, [k]: v }));
  const save = () => { updateProfile(p); setSaved(true); setTimeout(() => setSaved(false), 2200); };

  const [nc, setNc] = React.useState({ number: "", exp: "", cvv: "", name: "" });
  const [ncErr, setNcErr] = React.useState({});
  const [adding, setAdding] = React.useState(false);
  const brand = window.detectBrand ? detectBrand(nc.number) : "unknown";
  const addNewCard = () => {
    const v = window.validateCard ? validateCard(nc) : { ok: true, errors: {} };
    if (!v.ok) { setNcErr(v.errors); return; }
    const tok = tokenize(nc);
    addCard({ brand: tok.brand, last4: tok.last4, exp: tok.exp, name: nc.name || "My card", token: tok.token });
    setNc({ number: "", exp: "", cvv: "", name: "" }); setNcErr({}); setAdding(false);
  };

  const [pw, setPw] = React.useState({ cur: "", next: "" });
  const [pwMsg, setPwMsg] = React.useState(null);
  const doChangePw = async () => {
    setPwMsg(null);
    const r = await changePassword(pw.cur, pw.next);
    if (r.ok) { setPw({ cur: "", next: "" }); setPwMsg({ ok: true }); setTimeout(() => setPwMsg(null), 2500); }
    else setPwMsg({ err: r.error });
  };

  const memberDate = user.createdAt ? new Date(user.createdAt).toISOString().slice(0, 10) : null;
  const cabinOpts = [["any", t("cabin.any")], ["Economy", t("cabin.economy")], ["Business", t("cabin.business")]];
  const countries = ["SA", "AE", "EG", "QA", "KW", "BH", "OM", "other"];
  const err = (k) => k ? <div style={{ color: "var(--danger)", fontSize: 12.5, marginTop: 5 }}>{t(k)}</div> : null;

  return (
    <main style={{ paddingTop: 96, minHeight: "100vh", background: "var(--paper)" }}>
      <div className="wrap" style={{ paddingTop: 32, paddingBottom: 80, maxWidth: 940 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 18, marginBottom: 30, flexWrap: "wrap" }}>
          <div style={{ width: 64, height: 64, borderRadius: "50%", background: "var(--emerald)", color: "#fff", display: "grid", placeItems: "center", fontWeight: 700, fontSize: 24, textTransform: "uppercase" }}>{initials(user.name) || "•"}</div>
          <div style={{ flex: 1, minWidth: 200 }}>
            <h1 style={{ fontFamily: "var(--serif)", fontSize: 32, fontWeight: 600 }}>{t("profile.greeting", { name: user.name.split(" ")[0] })}</h1>
            <div className="muted" style={{ fontSize: 13.5, marginTop: 2 }}>{user.email}{memberDate && [" · ", t("profile.member", { date: memberDate })]}</div>
          </div>
          <button className="btn btn-ghost btn-sm" onClick={() => nav("trips")}><Icon name="bag" size={15} /> {t("profile.viewTrips")}</button>
        </div>

        <div style={{ display: "flex", flexDirection: "column", gap: 20 }}>
          <ProfileSection title={t("profile.personal")} action={<button className="btn btn-primary btn-sm" onClick={save}>{saved ? <><Icon name="check" size={14} /> {t("profile.saved")}</> : t("profile.save")}</button>}>
            <div className="rcol-2" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
              <div className="field"><label>{t("auth.name")}</label><input className="input" value={p.name} onChange={e => upd("name", e.target.value)} /></div>
              <div className="field"><label>{t("auth.email")}</label><input className="input" value={user.email} disabled style={{ opacity: .7 }} /></div>
              <div className="field"><label>{t("profile.f.org")}</label><input className="input" value={p.org} onChange={e => upd("org", e.target.value)} placeholder={t("corp.ph.org")} /></div>
              <div className="field"><label>{t("profile.f.phone")}</label><input className="input" value={p.phone} onChange={e => upd("phone", e.target.value)} placeholder="+966 5X XXX XXXX" /></div>
              <div className="field"><label>{t("profile.f.country")}</label><select className="select" value={p.country} onChange={e => upd("country", e.target.value)}>{countries.map(c => <option key={c} value={c}>{t("country." + c)}</option>)}</select></div>
            </div>
          </ProfileSection>

          <ProfileSection title={t("profile.travel")} action={<button className="btn btn-primary btn-sm" onClick={save}>{saved ? <><Icon name="check" size={14} /> {t("profile.saved")}</> : t("profile.save")}</button>}>
            <div className="rcol-2" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
              <div className="field"><label>{t("profile.f.homeAirport")}</label><select className="select" value={p.homeAirport} onChange={e => upd("homeAirport", e.target.value)}>{(AIRPORTS || []).map(a => <option key={a.code} value={a.code}>{a.code} · {lang === "ar" ? a.ar : a.city}</option>)}</select></div>
              <div className="field"><label>{t("profile.f.prefCabin")}</label><select className="select" value={p.prefCabin} onChange={e => upd("prefCabin", e.target.value)}>{cabinOpts.map(([v, l]) => <option key={v} value={v}>{l}</option>)}</select></div>
            </div>
            <label style={{ display: "flex", gap: 10, alignItems: "center", fontSize: 14, cursor: "pointer", marginTop: 16 }}>
              <input type="checkbox" checked={p.newsletter} onChange={e => upd("newsletter", e.target.checked)} style={{ accentColor: "var(--emerald)", width: 18, height: 18 }} /> {t("profile.f.newsletter")}
            </label>
          </ProfileSection>

          <ProfileSection title={t("profile.cards")} action={!adding && <button className="btn btn-ghost btn-sm" onClick={() => setAdding(true)}><Icon name="plus" size={15} /> {t("profile.addCard")}</button>}>
            <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
              {cards.map(c => (
                <div key={c.id} style={{ display: "flex", alignItems: "center", gap: 14, padding: 14, borderRadius: 12, border: "1px solid var(--line-2)" }}>
                  <BrandMark brand={c.brand} />
                  <div style={{ flex: 1 }}><div style={{ fontWeight: 600, fontSize: 14.5 }}>{c.name} · •• {c.last4}</div><div className="muted" style={{ fontSize: 12.5 }}>{t("booking.f.exp")} {c.exp}</div></div>
                  {c.primary ? <span className="chip chip-gold" style={{ fontSize: 11 }}>{t("booking.primary")}</span> : <button className="btn btn-ghost btn-sm" onClick={() => makePrimaryCard(c.id)}>{t("profile.makePrimary")}</button>}
                  <button onClick={() => removeCard(c.id)} aria-label={t("profile.remove")} style={{ background: "none", border: "none", cursor: "pointer", color: "var(--ink-3)", padding: 6 }}><Icon name="x" size={16} /></button>
                </div>
              ))}
              {cards.length === 0 && !adding && <div className="muted" style={{ fontSize: 14 }}>{t("profile.noCards")}</div>}
              {adding && (
                <div className="card" style={{ padding: 18, background: "var(--paper)" }}>
                  <div className="rcol-2" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
                    <div className="field" style={{ gridColumn: "1/3" }}><label>{t("booking.f.cardNo")}</label><div style={{ position: "relative" }}><input className="input" inputMode="numeric" value={nc.number} onChange={e => setNc({ ...nc, number: formatCardNumber(e.target.value) })} placeholder="•••• •••• •••• ••••" style={{ paddingInlineEnd: 56 }} />{brand !== "unknown" && <span style={{ position: "absolute", insetInlineEnd: 10, top: "50%", transform: "translateY(-50%)" }}><BrandMark brand={brand} /></span>}</div>{err(ncErr.number)}</div>
                    <div className="field"><label>{t("booking.f.exp")}</label><input className="input" inputMode="numeric" value={nc.exp} onChange={e => setNc({ ...nc, exp: formatExpiry(e.target.value) })} placeholder="MM / YY" />{err(ncErr.exp)}</div>
                    <div className="field"><label>{t("booking.f.cvv")}</label><input className="input" inputMode="numeric" maxLength={4} value={nc.cvv} onChange={e => setNc({ ...nc, cvv: e.target.value.replace(/\D/g, "") })} placeholder="•••" />{err(ncErr.cvv)}</div>
                    <div className="field" style={{ gridColumn: "1/3" }}><label>{t("booking.f.cardName")}</label><input className="input" value={nc.name} onChange={e => setNc({ ...nc, name: e.target.value })} placeholder={t("booking.ph.cardName")} />{err(ncErr.name)}</div>
                  </div>
                  <div style={{ display: "flex", gap: 10, marginTop: 14 }}>
                    <button className="btn btn-primary btn-sm" onClick={addNewCard}>{t("profile.addCard")}</button>
                    <button className="btn btn-ghost btn-sm" onClick={() => { setAdding(false); setNcErr({}); }}>{t("common.cancel")}</button>
                  </div>
                </div>
              )}
            </div>
          </ProfileSection>

          <ProfileSection title={t("profile.security")}>
            <div className="rcol-2" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16, alignItems: "end" }}>
              <div className="field"><label>{t("profile.currentPw")}</label><input className="input" type="password" value={pw.cur} onChange={e => setPw({ ...pw, cur: e.target.value })} autoComplete="current-password" /></div>
              <div className="field"><label>{t("profile.newPw")}</label><input className="input" type="password" value={pw.next} onChange={e => setPw({ ...pw, next: e.target.value })} autoComplete="new-password" /></div>
            </div>
            {pwMsg && <div style={{ marginTop: 10, fontSize: 13, color: pwMsg.ok ? "var(--ok)" : "var(--danger)" }}>{pwMsg.ok ? t("profile.pwChanged") : t("auth.err." + pwMsg.err)}</div>}
            <div style={{ display: "flex", gap: 12, marginTop: 16, flexWrap: "wrap" }}>
              <button className="btn btn-ghost btn-sm" onClick={doChangePw} disabled={!pw.cur || !pw.next}>{t("profile.changePw")}</button>
              <div style={{ flex: 1 }}></div>
              <button className="btn btn-ghost btn-sm" onClick={() => store.logout()} style={{ borderColor: "var(--line-2)" }}><Icon name="arrowL" size={14} className="flip-rtl" /> {t("profile.signout")}</button>
              <button className="btn btn-ghost btn-sm" onClick={() => { if (confirm(t("profile.deleteConfirm"))) deleteAccount(); }} style={{ borderColor: "var(--danger)", color: "var(--danger)" }}>{t("profile.delete")}</button>
            </div>
          </ProfileSection>
        </div>
      </div>
    </main>
  );
}

Object.assign(window, { AccountMenu, AuthPage, ProfilePage, initials });
