/* =========================================================================
   TAXR — Auth (sign up / sign in) — wired to Waddl3 ID (Firebase Auth)
   ========================================================================= */
function Auth({ nav, params, account, onAuth }) {
  const [mode, setMode]   = useState(params.mode || "signup");
  const [name, setName]   = useState("");
  const [email, setEmail] = useState("");
  const [pw, setPw]       = useState("");
  const [err, setErr]     = useState("");
  const [busy, setBusy]   = useState(false);

  const isSignup = mode === "signup";
  const valid    = email.includes("@") && pw.length >= 6 && (!isSignup || name.trim());

  function afterAuth(firebaseUser, displayName) {
    onAuth({
      name:  displayName || firebaseUser.displayName || firebaseUser.email.split("@")[0],
      email: firebaseUser.email,
      uid:   firebaseUser.uid,
    });
    if (params.plan === "full") nav("checkout", { plan: "full" });
    else if (isSignup)          nav("onboarding");
    else                        nav("dashboard");
  }

  async function signInWithGoogle() {
    if (!window.taxrAuth) return;
    setErr(""); setBusy(true);
    try {
      const provider = new firebase.auth.GoogleAuthProvider();
      const result   = await window.taxrAuth.signInWithPopup(provider);
      afterAuth(result.user, result.user.displayName);
    } catch (e) {
      setErr(e.message);
    } finally {
      setBusy(false);
    }
  }

  async function submit(e) {
    e && e.preventDefault();
    if (!valid || !window.taxrAuth) return;
    setErr(""); setBusy(true);
    try {
      let result;
      if (isSignup) {
        result = await window.taxrAuth.createUserWithEmailAndPassword(email, pw);
        await result.user.updateProfile({ displayName: name.trim() });
        afterAuth(result.user, name.trim());
      } else {
        result = await window.taxrAuth.signInWithEmailAndPassword(email, pw);
        afterAuth(result.user, result.user.displayName);
      }
    } catch (e) {
      const msgs = {
        "auth/email-already-in-use":    "An account with that email already exists.",
        "auth/wrong-password":          "Incorrect password.",
        "auth/user-not-found":          "No account found with that email.",
        "auth/weak-password":           "Password must be at least 6 characters.",
        "auth/invalid-email":           "Please enter a valid email address.",
        "auth/too-many-requests":       "Too many attempts. Try again later.",
      };
      setErr(msgs[e.code] || e.message);
    } finally {
      setBusy(false);
    }
  }

  return (
    <div style={{ minHeight: "100vh", display: "grid", gridTemplateColumns: "1.1fr 1fr" }}>
      {/* left — brand panel */}
      <div className="grid-tex col" style={{ padding: "48px 56px", borderRight: "1px solid var(--line)", position: "relative", overflow: "hidden" }}>
        <div style={{ position: "absolute", top: -160, left: -120, width: 480, height: 480, borderRadius: "50%",
          background: "radial-gradient(circle, rgba(58,109,240,0.16), transparent 65%)", pointerEvents: "none" }} />
        <button className="row gap-8" onClick={() => nav("landing")} style={{ color: "var(--muted)", marginBottom: "auto" }}>
          <Icon name="back" size={17} /> <Logo />
        </button>
        <div style={{ maxWidth: 420 }}>
          <h1 className="display" style={{ fontSize: 44 }}>
            {isSignup ? <>Start your path to <span className="it">Enrolled Agent.</span></> : <>Welcome back to <span className="it">Taxr.</span></>}
          </h1>
          <div className="col gap-16" style={{ marginTop: 32 }}>
            {[
              ["94 lessons", "Across 3 phases — zero knowledge to EA-ready."],
              ["18 tests",   "Prove it stuck before you move on."],
              ["Lifetime access", "Buy once. Yours forever, updated yearly."],
            ].map(([t, x]) => (
              <div key={t} className="row gap-12">
                <Icon name="check" size={18} style={{ color: "var(--green)", marginTop: 3, flex: "none" }} />
                <div className="col"><span style={{ fontWeight: 600 }}>{t}</span><span className="fs-14 t-muted">{x}</span></div>
              </div>
            ))}
          </div>
        </div>
        <div style={{ marginTop: "auto", paddingTop: 40 }}>
          <Pip tone="cheer" compact>{isSignup ? "Great to have you. Your first two lessons are already free — let's go!" : "Good to see you again. Let's keep the streak going."}</Pip>
        </div>
      </div>

      {/* right — form */}
      <div className="col center" style={{ padding: 48, background: "var(--bg-2)" }}>
        <form onSubmit={submit} className="col" style={{ width: "100%", maxWidth: 380, gap: 18 }}>
          <div className="col" style={{ gap: 6, marginBottom: 6 }}>
            <h2 className="serif" style={{ fontSize: 28 }}>{isSignup ? "Create your account" : "Sign in"}</h2>
            <p className="fs-14 t-muted">{isSignup ? "Free to start — no card required." : "Pick up where you left off."}</p>
          </div>

          {/* Waddl3 ID = Google sign-in */}
          <button type="button" className="btn btn-ghost btn-block" onClick={signInWithGoogle} disabled={busy} style={{ gap: 10 }}>
            <span style={{ fontSize: 17 }}>🐧</span> Continue with Waddl3 ID
          </button>
          <div className="row gap-12" style={{ color: "var(--faint)" }}>
            <div className="hr" style={{ flex: 1 }} /><span className="mono fs-13">OR</span><div className="hr" style={{ flex: 1 }} />
          </div>

          {isSignup && (
            <div className="field"><label>Name</label>
              <input className="input" value={name} onChange={(e) => setName(e.target.value)} placeholder="Your name" /></div>
          )}
          <div className="field"><label>Email</label>
            <input className="input" type="email" value={email} onChange={(e) => setEmail(e.target.value)} placeholder="you@email.com" /></div>
          <div className="field"><label>Password</label>
            <input className="input" type="password" value={pw} onChange={(e) => setPw(e.target.value)} placeholder="6+ characters" /></div>

          {err && <p className="fs-13" style={{ color: "var(--red, #ef4444)", marginTop: -4 }}>{err}</p>}

          <Button type="submit" block size="lg" arrow disabled={!valid || busy} style={{ marginTop: 4 }}>
            {busy ? "Please wait…" : isSignup ? "Create account" : "Sign in"}
          </Button>

          <p className="fs-14 t-muted center" style={{ justifyContent: "center", gap: 6 }}>
            {isSignup ? "Already have an account?" : "New to Taxr?"}
            <button type="button" className="t-blue" style={{ fontWeight: 600 }} onClick={() => { setMode(isSignup ? "login" : "signup"); setErr(""); }}>
              {isSignup ? "Sign in" : "Create one"}
            </button>
          </p>
          <p className="fs-13 t-muted center" style={{ justifyContent: "center" }}>
            Your Waddl3 ID works across all Waddl3 apps.{" "}
            <a href="/account" className="t-blue" target="_blank" rel="noopener">Learn more</a>
          </p>
        </form>
      </div>
    </div>
  );
}

Object.assign(window, { Auth });
