/* eslint-disable */
(function () {
  const { useState, useEffect } = React;

  // Inject self-contained theme vars — independent of the app's warm palette
  const themeStyle = document.createElement('style');
  themeStyle.textContent = `
    :root {
      --a-bg:       #F5F5F7;
      --a-surface:  #FFFFFF;
      --a-border:   #D1D1D6;
      --a-input:    #FFFFFF;
      --a-text:     #1D1D1F;
      --a-muted:    #6E6E73;
      --a-accent:   #0071E3;
      --a-btn-text: #FFFFFF;
      --a-err-bg:   rgba(220,38,38,0.07);
      --a-err-bd:   rgba(220,38,38,0.18);
      --a-err-tx:   #B91C1C;
      --a-ok-bg:    rgba(22,163,74,0.07);
      --a-ok-bd:    rgba(22,163,74,0.2);
      --a-ok-tx:    #15803D;
      --a-ring:     rgba(0,113,227,0.25);
    }
    @media (prefers-color-scheme: dark) {
      :root {
        --a-bg:       #1C1C1E;
        --a-surface:  #2C2C2E;
        --a-border:   #3A3A3C;
        --a-input:    #1C1C1E;
        --a-text:     #F5F5F7;
        --a-muted:    #8E8E93;
        --a-accent:   #0A84FF;
        --a-btn-text: #FFFFFF;
        --a-err-bg:   rgba(248,113,113,0.1);
        --a-err-bd:   rgba(248,113,113,0.2);
        --a-err-tx:   #FCA5A5;
        --a-ok-bg:    rgba(74,222,128,0.1);
        --a-ok-bd:    rgba(74,222,128,0.2);
        --a-ok-tx:    #86EFAC;
        --a-ring:     rgba(10,132,255,0.3);
      }
    }
    @keyframes a-spin { to { transform: rotate(360deg); } }
    .a-input {
      display: block; width: 100%; padding: 9px 12px;
      background: var(--a-input); border: 1px solid var(--a-border);
      border-radius: 8px; font-size: 14px; color: var(--a-text);
      font-family: inherit; box-sizing: border-box; outline: none;
      transition: border-color 0.15s, box-shadow 0.15s;
    }
    .a-input:focus {
      border-color: var(--a-accent);
      box-shadow: 0 0 0 3px var(--a-ring);
    }
    .a-input::placeholder { color: var(--a-muted); opacity: 0.7; }
    .a-btn-link {
      background: none; border: none; padding: 0;
      color: var(--a-accent); cursor: pointer; font-size: 13px;
      font-weight: 500; font-family: inherit;
    }
    .a-btn-link:hover { text-decoration: underline; }
  `;
  document.head.appendChild(themeStyle);

  // ── Wordmark ──────────────────────────────────────────────────────────────
  function Brand() {
    return (
      <div style={{ textAlign: 'center', marginBottom: 32 }}>
        <div style={{ display: 'inline-flex', alignItems: 'center', gap: 7 }}>
          <svg width="18" height="18" viewBox="0 0 18 18" fill="none">
            <rect width="18" height="18" rx="5" fill="var(--a-accent)" opacity="0.15"/>
            <path d="M4 9h10M9 4l5 5-5 5" stroke="var(--a-accent)" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
          <span style={{ fontSize: 16, fontWeight: 600, color: 'var(--a-text)', letterSpacing: '-0.02em' }}>
            getplan.today
          </span>
        </div>
      </div>
    );
  }

  // ── Main component ────────────────────────────────────────────────────────
  function AuthPage() {
    const [mode,         setMode]         = useState('login');
    const [email,        setEmail]        = useState('');
    const [password,     setPassword]     = useState('');
    const [name,         setName]         = useState('');
    const [pendingEmail, setPendingEmail] = useState('');
    const [error,        setError]        = useState('');
    const [banner,       setBanner]       = useState(null);
    const [loading,      setLoading]      = useState(false);
    const [resendSent,   setResendSent]   = useState(false);
    const [checking,     setChecking]     = useState(true);

    useEffect(() => {
      const params = new URLSearchParams(window.location.search);
      if (params.get('verified') === '1') {
        window.history.replaceState({}, '', window.location.pathname);
        setBanner({ type: 'ok', text: 'Email confirmed — signing you in…' });
      } else if (params.get('auth_error')) {
        window.history.replaceState({}, '', window.location.pathname);
        setBanner({ type: 'err', text: 'Verification link is invalid or already used.' });
      }
      fetch('/api/auth/me', { credentials: 'include' })
        .then(r => r.ok ? r.json() : null)
        .then(d => { if (d?.user && window.__renderApp) window.__renderApp(d.user); else setChecking(false); })
        .catch(() => setChecking(false));
    }, []);

    async function submit(e) {
      e.preventDefault();
      setError(''); setLoading(true);
      const isLogin  = mode === 'login';
      const endpoint = isLogin ? '/api/auth/login' : '/api/auth/register';
      const payload  = isLogin ? { email, password } : { email, password, name };
      try {
        const res  = await fetch(endpoint, { method: 'POST', headers: { 'Content-Type': 'application/json' }, credentials: 'include', body: JSON.stringify(payload) });
        const data = await res.json();
        if (!res.ok) {
          if (data.unverified) { setPendingEmail(data.email || email); setMode('pending'); setLoading(false); return; }
          setError(data.error || 'Something went wrong'); setLoading(false); return;
        }
        if (data.pending) { setPendingEmail(data.email || email); setMode('pending'); setLoading(false); return; }
        if (window.__renderApp) window.__renderApp(data.user);
      } catch { setError('Network error — check your connection'); setLoading(false); }
    }

    async function resend() {
      setResendSent(false);
      try { await fetch('/api/auth/resend-verification', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email: pendingEmail }) }); setResendSent(true); } catch {}
    }

    const wrap = {
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      minHeight: '100vh', background: 'var(--a-bg)',
      fontFamily: '"Geist", "Inter", system-ui, sans-serif',
      padding: '24px 16px',
    };
    const card = {
      background: 'var(--a-surface)', border: '1px solid var(--a-border)',
      borderRadius: 14, padding: '28px 24px',
    };

    // ── Loading ──
    if (checking) return (
      <div style={wrap}>
        <div style={{ width: 20, height: 20, border: '2px solid var(--a-border)', borderTopColor: 'var(--a-accent)', borderRadius: '50%', animation: 'a-spin 0.7s linear infinite' }} />
      </div>
    );

    // ── Pending: check inbox ──
    if (mode === 'pending') return (
      <div style={wrap}>
        <div style={{ width: '100%', maxWidth: 380 }}>
          <Brand />
          <div style={{ ...card, textAlign: 'center' }}>
            <div style={{ width: 48, height: 48, borderRadius: 12, background: 'var(--a-err-bg)', border: '1px solid var(--a-border)', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 20px' }}>
              <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="var(--a-accent)" strokeWidth="1.7">
                <rect x="2" y="4" width="20" height="16" rx="2"/>
                <path d="M2 7l10 7 10-7"/>
              </svg>
            </div>
            <p style={{ margin: '0 0 3px', fontSize: 17, fontWeight: 600, color: 'var(--a-text)' }}>Check your email</p>
            <p style={{ margin: '0 0 3px', fontSize: 13, color: 'var(--a-muted)' }}>Confirmation sent to</p>
            <p style={{ margin: '0 0 22px', fontSize: 13, fontWeight: 500, color: 'var(--a-text)' }}>{pendingEmail}</p>
            {resendSent
              ? <div style={{ padding: '9px 12px', background: 'var(--a-ok-bg)', border: '1px solid var(--a-ok-bd)', borderRadius: 8, fontSize: 13, color: 'var(--a-ok-tx)' }}>Sent — check your inbox.</div>
              : <p style={{ fontSize: 13, color: 'var(--a-muted)', margin: 0 }}>Didn't get it? <button className="a-btn-link" onClick={resend}>Resend</button></p>
            }
          </div>
          <p style={{ textAlign: 'center', marginTop: 18, fontSize: 13, color: 'var(--a-muted)' }}>
            <button className="a-btn-link" onClick={() => { setMode('login'); setError(''); setResendSent(false); }}>← Back to sign in</button>
          </p>
        </div>
      </div>
    );

    // ── Login / Signup ──
    return (
      <div style={wrap}>
        <div style={{ width: '100%', maxWidth: 380 }}>
          <Brand />

          {banner && (
            <div style={{ marginBottom: 14, padding: '10px 14px', borderRadius: 8, fontSize: 13,
              background: banner.type === 'ok' ? 'var(--a-ok-bg)' : 'var(--a-err-bg)',
              border:     banner.type === 'ok' ? '1px solid var(--a-ok-bd)' : '1px solid var(--a-err-bd)',
              color:      banner.type === 'ok' ? 'var(--a-ok-tx)' : 'var(--a-err-tx)',
            }}>{banner.text}</div>
          )}

          <div style={card}>
            <p style={{ margin: '0 0 2px', fontSize: 18, fontWeight: 600, color: 'var(--a-text)', letterSpacing: '-0.02em' }}>
              {mode === 'login' ? 'Sign in' : 'Create account'}
            </p>
            <p style={{ margin: '0 0 22px', fontSize: 13, color: 'var(--a-muted)' }}>
              {mode === 'login' ? 'Welcome back to getplan.today' : 'Get started — it only takes a minute'}
            </p>

            <form onSubmit={submit} noValidate>
              {mode === 'signup' && (
                <div style={{ marginBottom: 14 }}>
                  <label style={{ display: 'block', fontSize: 12, fontWeight: 500, color: 'var(--a-muted)', marginBottom: 5 }}>Name <span style={{ fontWeight: 400, opacity: 0.7 }}>(optional)</span></label>
                  <input className="a-input" type="text" value={name} onChange={e => setName(e.target.value)} placeholder="Your name" autoComplete="name" />
                </div>
              )}

              <div style={{ marginBottom: 14 }}>
                <label style={{ display: 'block', fontSize: 12, fontWeight: 500, color: 'var(--a-muted)', marginBottom: 5 }}>Email</label>
                <input className="a-input" type="email" value={email} onChange={e => setEmail(e.target.value)} placeholder="you@example.com" required autoComplete="email" autoFocus />
              </div>

              <div style={{ marginBottom: 20 }}>
                <label style={{ display: 'block', fontSize: 12, fontWeight: 500, color: 'var(--a-muted)', marginBottom: 5 }}>Password</label>
                <input className="a-input" type="password" value={password} onChange={e => setPassword(e.target.value)}
                  placeholder={mode === 'signup' ? 'At least 8 characters' : '••••••••'}
                  required autoComplete={mode === 'login' ? 'current-password' : 'new-password'} />
              </div>

              {error && (
                <div style={{ marginBottom: 14, padding: '9px 12px', background: 'var(--a-err-bg)', border: '1px solid var(--a-err-bd)', borderRadius: 8, fontSize: 13, color: 'var(--a-err-tx)' }}>
                  {error}
                </div>
              )}

              <button type="submit" disabled={loading} style={{
                width: '100%', padding: '10px', border: 'none', borderRadius: 8,
                background: loading ? 'var(--a-border)' : 'var(--a-accent)',
                color: loading ? 'var(--a-muted)' : 'var(--a-btn-text)',
                fontSize: 14, fontWeight: 600, fontFamily: 'inherit',
                cursor: loading ? 'not-allowed' : 'pointer',
                transition: 'opacity 0.15s',
              }}>
                {loading ? '…' : (mode === 'login' ? 'Sign in' : 'Create account')}
              </button>
            </form>
          </div>

          <p style={{ textAlign: 'center', marginTop: 18, fontSize: 13, color: 'var(--a-muted)' }}>
            {mode === 'login' ? "No account? " : "Have an account? "}
            <button className="a-btn-link" onClick={() => { setMode(mode === 'login' ? 'signup' : 'login'); setError(''); setBanner(null); }}>
              {mode === 'login' ? 'Sign up' : 'Sign in'}
            </button>
          </p>
        </div>
      </div>
    );
  }

  const authRoot = ReactDOM.createRoot(document.getElementById('root'));
  authRoot.render(<AuthPage />);
  window.__authRoot = authRoot;
})();
