/* global React, Icons, RBAuth, useAuth */
// ============================================================
//  Auth — sign in / sign up modal + nav account control
//  Open from anywhere:  window.requestAuth({ mode, next })
// ============================================================
const { useState: useStateAuth, useEffect: useEffectAuth } = React;

window.requestAuth = (opts) =>
  window.dispatchEvent(new CustomEvent("rb-auth-open", { detail: opts || {} }));

const isEmailA = (s) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(s);

function AuthModal({ mode: initMode, next, onClose }) {
  const [mode, setMode] = useStateAuth(initMode === "signup" ? "signup" : "signin");
  const [name, setName] = useStateAuth("");
  const [email, setEmail] = useStateAuth("");
  const [pw, setPw] = useStateAuth("");
  const [busy, setBusy] = useStateAuth(false);
  const [err, setErr] = useStateAuth("");
  const [info, setInfo] = useStateAuth("");

  useEffectAuth(() => {
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    document.addEventListener("keydown", onKey);
    return () => document.removeEventListener("keydown", onKey);
  }, []);

  const submit = async (e) => {
    e.preventDefault();
    setErr(""); setInfo("");
    if (!isEmailA(email)) { setErr("Enter a valid email address."); return; }
    if (pw.length < 6) { setErr("Password must be at least 6 characters."); return; }
    setBusy(true);
    try {
      if (mode === "signup") {
        const r = await RBAuth.signUp(email.trim(), pw, name.trim());
        if (r && r.user && !r.session) {
          setInfo("Check your inbox to confirm your email, then sign in.");
          setMode("signin"); setBusy(false); return;
        }
      } else {
        await RBAuth.signIn(email.trim(), pw);
      }
      setBusy(false);
      if (typeof next === "function") setTimeout(next, 30);
      onClose();
    } catch (e2) {
      setBusy(false);
      setErr((e2 && e2.message) || "Something went wrong. Please try again.");
    }
  };

  const magic = async () => {
    setErr(""); setInfo("");
    if (!isEmailA(email)) { setErr("Enter your email first."); return; }
    setBusy(true);
    try { await RBAuth.magicLink(email.trim()); setInfo("Magic link sent — check your email."); }
    catch (e2) { setErr((e2 && e2.message) || "Could not send link."); }
    setBusy(false);
  };

  return (
    <div className="up-scrim" onMouseDown={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="up-modal auth-modal" role="dialog" aria-modal="true">
        <div className="up-head">
          <button className="up-close" onClick={onClose} aria-label="Close"><Icons.close size={16} /></button>
          <span className="up-head-badge"><Icons.pen size={13} /> get-resume.com</span>
          <h3>{mode === "signup" ? "Create your account" : "Welcome back"}</h3>
          <p>{mode === "signup"
            ? "Save your résumés to the cloud and unlock Pro."
            : "Sign in to access your saved résumés and Pro."}</p>
        </div>
        <div className="up-body">
          <form className="auth-form" onSubmit={submit} noValidate>
            {mode === "signup" && (
              <label className="auth-field">
                <span>Name</span>
                <input value={name} onChange={(e) => setName(e.target.value)} placeholder="Jordan Rivera" autoComplete="name" />
              </label>
            )}
            <label className="auth-field">
              <span>Email</span>
              <input type="email" value={email} onChange={(e) => setEmail(e.target.value)} placeholder="you@email.com" autoComplete="email" />
            </label>
            <label className="auth-field">
              <span>Password</span>
              <input type="password" value={pw} onChange={(e) => setPw(e.target.value)} placeholder="••••••••" autoComplete={mode === "signup" ? "new-password" : "current-password"} />
            </label>

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

            <button className="btn btn-primary auth-submit" type="submit" disabled={busy}>
              {busy ? "Please wait…" : (mode === "signup" ? "Create account" : "Sign in")} <Icons.arrow size={16} />
            </button>
            <button type="button" className="auth-magic" onClick={magic} disabled={busy}>
              <Icons.mail size={14} /> Email me a magic link instead
            </button>
          </form>

          <div className="auth-switch">
            {mode === "signup" ? (
              <>Already have an account? <button onClick={() => { setMode("signin"); setErr(""); setInfo(""); }}>Sign in</button></>
            ) : (
              <>New here? <button onClick={() => { setMode("signup"); setErr(""); setInfo(""); }}>Create an account</button></>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

// Mounted once at app root; listens for rb-auth-open.
function AuthGate() {
  const [state, setState] = useStateAuth(null);
  useEffectAuth(() => {
    const h = (e) => setState((e.detail) || {});
    window.addEventListener("rb-auth-open", h);
    return () => window.removeEventListener("rb-auth-open", h);
  }, []);
  if (!state) return null;
  if (!RBAuth.enabled()) {
    // backend not configured — let the user know, don't trap them
    return (
      <div className="up-scrim" onMouseDown={() => setState(null)}>
        <div className="up-modal auth-modal" role="dialog" aria-modal="true">
          <div className="up-head">
            <button className="up-close" onClick={() => setState(null)} aria-label="Close"><Icons.close size={16} /></button>
            <span className="up-head-badge"><Icons.pen size={13} /> Demo mode</span>
            <h3>Accounts aren't connected yet</h3>
            <p>Add your Supabase keys in <b>config.js</b> to enable real sign-in. Until then the app runs locally on this device.</p>
          </div>
        </div>
      </div>
    );
  }
  return <AuthModal mode={state.mode} next={state.next} onClose={() => setState(null)} />;
}

// Nav control: shows Sign in, or the account menu when logged in.
function AccountButton() {
  const { user, enabled } = useAuth();
  const [open, setOpen] = useStateAuth(false);
  if (!enabled) return null;            // hide entirely in demo mode
  if (!user) {
    return (
      <button className="btn btn-quiet btn-sm nav-auth" onClick={() => window.requestAuth({ mode: "signin" })}>
        <Icons.user size={14} /> Sign in
      </button>
    );
  }
  const label = (user.user_metadata && user.user_metadata.full_name) || user.email;
  const initial = (label || "?").trim().charAt(0).toUpperCase();
  return (
    <div className="acct-wrap">
      <button className="acct-chip" onClick={() => setOpen((o) => !o)} title={user.email}>
        <span className="acct-av">{initial}</span>
      </button>
      {open && (
        <div className="acct-menu" onMouseLeave={() => setOpen(false)}>
          <div className="acct-id"><b>{label}</b><span>{user.email}</span></div>
          <button className="acct-item" onClick={() => { setOpen(false); window.RBAuth.signOut(); }}>
            <Icons.arrowL size={14} /> Sign out
          </button>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { AuthModal, AuthGate, AccountButton });
