/* ============================================================
   PRESTIGE BIMMER — Customer account (email/password)
   Sign up / sign in, basic profile, and a saved list of the
   vehicles a customer is interested in. Reuses PB.User + useUser.
   ============================================================ */

const AUTH_ERRORS = {
  "auth/invalid-email": "That email address doesn’t look right.",
  "auth/email-already-in-use": "An account with that email already exists — try signing in.",
  "auth/weak-password": "Password must be at least 6 characters.",
  "auth/missing-password": "Please enter a password.",
  "auth/wrong-password": "Email or password is incorrect.",
  "auth/user-not-found": "Email or password is incorrect.",
  "auth/invalid-credential": "Email or password is incorrect.",
  "auth/too-many-requests": "Too many attempts. Please wait a moment and try again.",
  "auth/account-exists-with-different-credential": "You already have an account with this email — sign in with your email and password instead.",
  "auth/popup-blocked": "Your browser blocked the sign-in popup. Allow popups for this site and try again.",
};
const authMsg = (e) => AUTH_ERRORS[e && e.code] || (e && e.message) || "Something went wrong.";

/* Google "G" glyph */
function GoogleGlyph() {
  return (
    <svg width="18" height="18" viewBox="0 0 18 18" aria-hidden="true" style={{ flexShrink: 0 }}>
      <path fill="#4285F4" d="M17.64 9.2c0-.64-.06-1.25-.16-1.84H9v3.48h4.84a4.14 4.14 0 0 1-1.8 2.72v2.26h2.92c1.71-1.57 2.68-3.89 2.68-6.62z" />
      <path fill="#34A853" d="M9 18c2.43 0 4.47-.8 5.96-2.18l-2.92-2.26c-.8.54-1.84.86-3.04.86-2.34 0-4.32-1.58-5.02-3.7H.96v2.33A9 9 0 0 0 9 18z" />
      <path fill="#FBBC05" d="M3.98 10.72a5.41 5.41 0 0 1 0-3.44V4.95H.96a9 9 0 0 0 0 8.1l3.02-2.33z" />
      <path fill="#EA4335" d="M9 3.58c1.32 0 2.5.45 3.44 1.35l2.58-2.58C13.47.89 11.43 0 9 0A9 9 0 0 0 .96 4.95l3.02 2.33C4.68 5.16 6.66 3.58 9 3.58z" />
    </svg>
  );
}

/* ---------------- Auth (sign in / sign up) ---------------- */
function AccountAuth() {
  const [mode, setMode] = useState("signin"); // 'signin' | 'signup'
  const [f, setF] = useState({ name: "", phone: "", email: "", password: "" });
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState("");
  const [note, setNote] = useState("");
  const set = (k) => (e) => setF((s) => ({ ...s, [k]: e.target.value }));

  const submit = async (e) => {
    e.preventDefault();
    setBusy(true); setErr(""); setNote("");
    try {
      if (mode === "signup") await PB.User.signUp(f);
      else await PB.User.signIn(f.email, f.password);
      // onAuthStateChanged swaps the view to the dashboard.
    } catch (ex) { setErr(authMsg(ex)); setBusy(false); }
  };

  const forgot = async () => {
    if (!f.email) { setErr("Enter your email above first, then tap reset."); return; }
    setErr(""); setNote("");
    try { await PB.User.resetPassword(f.email); setNote("Password reset email sent — check your inbox."); }
    catch (ex) { setErr(authMsg(ex)); }
  };

  const google = async () => {
    setBusy(true); setErr(""); setNote("");
    try {
      await PB.User.signInWithGoogle();
      // onAuthStateChanged swaps the view (Google accounts are pre-verified).
    } catch (ex) {
      if (ex.code !== "auth/popup-closed-by-user" && ex.code !== "auth/cancelled-popup-request") setErr(authMsg(ex));
      setBusy(false);
    }
  };

  return (
    <section className="section account-auth">
      <div className="wrap account-auth-grid">
        <div className="account-auth-intro">
          <span className="kicker">{t("Your garage")}</span>
          <h1 className="display-l">{mode === "signup" ? t("Create your account.") : t("Welcome back.")}</h1>
          <p className="lede">
            {t("Save the BMWs you love, keep your details on file, and book a showroom visit in seconds. Pickup is by appointment at our Miami showroom.")}
          </p>
          <ul className="account-perks">
            <li><Icon name="heart" size={16} /> {t("Build a shortlist of vehicles you’re interested in")}</li>
            <li><Icon name="check" size={16} /> {t("Faster appointment requests")}</li>
            <li><Icon name="shield" size={16} /> {t("Your details stay private to Prestige Bimmer")}</li>
          </ul>
        </div>

        <div className="account-card card">
          <div className="account-tabs">
            <button className={"account-tab " + (mode === "signin" ? "active" : "")} onClick={() => { setMode("signin"); setErr(""); }}>{t("Sign in")}</button>
            <button className={"account-tab " + (mode === "signup" ? "active" : "")} onClick={() => { setMode("signup"); setErr(""); }}>{t("Create account")}</button>
          </div>

          <button type="button" className="btn btn-ghost btn-block btn-lg account-google" onClick={google} disabled={busy}>
            <GoogleGlyph /> {t("Continue with Google")}
          </button>
          <div className="account-or mono"><span>{mode === "signup" ? t("or sign up with email") : t("or sign in with email")}</span></div>

          <form className="account-form" onSubmit={submit}>
            {mode === "signup" && (
              <div className="field-row">
                <Field label={t("Full name")}><input required value={f.name} onChange={set("name")} placeholder="Jane Doe" /></Field>
                <Field label={t("Phone")}><input value={f.phone} onChange={set("phone")} placeholder="(305) 555-0123" /></Field>
              </div>
            )}
            <Field label={t("Email")}><input required type="email" value={f.email} onChange={set("email")} placeholder="jane@email.com" /></Field>
            <Field label={t("Password")}><input required type="password" value={f.password} onChange={set("password")} placeholder={mode === "signup" ? t("At least 6 characters") : t("Your password")} autoComplete={mode === "signup" ? "new-password" : "current-password"} /></Field>

            {err && <div className="account-err mono"><Icon name="x" size={13} /> {t(err)}</div>}
            {note && <div className="account-note mono"><Icon name="check" size={13} /> {t(note)}</div>}

            <button className="btn btn-primary btn-block btn-lg" type="submit" disabled={busy}>
              {busy ? t("Please wait…") : (mode === "signup" ? t("Create account") : t("Sign in"))} <Icon name="arrow" size={17} />
            </button>

            {mode === "signin" && (
              <button type="button" className="account-forgot mono" onClick={forgot}>{t("Forgot your password?")}</button>
            )}
          </form>
        </div>
      </div>
    </section>
  );
}

/* ---------------- Dashboard (signed in) ---------------- */
function AccountDashboard({ user, profile }) {
  const inv = useInventory();
  const [name, setName] = useState((profile && profile.name) || user.displayName || "");
  const [phone, setPhone] = useState((profile && profile.phone) || "");
  const [saved, setSaved] = useState(false);
  const [busy, setBusy] = useState(false);

  useEffect(() => {
    setName((profile && profile.name) || user.displayName || "");
    setPhone((profile && profile.phone) || "");
  }, [profile && profile.name, profile && profile.phone]);

  const ids = (profile && profile.interested) || [];
  const cars = ids.map((id) => inv.find((v) => v.id === id)).filter(Boolean);

  const saveProfile = async (e) => {
    e.preventDefault();
    setBusy(true);
    try { await PB.User.saveProfile({ name, phone }); setSaved(true); setTimeout(() => setSaved(false), 2200); }
    catch (ex) { alert(authMsg(ex)); }
    finally { setBusy(false); }
  };

  const remove = async (id) => { try { await PB.User.toggleInterest(id); } catch (ex) { alert(authMsg(ex)); } };

  const greeting = (name || user.displayName || user.email || "").split(" ")[0] || "there";

  return (
    <section className="section account-dash">
      <div className="wrap">
        <div className="account-dash-head">
          <div>
            <span className="kicker">{t("Your account")}</span>
            <h1 className="display-l">{t("Hi, {name}.", { name: greeting })}</h1>
          </div>
          <button className="btn btn-ghost" onClick={() => PB.User.signOut()}><Icon name="logout" size={16} /> {t("Sign out")}</button>
        </div>

        <div className="account-dash-grid">
          <form className="account-profile card" onSubmit={saveProfile}>
            <h3 className="account-section-title mono">{t("Your details")}</h3>
            <Field label={t("Full name")}><input value={name} onChange={(e) => setName(e.target.value)} placeholder="Jane Doe" /></Field>
            <Field label={t("Phone")}><input value={phone} onChange={(e) => setPhone(e.target.value)} placeholder="(305) 555-0123" /></Field>
            <Field label={t("Email")}><input value={user.email} disabled /></Field>
            <button className="btn btn-primary btn-block" type="submit" disabled={busy}>
              <Icon name="check" size={16} /> {saved ? t("Saved") : (busy ? t("Saving…") : t("Save details"))}
            </button>
          </form>

          <div className="account-saved">
            <h3 className="account-section-title mono">{t("Vehicles you’re interested in ({n})", { n: cars.length })}</h3>
            {cars.length ? (
              <div className="account-saved-grid">
                {cars.map((v) => (
                  <div className="account-saved-item" key={v.id}>
                    <a href={"/vehicle/" + v.id} className="account-saved-link">
                      <Photo className="account-saved-thumb" label={v.model} src={pbMediaThumb(pbMedia(v)[0])} />
                      <div className="account-saved-info">
                        <strong>{v.model}</strong>
                        <span className="mono text-dim">{v.year} · {v.series}</span>
                        <span className="account-saved-price tnum">{fmtPrice(v.price)}</span>
                        <span className={"badge badge-" + v.status}>{t(statusLabel[v.status])}</span>
                      </div>
                    </a>
                    <button className="account-saved-x" title={t("Remove")} onClick={() => remove(v.id)}><Icon name="trash" size={15} /></button>
                  </div>
                ))}
              </div>
            ) : (
              <div className="account-empty card">
                <Icon name="heart" size={34} />
                <p>{t("You haven’t saved any vehicles yet.")}</p>
                <a href="/inventory" className="btn btn-primary">{t("Browse the collection")} <Icon name="arrow" size={16} /></a>
              </div>
            )}
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---------------- Loading + router entry ---------------- */
function AccountLoading() {
  return (
    <section className="section account-loading">
      <div className="wrap" style={{ textAlign: "center" }}>
        <Icon name="cog" size={26} />
        <p className="text-dim mono" style={{ marginTop: 12 }}>{t("Loading your account…")}</p>
      </div>
    </section>
  );
}

/* ---------------- Verify email (signed in, not yet verified) ---------------- */
function AccountVerify({ user }) {
  const [busy, setBusy] = useState(false);
  const [note, setNote] = useState("");
  const [err, setErr] = useState("");

  const resend = async () => {
    setBusy(true); setErr(""); setNote("");
    try { await PB.User.resendVerification(); setNote("Verification email sent — check your inbox (and spam)."); }
    catch (ex) { setErr(authMsg(ex)); }
    finally { setBusy(false); }
  };

  const check = async () => {
    setBusy(true); setErr(""); setNote("");
    try {
      await PB.User.reload();
      const u = PB.User.current().user;
      if (!u || !u.emailVerified) setErr("Not verified yet — open the link in the email, then try again.");
      // If verified, useUser re-renders and AccountApp swaps to the dashboard.
    } catch (ex) { setErr(authMsg(ex)); }
    finally { setBusy(false); }
  };

  return (
    <section className="section account-auth">
      <div className="wrap" style={{ maxWidth: 520 }}>
        <div className="account-card card" style={{ textAlign: "center" }}>
          <div className="account-verify-ic"><Icon name="mail" size={26} /></div>
          <h1 className="display-m">{t("Verify your email")}</h1>
          <p className="text-dim" style={{ marginTop: 10 }}>
            {t("We sent a verification link to")} <strong>{user.email}</strong>. {t("Click it to activate your account, then come back and continue.")}
          </p>

          {err && <div className="account-err mono" style={{ justifyContent: "center", marginTop: 18 }}><Icon name="x" size={13} /> {t(err)}</div>}
          {note && <div className="account-note mono" style={{ justifyContent: "center", marginTop: 18 }}><Icon name="check" size={13} /> {t(note)}</div>}

          <div className="account-verify-actions">
            <button className="btn btn-primary btn-block btn-lg" onClick={check} disabled={busy}>
              {busy ? t("Checking…") : t("I’ve verified — continue")} <Icon name="arrow" size={17} />
            </button>
            <button className="btn btn-ghost btn-block" onClick={resend} disabled={busy}>{t("Resend email")}</button>
            <button type="button" className="account-forgot mono" onClick={() => PB.User.signOut()}>{t("Sign out")}</button>
          </div>
        </div>
      </div>
    </section>
  );
}

function AccountApp() {
  const { ready, user, profile } = useUser();
  if (!ready) return <AccountLoading />;
  if (!user) return <AccountAuth />;
  if (!user.emailVerified) return <AccountVerify user={user} />;
  return <AccountDashboard user={user} profile={profile} />;
}

/* ---------------- "I'm interested" button (used on detail page) ---------------- */
function InterestButton({ id, className = "btn btn-ghost btn-block" }) {
  const { ready, user, profile } = useUser();
  const [busy, setBusy] = useState(false);
  const saved = !!(profile && Array.isArray(profile.interested) && profile.interested.includes(id));

  const onClick = async () => {
    // Send unauthenticated or unverified users to the account page to sign in / verify.
    if (!user || !user.emailVerified) { go("/account"); return; }
    setBusy(true);
    try { await PB.User.toggleInterest(id); } catch (ex) { alert(authMsg(ex)); } finally { setBusy(false); }
  };

  return (
    <button className={className + (saved ? " is-saved" : "")} onClick={onClick} disabled={busy || !ready}>
      <Icon name="heart" size={16} fill={saved} /> {saved ? t("Saved to your list") : t("I’m interested")}
    </button>
  );
}

Object.assign(window, { AccountApp, AccountAuth, AccountDashboard, AccountLoading, AccountVerify, InterestButton });
