// ─────────────────────────────────────────────────────────────
// Auth modal — email/password login, signup, forgot password.
// ─────────────────────────────────────────────────────────────
function AuthModal({ open, onClose, onAuthed }) {
  const [mode, setMode] = React.useState("signup"); // 'signup' | 'login' | 'forgot'
  const [email, setEmail] = React.useState("");
  const [password, setPassword] = React.useState("");
  const [busy, setBusy] = React.useState(false);
  const [error, setError] = React.useState("");
  const [info, setInfo] = React.useState("");

  React.useEffect(() => {
    if (open) { setError(""); setInfo(""); setBusy(false); }
  }, [open, mode]);

  if (!open) return null;

  const ready = window.SUPABASE_READY;

  async function submit(e) {
    e.preventDefault();
    setError(""); setInfo("");
    if (!ready) { setError("Accounts aren't connected yet. Add your Supabase keys in supabase-config.js."); return; }
    setBusy(true);
    try {
      const sb = window.supabaseClient;
      if (mode === "forgot") {
        const { error } = await sb.auth.resetPasswordForEmail(email, { redirectTo: window.location.origin + window.location.pathname });
        if (error) throw error;
        setInfo("Password reset link sent — check your email.");
      } else if (mode === "signup") {
        const { data, error } = await sb.auth.signUp({ email, password });
        if (error) throw error;
        if (data.session) {
          onAuthed && onAuthed(data.user);   // instant session → flush + redirect
        } else {
          setInfo("Account created. Check your email to confirm, then log in — your plan is saved and waiting.");
        }
      } else {
        const { data, error } = await sb.auth.signInWithPassword({ email, password });
        if (error) throw error;
        onAuthed && onAuthed(data.user);
      }
    } catch (err) {
      setError(err.message || "Something went wrong. Please try again.");
    } finally {
      setBusy(false);
    }
  }

  const titles = { signup: "Create your free account", login: "Welcome back", forgot: "Reset your password" };
  const subs = {
    signup: "Save your card history and plan — free, no card required.",
    login: "Log in to see your saved plan and dashboard.",
    forgot: "We'll email you a link to set a new password.",
  };

  return (
    <div className="modal-overlay" onMouseDown={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="modal" role="dialog" aria-modal="true">
        <button className="modal-close" onClick={onClose} aria-label="Close">×</button>
        <div className="modal-head">
          <h2>{titles[mode]}</h2>
          <p>{subs[mode]}</p>
        </div>

        {!ready && (
          <div className="modal-note">
            Demo mode — connect Supabase (see <code>supabase-config.js</code>) to enable real accounts.
          </div>
        )}

        <form onSubmit={submit}>
          <div className="field" style={{ marginBottom: 16 }}>
            <label className="field-label" style={{ fontSize: "0.95rem" }}>Email</label>
            <input className="input" type="email" required value={email}
              onChange={(e) => setEmail(e.target.value)} placeholder="you@email.com" autoFocus />
          </div>

          {mode !== "forgot" && (
            <div className="field" style={{ marginBottom: 16 }}>
              <label className="field-label" style={{ fontSize: "0.95rem" }}>Password</label>
              <input className="input" type="password" required minLength={6} value={password}
                onChange={(e) => setPassword(e.target.value)} placeholder="At least 6 characters" />
            </div>
          )}

          {error && <div className="modal-error">{error}</div>}
          {info && <div className="modal-info">{info}</div>}

          <button className="btn btn-primary" type="submit" disabled={busy} style={{ width: "100%", marginTop: 6 }}>
            {busy ? "Working…" : mode === "signup" ? "Create account" : mode === "login" ? "Log in" : "Send reset link"}
          </button>
        </form>

        <div className="modal-foot">
          {mode === "signup" && (
            <span>Already have an account? <button className="link-btn" onClick={() => setMode("login")}>Log in</button></span>
          )}
          {mode === "login" && (
            <>
              <span>New here? <button className="link-btn" onClick={() => setMode("signup")}>Create account</button></span>
              <button className="link-btn" onClick={() => setMode("forgot")}>Forgot password?</button>
            </>
          )}
          {mode === "forgot" && (
            <span><button className="link-btn" onClick={() => setMode("login")}>← Back to log in</button></span>
          )}
        </div>
        <p className="modal-disclaimer">General information only — not financial advice.</p>
      </div>
    </div>
  );
}

window.AuthModal = AuthModal;
