// login.jsx
const { useState: useStateLG, useEffect: useEffectLG } = React;

const __LOGIN_CSS = `
  .lg-page {
    min-height: 100vh;
    display: grid;
    grid-template-columns: 1fr;
    position: relative;
  }
  .lg-left {
    display: flex; align-items: center; justify-content: center;
    padding: 80px 32px 48px;
    min-height: 100vh;
  }
  .lg-right {
    display: none;
    border-left: 1px solid var(--hairline);
    background:
      radial-gradient(circle at 20% 20%, color-mix(in oklab, var(--accent) 14%, transparent), transparent 50%),
      var(--surface);
    padding: 48px;
    align-items: center; justify-content: center;
    overflow: hidden;
    position: relative;
  }
  @media (min-width: 920px) {
    .lg-page { grid-template-columns: 1fr 1fr; }
    .lg-right { display: flex; }
  }

  .lg-card {
    width: 100%;
    max-width: 380px;
  }
  .lg-back {
    position: absolute; top: 24px; left: 24px;
    display: inline-flex; align-items: center; gap: 6px;
    color: var(--ink-2); font-size: 13px;
    padding: 6px 10px; border-radius: var(--r-sm);
  }
  .lg-back:hover { background: var(--hover); color: var(--ink); }

  .lg-brand-row { margin-bottom: 36px; }

  .lg-eyebrow {
    font-family: var(--font-mono);
    font-size: 11px;
    color: var(--muted);
    letter-spacing: 0.08em;
    text-transform: uppercase;
    margin-bottom: 8px;
  }
  .lg-h {
    font-size: 32px;
    font-weight: 400;
    line-height: 1.05;
    letter-spacing: -0.02em;
    margin: 0 0 12px;
  }
  .lg-h .accent {
    font-family: var(--font-serif); font-style: italic; color: var(--accent);
  }
  .lg-sub {
    color: var(--ink-2);
    font-size: 14.5px;
    line-height: 1.5;
    margin: 0 0 28px;
  }

  .lg-fields { display: flex; flex-direction: column; gap: 12px; margin-bottom: 16px; }

  .lg-tools-row {
    display: flex; align-items: center; justify-content: space-between;
    margin-bottom: 16px;
    font-size: 13px;
  }
  .lg-link {
    color: var(--accent);
    background: transparent; border: 0;
    padding: 4px 0;
    font-weight: 500;
  }
  .lg-link:hover { text-decoration: underline; text-underline-offset: 3px; }

  .lg-divider {
    display: flex; align-items: center; gap: 12px;
    margin: 20px 0;
    color: var(--muted);
    font-family: var(--font-mono);
    font-size: 11px;
    letter-spacing: 0.1em;
    text-transform: uppercase;
  }
  .lg-divider::before, .lg-divider::after {
    content: ""; flex: 1; height: 1px; background: var(--hairline);
  }

  .lg-switch {
    text-align: center;
    margin-top: 24px;
    color: var(--muted);
    font-size: 13.5px;
  }

  .lg-error {
    padding: 10px 12px;
    border-radius: var(--r-sm);
    background: color-mix(in oklab, var(--danger) 12%, transparent);
    color: var(--danger);
    font-size: 13px;
    border: 1px solid color-mix(in oklab, var(--danger) 30%, transparent);
    margin-bottom: 12px;
  }

  .lg-status {
    text-align: center;
    padding: 16px 0;
  }
  .lg-status-icon {
    width: 64px; height: 64px;
    border-radius: 50%;
    background: var(--accent-soft);
    color: var(--accent);
    display: grid; place-items: center;
    margin: 0 auto 20px;
  }

  /* Right pane decoration */
  .lg-quote-wrap {
    max-width: 480px;
    position: relative; z-index: 1;
  }
  .lg-quote-mark {
    font-family: var(--font-serif);
    font-style: italic;
    font-size: 96px;
    line-height: 1;
    color: var(--accent);
    margin-bottom: -24px;
  }
  .lg-quote {
    font-family: var(--font-serif);
    font-size: 28px;
    line-height: 1.3;
    color: var(--ink);
    letter-spacing: -0.015em;
    margin: 0 0 20px;
    font-weight: 400;
  }
  .lg-quote-italic { font-style: italic; }
  .lg-quote-cite {
    font-family: var(--font-mono);
    font-size: 11px;
    color: var(--muted);
    letter-spacing: 0.08em;
    text-transform: uppercase;
  }

  /* Mini illustration of a card library */
  .lg-cards {
    position: absolute; right: -120px; bottom: -200px;
    width: 380px; transform: rotate(-6deg);
    opacity: 0.28;
    pointer-events: none;
    z-index: 0;
  }
  .lg-card-strip {
    background: var(--bg);
    border: 1px solid var(--hairline);
    border-radius: 10px;
    padding: 14px 16px;
    display: flex; gap: 12px; align-items: center;
    margin-bottom: 12px;
    box-shadow: var(--shadow-sm);
    font-size: 12px;
  }
  .lg-card-fav {
    width: 24px; height: 24px; border-radius: 6px;
    background: var(--accent-soft); color: var(--accent);
    display: grid; place-items: center; font-size: 10px;
    flex-shrink: 0;
  }
  .lg-card-strip .t { font-weight: 500; }
  .lg-card-strip .h { color: var(--muted); font-family: var(--font-mono); font-size: 10px; }

  /* Google button */
  .lg-google {
    width: 100%;
    display: inline-flex; align-items: center; justify-content: center; gap: 10px;
  }
`;

function GoogleLogo({ size = 18 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
      <path fill="#4285F4" d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z" />
      <path fill="#34A853" d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" />
      <path fill="#FBBC05" d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z" />
      <path fill="#EA4335" d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z" />
    </svg>
  );
}

function LoginPage({ navigate, onAuth }) {
  const [mode, setMode] = useStateLG("login"); // login | register | forgot | sent | reset | reset-done
  const [email, setEmail] = useStateLG("");
  const [password, setPassword] = useStateLG("");
  const [newPassword, setNewPassword] = useStateLG("");
  const [name, setName] = useStateLG("");
  const [resetToken, setResetToken] = useStateLG(null);
  const [error, setError] = useStateLG(null);
  const [busy, setBusy] = useStateLG(false);

  // Detect password-reset link or OAuth error from query params
  useEffectLG(() => {
    const params = new URLSearchParams(window.location.search);
    if (params.get('action') === 'reset-password' && params.get('token')) {
      setResetToken(params.get('token'));
      setMode('reset');
    } else if (params.get('oauth_error')) {
      setError('Google sign-in failed. Please try again.');
      const url = new URL(window.location.href);
      url.searchParams.delete('oauth_error');
      window.history.replaceState({}, '', url.pathname + url.search + url.hash);
    }
  }, []);

  const switchTo = (m) => { setError(null); setMode(m); };

  const submit = async (e) => {
    e?.preventDefault();
    setError(null);
    setBusy(true);
    try {
      if (mode === "login") {
        if (!email || !password) { setError("Email and password are required"); setBusy(false); return; }
        const data = await api.login(email, password);
        onAuth(await api.resolveUser(data));
        navigate("/spaces");

      } else if (mode === "register") {
        if (!name || !email || !password) { setError("All fields are required"); setBusy(false); return; }
        if (password.length < 8) { setError("Password must be at least 8 characters"); setBusy(false); return; }
        const data = await api.register(email, password, name);
        onAuth(await api.resolveUser(data));
        navigate("/spaces");

      } else if (mode === "forgot") {
        if (!email) { setError("Email is required"); setBusy(false); return; }
        await api.forgotPassword(email);
        setBusy(false);
        switchTo("sent");

      } else if (mode === "reset") {
        if (!newPassword) { setError("New password is required"); setBusy(false); return; }
        if (newPassword.length < 8) { setError("Password must be at least 8 characters"); setBusy(false); return; }
        await api.resetPassword(resetToken, newPassword);
        // Clear the query params from the URL
        window.history.replaceState({}, '', window.location.pathname);
        setBusy(false);
        switchTo("reset-done");
      }
    } catch (err) {
      setError(err.message || "Something went wrong");
      setBusy(false);
    }
  };

  return (
    <div className="lg-page">
      <style>{__LOGIN_CSS}</style>

      {mode !== 'reset' && mode !== 'reset-done' && (
        <a className="lg-back" href="/" onClick={(e) => { e.preventDefault(); navigate("/"); }}>
          <I.ArrowL size={14} /> Back
        </a>
      )}

      <div className="lg-left">
        <div className="lg-card">
          <div className="lg-brand-row"><Brand /></div>

          {mode === "login" && (
            <>
              <div className="lg-eyebrow">Sign in</div>
              <h1 className="lg-h">Welcome <span className="accent">back.</span></h1>
              <p className="lg-sub">Pick up your library where you left off.</p>

              <form onSubmit={submit}>
                {error && <div className="lg-error">{error}</div>}
                <div className="lg-fields">
                  <input className="input" placeholder="you@example.com" type="email" autoComplete="email"
                         value={email} onChange={(e) => setEmail(e.target.value)} />
                  <input className="input" placeholder="Password" type="password" autoComplete="current-password"
                         value={password} onChange={(e) => setPassword(e.target.value)} />
                </div>
                <div className="lg-tools-row">
                  <span></span>
                  <button type="button" className="lg-link" onClick={() => switchTo("forgot")}>Forgot password?</button>
                </div>
                <button type="submit" className="btn btn-accent btn-lg" style={{ width: "100%" }} disabled={busy}>
                  {busy ? "Signing in…" : <>Sign in <I.ArrowR size={15} /></>}
                </button>
              </form>

              <div className="lg-divider">or</div>
              <button className="btn btn-outline btn-lg lg-google"
                      onClick={() => { try { api.startGoogleLogin(); } catch (err) { setError(err.message); } }}>
                <GoogleLogo /> Continue with Google
              </button>

              <p className="lg-switch">
                Don't have an account?{" "}
                <button className="lg-link" onClick={() => switchTo("register")}>Create one</button>
              </p>
            </>
          )}

          {mode === "register" && (
            <>
              <div className="lg-eyebrow">Create account</div>
              <h1 className="lg-h">Start a new <span className="accent">library.</span></h1>
              <p className="lg-sub">Free, no credit card. Import your bookmarks once you're in.</p>

              <form onSubmit={submit}>
                {error && <div className="lg-error">{error}</div>}
                <div className="lg-fields">
                  <input className="input" placeholder="Your name" autoComplete="name"
                         value={name} onChange={(e) => setName(e.target.value)} />
                  <input className="input" placeholder="you@example.com" type="email" autoComplete="email"
                         value={email} onChange={(e) => setEmail(e.target.value)} />
                  <input className="input" placeholder="Password (at least 8 characters)" type="password" autoComplete="new-password"
                         value={password} onChange={(e) => setPassword(e.target.value)} />
                </div>
                <button type="submit" className="btn btn-accent btn-lg" style={{ width: "100%" }} disabled={busy}>
                  {busy ? "Creating account…" : <>Create account <I.ArrowR size={15} /></>}
                </button>
              </form>

              <div className="lg-divider">or</div>
              <button className="btn btn-outline btn-lg lg-google"
                      onClick={() => { try { api.startGoogleLogin(); } catch (err) { setError(err.message); } }}>
                <GoogleLogo /> Continue with Google
              </button>

              <p className="lg-switch">
                Already have an account?{" "}
                <button className="lg-link" onClick={() => switchTo("login")}>Sign in</button>
              </p>
            </>
          )}

          {mode === "forgot" && (
            <>
              <div className="lg-eyebrow">Reset password</div>
              <h1 className="lg-h">Send me a <span className="accent">new key.</span></h1>
              <p className="lg-sub">We'll email you a reset link if there's an account.</p>

              <form onSubmit={submit}>
                {error && <div className="lg-error">{error}</div>}
                <div className="lg-fields">
                  <input className="input" placeholder="Your account email" type="email" autoComplete="email"
                         value={email} onChange={(e) => setEmail(e.target.value)} />
                </div>
                <button type="submit" className="btn btn-accent btn-lg" style={{ width: "100%" }} disabled={busy}>
                  {busy ? "Sending…" : "Send reset link"}
                </button>
              </form>

              <p className="lg-switch">
                <button className="lg-link" onClick={() => switchTo("login")}>Back to sign in</button>
              </p>
            </>
          )}

          {mode === "sent" && (
            <div className="lg-status">
              <div className="lg-status-icon"><I.Mail size={26} /></div>
              <h2 className="lg-h" style={{ fontSize: 24, marginBottom: 8 }}>Check your <span className="accent">inbox.</span></h2>
              <p className="lg-sub">If an account exists for <strong>{email}</strong>, a reset link is on its way.</p>
              <button className="btn btn-primary btn-lg" style={{ width: "100%" }} onClick={() => switchTo("login")}>
                Back to sign in
              </button>
            </div>
          )}

          {mode === "reset" && (
            <>
              <div className="lg-eyebrow">Set new password</div>
              <h1 className="lg-h">Choose a new <span className="accent">password.</span></h1>
              <p className="lg-sub">Enter your new password below to complete the reset.</p>

              <form onSubmit={submit}>
                {error && <div className="lg-error">{error}</div>}
                <div className="lg-fields">
                  <input className="input" placeholder="New password (at least 8 characters)" type="password" autoComplete="new-password"
                         value={newPassword} onChange={(e) => setNewPassword(e.target.value)} />
                </div>
                <button type="submit" className="btn btn-accent btn-lg" style={{ width: "100%" }} disabled={busy}>
                  {busy ? "Saving…" : "Set new password"}
                </button>
              </form>
            </>
          )}

          {mode === "reset-done" && (
            <div className="lg-status">
              <div className="lg-status-icon"><I.Check size={26} /></div>
              <h2 className="lg-h" style={{ fontSize: 24, marginBottom: 8 }}>Password <span className="accent">updated.</span></h2>
              <p className="lg-sub">Your password has been changed. You can now sign in with your new password.</p>
              <button className="btn btn-accent btn-lg" style={{ width: "100%" }} onClick={() => switchTo("login")}>
                Sign in
              </button>
            </div>
          )}
        </div>
      </div>

      {/* ── Right pane: editorial quote + card illustration ── */}
      <aside className="lg-right" aria-hidden="true">
        <div className="lg-quote-wrap">
          <div className="lg-quote-mark">"</div>
          <p className="lg-quote">
            A bookmark is <span className="lg-quote-italic">a promise to your future self</span> — and a personal library is the keeping of that promise.
          </p>
          <div className="lg-quote-cite">From the BUKMAK Handbook</div>
        </div>

        <div className="lg-cards">
          {[
            { fav: "T", title: "The Anatomy of Typography", host: "typewolf.com" },
            { fav: "R", title: "Refactoring UI", host: "refactoringui.com" },
            { fav: "L", title: "Linear — Method", host: "linear.app" },
            { fav: "A", title: "Are.na — Modern Library", host: "are.na" },
            { fav: "P", title: "Why I Write", host: "paulgraham.com" },
          ].map((c, i) => (
            <div key={i} className="lg-card-strip">
              <div className="lg-card-fav">{c.fav}</div>
              <div>
                <div className="t">{c.title}</div>
                <div className="h">{c.host}</div>
              </div>
            </div>
          ))}
        </div>
      </aside>
    </div>
  );
}

window.LoginPage = LoginPage;
