/* Account settings — name, email, password (email/password changes are
 * two-step: request mails a confirmation link, nothing changes until it's
 * clicked), and a per-sport team-preferences summary that links out to the
 * restricted single-sport editor (src/onboarding.jsx's restrictToSport mode).
 * Lives at "/account", opened from the user menu's "Edit account". Guests
 * have no server account, so they only see the team-preferences section. */

const { useState: useAcctState, useEffect: useAcctEffect } = React;

const EMAIL_RE = /^\S+@\S+\.\S+$/;

function acctTeamSwatch(sportId, abbr) {
  if (!abbr) return null;
  const bundle = window.W2R4_getLeague ? window.W2R4_getLeague(sportId) : null;
  return bundle?.TEAM_COLOR_FALLBACK?.[abbr] || "#999999";
}

function AccountSettings({ user, onClose, onUserUpdated }) {
  const isGuest = !!user?.isGuest;
  const prefs = window.W2R4TeamPrefs.loadTeamPrefs();

  // Same guest→real-account path as the header's "Sign up to save your team":
  // drop the guest session and land back on the auth screen. Team prefs live
  // under their own localStorage key (not the session), so picks made as a
  // guest carry straight into the new account.
  const convertGuest = () => {
    window.W2R4_Auth.serverLogout();
    window.W2R4_Auth.clearSession();
    window.location.assign("/");
  };

  const [name, setName] = useAcctState(user?.name || "");
  const [nameStatus, setNameStatus] = useAcctState(null);
  const [nameBusy, setNameBusy] = useAcctState(false);

  const saveName = async (e) => {
    e && e.preventDefault();
    const nm = name.trim();
    if (!nm) { setNameStatus({ ok: false, msg: "Tell us what to call you" }); return; }
    setNameBusy(true);
    const res = await window.W2R4_Auth.serverUpdateName({ name: nm });
    setNameBusy(false);
    if (res.unavailable) { setNameStatus({ ok: false, msg: "Not available right now. Try again later." }); return; }
    if (res.ok && res.data.user) {
      const updated = { ...user, name: res.data.user.name };
      window.W2R4_Auth.saveSession(updated);
      onUserUpdated(updated);
      setNameStatus({ ok: true, msg: "Saved." });
    } else {
      setNameStatus({ ok: false, msg: "Something went wrong. Try again." });
    }
  };

  const [newEmail, setNewEmail] = useAcctState("");
  const [emailStatus, setEmailStatus] = useAcctState(null);
  const [emailBusy, setEmailBusy] = useAcctState(false);

  const requestEmailChange = async (e) => {
    e && e.preventDefault();
    const key = newEmail.trim().toLowerCase();
    if (!EMAIL_RE.test(key)) { setEmailStatus({ ok: false, msg: "That doesn't look like an email" }); return; }
    setEmailBusy(true);
    const res = await window.W2R4_Auth.serverRequestEmailChange({ newEmail: key });
    setEmailBusy(false);
    if (res.unavailable) { setEmailStatus({ ok: false, msg: "Email changes aren't available right now. Try again later." }); return; }
    if (res.ok) {
      setEmailStatus({ ok: true, msg: `Check ${key} for a link to confirm the change.` });
      setNewEmail("");
      return;
    }
    const code = res.data && res.data.error;
    setEmailStatus({
      ok: false,
      msg:
        code === "exists" ? "That email is already in use." :
        code === "unchanged" ? "That's already your email." :
        code === "email" ? "That doesn't look like an email" :
        "Something went wrong. Try again.",
    });
  };

  const [currentPw, setCurrentPw] = useAcctState("");
  const [newPw, setNewPw] = useAcctState("");
  const [newPw2, setNewPw2] = useAcctState("");
  const [pwStatus, setPwStatus] = useAcctState(null);
  const [pwBusy, setPwBusy] = useAcctState(false);

  const requestPasswordChange = async (e) => {
    e && e.preventDefault();
    if (newPw.length < 6) { setPwStatus({ ok: false, msg: "At least 6 characters" }); return; }
    if (newPw !== newPw2) { setPwStatus({ ok: false, msg: "New passwords don't match" }); return; }
    setPwBusy(true);
    const res = await window.W2R4_Auth.serverRequestPasswordChange({ currentPassword: currentPw, newPassword: newPw });
    setPwBusy(false);
    if (res.unavailable) { setPwStatus({ ok: false, msg: "Password changes aren't available right now. Try again later." }); return; }
    if (res.ok) {
      setPwStatus({ ok: true, msg: "Check your email for a link to confirm the change." });
      setCurrentPw(""); setNewPw(""); setNewPw2("");
      return;
    }
    const code = res.data && res.data.error;
    setPwStatus({
      ok: false,
      msg:
        code === "current_password" ? "Current password doesn't match." :
        code === "password" ? "At least 6 characters" :
        "Something went wrong. Try again.",
    });
  };

  return (
    <div className="ts-shell">
      <div className="ts-inner">
        <div className="page-head">
          <div>
            <div className="eyebrow">Your account</div>
            <h1>Account settings</h1>
            <div className="sub">Update your name, email, password, and team preferences.</div>
          </div>
          <button className="btn ghost" style={{ flexShrink: 0 }} onClick={onClose}>Back</button>
        </div>

        {isGuest &&
        <div className="acct-section">
          <div className="acct-section-title">You're browsing as a guest</div>
          <p className="acct-note">Sign up to set a name, email, and password — and keep your picks across devices.</p>
          <button className="btn primary" onClick={convertGuest}>Sign up</button>
        </div>
        }

        {!isGuest &&
        <>
          <form className="acct-section" onSubmit={saveName}>
            <div className="acct-section-title">Name</div>
            <div className="acct-row">
              <input className="auth-input" type="text" value={name}
                onChange={(e) => setName(e.target.value)} placeholder="Your name" />
              <button className="btn primary" type="submit" disabled={nameBusy}>
                {nameBusy ? "Saving…" : "Save"}
              </button>
            </div>
            {nameStatus && <span className={"auth-hint" + (nameStatus.ok ? "" : " err")}>{nameStatus.msg}</span>}
          </form>

          <form className="acct-section" onSubmit={requestEmailChange}>
            <div className="acct-section-title">Email</div>
            <div className="acct-current">Current: {user.email}</div>
            <div className="acct-row">
              <input className="auth-input" type="email" value={newEmail}
                onChange={(e) => setNewEmail(e.target.value)} placeholder="New email address" />
              <button className="btn primary" type="submit" disabled={emailBusy}>
                {emailBusy ? "Sending…" : "Send verification link"}
              </button>
            </div>
            <p className="acct-note">We'll email a confirmation link to the new address — it won't take effect until you click it.</p>
            {emailStatus && <span className={"auth-hint" + (emailStatus.ok ? "" : " err")}>{emailStatus.msg}</span>}
          </form>

          <form className="acct-section" onSubmit={requestPasswordChange}>
            <div className="acct-section-title">Password</div>
            <input className="auth-input" type="password" value={currentPw}
              onChange={(e) => setCurrentPw(e.target.value)} placeholder="Current password" />
            <input className="auth-input" type="password" value={newPw}
              onChange={(e) => setNewPw(e.target.value)} placeholder="New password (at least 6 characters)" />
            <input className="auth-input" type="password" value={newPw2}
              onChange={(e) => setNewPw2(e.target.value)} placeholder="Confirm new password" />
            <button className="btn primary" type="submit" disabled={pwBusy}>
              {pwBusy ? "Sending…" : "Update password"}
            </button>
            <p className="acct-note">We'll email a confirmation link to {user.email} — your password won't change until you click it.</p>
            {pwStatus && <span className={"auth-hint" + (pwStatus.ok ? "" : " err")}>{pwStatus.msg}</span>}
          </form>
        </>
        }

        <div className="acct-section">
          <div className="acct-section-title">Team preferences</div>
          <div className="acct-team-list">
            {window.SPORTS.map((s) => {
              const pick = prefs.bySport[s.id];
              const swatch = pick?.favTeam ? acctTeamSwatch(s.id, pick.favTeam) : null;
              return (
                <div className="acct-team-row" key={s.id}>
                  <span className="acct-team-sport"><s.Icon size={20} /> {s.name}</span>
                  <span className="acct-team-summary">
                    {pick?.favTeam ?
                    <>
                      <span className="acct-team-pill" style={{ background: swatch }}>{pick.favTeam}</span>
                      {pick.dislikes?.length ? `${pick.dislikes.length} rival${pick.dislikes.length === 1 ? "" : "s"}` : "No rivals set"}
                    </> :
                    "Not set"}
                  </span>
                  <button className="btn ghost" onClick={() => window.location.assign("/?edit=" + s.id)}>Edit</button>
                </div>);

            })}
          </div>
        </div>
      </div>
    </div>);

}

// The page an email/password change confirmation link (mailed by
// request-email-change.js / request-password-change.js) lands on. No
// session required — the token in the link is the proof.
function AccountConfirm() {
  const params = new URLSearchParams(location.search);
  const type = params.get("type");
  const token = params.get("token") || "";
  const [status, setStatus] = useAcctState("working"); // working | ok | error
  const [msg, setMsg] = useAcctState("");

  useAcctEffect(() => {
    (async () => {
      if (!token || (type !== "email" && type !== "password")) {
        setStatus("error");
        setMsg("This confirmation link is invalid.");
        return;
      }
      const res = type === "email" ?
        await window.W2R4_Auth.serverConfirmEmailChange({ token }) :
        await window.W2R4_Auth.serverConfirmPasswordChange({ token });

      if (res.unavailable) {
        setStatus("error");
        setMsg("This isn't available right now. Please try again later.");
        return;
      }
      if (res.ok) {
        if (type === "email" && res.data.user) {
          const cur = window.W2R4_Auth.loadSession();
          window.W2R4_Auth.saveSession({ ...cur, email: res.data.user.email, name: res.data.user.name });
        }
        setStatus("ok");
        setMsg(type === "email" ? "Your email has been updated." : "Your password has been updated.");
        return;
      }
      setStatus("error");
      setMsg("This confirmation link is invalid or has expired.");
    })();
  }, []);

  return (
    <div className="w2r4-boot">
      <div className={"w2r4-boot-card" + (status === "error" ? " error" : "")}>
        <div className="w2r4-boot-title">
          {status === "working" ? "Confirming…" : status === "ok" ? "All set" : "Couldn't confirm"}
        </div>
        <div className="w2r4-boot-sub">{status === "working" ? "One moment." : msg}</div>
        {status === "working" && <div className="w2r4-boot-bar"><span /></div>}
        {status !== "working" &&
        <button className="w2r4-boot-retry" onClick={() => window.location.assign("/account")}>
          Go to account settings
        </button>
        }
      </div>
    </div>);

}

window.AccountSettings = AccountSettings;
window.AccountConfirm = AccountConfirm;
