// auth.jsx — Login screen shown when no Supabase session exists.

function AuthScreen({ onLogin }) {
  const [mode,     setMode]     = React.useState('signin'); // 'signin' | 'forgot'
  const [email,    setEmail]    = React.useState('');
  const [password, setPassword] = React.useState('');
  const [error,    setError]    = React.useState('');
  const [notice,   setNotice]   = React.useState('');
  const [loading,  setLoading]  = React.useState(false);

  const handleSubmit = async (e) => {
    e.preventDefault();
    setError('');
    setLoading(true);
    try {
      const { data, error } = await window.supabaseClient.auth.signInWithPassword({ email, password });
      if (error) throw error;
      onLogin(data.session);
    } catch (err) {
      setError(err.message || 'Sign-in failed. Check your email and password.');
    } finally {
      setLoading(false);
    }
  };

  const handleForgot = async (e) => {
    e.preventDefault();
    setError('');
    setNotice('');
    setLoading(true);
    try {
      // Supabase emails a time-limited, single-use recovery link. It does not
      // reveal whether the address exists, so the message stays generic.
      await window.supabaseClient.auth.resetPasswordForEmail(email, {
        redirectTo: window.location.origin + window.location.pathname,
      });
      setNotice(`If an account exists for ${email}, a password reset link is on its way. Check your inbox and spam.`);
    } catch (err) {
      setError(err.message || 'Could not send the reset email. Try again.');
    } finally {
      setLoading(false);
    }
  };

  const switchMode = (m) => { setMode(m); setError(''); setNotice(''); };

  return (
    <div style={{
      minHeight: '100vh',
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      background: 'var(--bg)',
    }}>
      <div style={{ width: 360 }}>
        {/* Logo */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, justifyContent: 'center', marginBottom: 32 }}>
          <div style={{
            width: 34, height: 34,
            background: 'var(--ink)', color: 'var(--bg)',
            borderRadius: 8,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontFamily: 'var(--f-display)', fontSize: 22, paddingTop: 2,
          }}>i</div>
          <div>
            <div style={{ fontWeight: 600, fontSize: 14, letterSpacing: '-0.01em' }}>IPSEM</div>
            <div style={{ fontSize: 11, color: 'var(--ink-3)', lineHeight: 1 }}>Sponsorship Prospecting OS</div>
          </div>
        </div>

        {/* Card */}
        <div className="card card-pad-lg">
          <h2 style={{ fontSize: 18, fontWeight: 600, marginBottom: 20, textAlign: 'center' }}>
            {mode === 'forgot' ? 'Reset your password' : 'Sign in'}
          </h2>

          {mode === 'forgot' ? (
            <form onSubmit={handleForgot}>
              <p className="text-2 text-sm" style={{ marginTop: 0, marginBottom: 16, lineHeight: 1.55 }}>
                Enter your email and we will send you a secure link to set a new password.
              </p>
              <div style={{ marginBottom: 18 }}>
                <label className="eyebrow" style={{ display: 'block', marginBottom: 6 }}>Email</label>
                <div className="field" style={{ height: 40 }}>
                  <input type="email" value={email} onChange={e => setEmail(e.target.value)} placeholder="you@ipsem.com" required autoFocus />
                </div>
              </div>

              {notice && (
                <div style={{ background: 'var(--positive-soft)', color: 'var(--positive)', padding: '10px 14px', borderRadius: 'var(--radius-sm)', marginBottom: 16, fontSize: 13, lineHeight: 1.45 }}>{notice}</div>
              )}
              {error && (
                <div style={{ background: 'var(--negative-soft)', color: 'var(--negative)', padding: '10px 14px', borderRadius: 'var(--radius-sm)', marginBottom: 16, fontSize: 13, lineHeight: 1.4 }}>{error}</div>
              )}

              <button type="submit" className="btn btn-primary" style={{ width: '100%', height: 40, fontSize: 14 }} disabled={loading || !email}>
                {loading ? 'Sending…' : 'Send reset link'}
              </button>
              <button type="button" className="btn btn-ghost" onClick={() => switchMode('signin')} style={{ width: '100%', height: 36, fontSize: 13, marginTop: 10, color: 'var(--ink-3)' }}>
                Back to sign in
              </button>
            </form>
          ) : (
            <form onSubmit={handleSubmit}>
              <div style={{ marginBottom: 14 }}>
                <label className="eyebrow" style={{ display: 'block', marginBottom: 6 }}>Email</label>
                <div className="field" style={{ height: 40 }}>
                  <input type="email" value={email} onChange={e => setEmail(e.target.value)} placeholder="you@ipsem.com" required autoFocus />
                </div>
              </div>

              <div style={{ marginBottom: 8 }}>
                <label className="eyebrow" style={{ display: 'block', marginBottom: 6 }}>Password</label>
                <div className="field" style={{ height: 40 }}>
                  <input type="password" value={password} onChange={e => setPassword(e.target.value)} placeholder="••••••••" required />
                </div>
              </div>

              <div style={{ textAlign: 'right', marginBottom: 18 }}>
                <button type="button" onClick={() => switchMode('forgot')} style={{ background: 'none', border: 0, color: 'var(--accent)', cursor: 'pointer', fontSize: 12.5, padding: 0 }}>
                  Forgot password?
                </button>
              </div>

              {error && (
                <div style={{ background: 'var(--negative-soft)', color: 'var(--negative)', padding: '10px 14px', borderRadius: 'var(--radius-sm)', marginBottom: 16, fontSize: 13, lineHeight: 1.4 }}>{error}</div>
              )}

              <button type="submit" className="btn btn-primary" style={{ width: '100%', height: 40, fontSize: 14 }} disabled={loading}>
                {loading ? 'Signing in…' : 'Sign in'}
              </button>
            </form>
          )}
        </div>

        <p style={{ textAlign: 'center', marginTop: 16, fontSize: 12, color: 'var(--ink-4)' }}>
          Internal tool · Contact your administrator for access
        </p>
      </div>
    </div>
  );
}

// ─── Reset password — shown when the user arrives via a recovery email link ──
function ResetPasswordScreen({ onDone }) {
  const [pw,  setPw]  = React.useState('');
  const [pw2, setPw2] = React.useState('');
  const [error,   setError]   = React.useState('');
  const [loading, setLoading] = React.useState(false);

  const submit = async (e) => {
    e.preventDefault();
    setError('');
    if (pw.length < 8) { setError('Password must be at least 8 characters.'); return; }
    if (pw !== pw2)   { setError('Passwords do not match.'); return; }
    setLoading(true);
    try {
      const { error } = await window.supabaseClient.auth.updateUser({ password: pw });
      if (error) throw error;
      onDone();
    } catch (err) {
      setError(err.message || 'Could not update password. The link may have expired — request a new one.');
      setLoading(false);
    }
  };

  return (
    <div style={{ minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'var(--bg)' }}>
      <div style={{ width: 360 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, justifyContent: 'center', marginBottom: 32 }}>
          <div style={{ width: 34, height: 34, background: 'var(--ink)', color: 'var(--bg)', borderRadius: 8, display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'var(--f-display)', fontSize: 22, paddingTop: 2 }}>i</div>
          <div>
            <div style={{ fontWeight: 600, fontSize: 14 }}>IPSEM</div>
            <div style={{ fontSize: 11, color: 'var(--ink-3)', lineHeight: 1 }}>Sponsorship Prospecting OS</div>
          </div>
        </div>
        <div className="card card-pad-lg">
          <h2 style={{ fontSize: 18, fontWeight: 600, marginBottom: 6, textAlign: 'center' }}>Set a new password</h2>
          <p className="text-2 text-sm" style={{ textAlign: 'center', marginTop: 0, marginBottom: 20 }}>Choose a new password for your account.</p>
          <form onSubmit={submit}>
            <div style={{ marginBottom: 14 }}>
              <label className="eyebrow" style={{ display: 'block', marginBottom: 6 }}>New password</label>
              <div className="field" style={{ height: 40 }}>
                <input type="password" value={pw} onChange={e => setPw(e.target.value)} placeholder="At least 8 characters" required autoFocus />
              </div>
            </div>
            <div style={{ marginBottom: 20 }}>
              <label className="eyebrow" style={{ display: 'block', marginBottom: 6 }}>Confirm password</label>
              <div className="field" style={{ height: 40 }}>
                <input type="password" value={pw2} onChange={e => setPw2(e.target.value)} placeholder="Re-enter password" required />
              </div>
            </div>
            {error && (
              <div style={{ background: 'var(--negative-soft)', color: 'var(--negative)', padding: '10px 14px', borderRadius: 'var(--radius-sm)', marginBottom: 16, fontSize: 13, lineHeight: 1.4 }}>{error}</div>
            )}
            <button type="submit" className="btn btn-primary" style={{ width: '100%', height: 40, fontSize: 14 }} disabled={loading}>
              {loading ? 'Updating…' : 'Update password'}
            </button>
          </form>
        </div>
      </div>
    </div>
  );
}

// ─── Seed screen — shown when DB is empty after first login ───────────────

function SeedScreen({ onSeeded, onLogout }) {
  const [loading, setLoading] = React.useState(false);
  const [error,   setError]   = React.useState('');

  const handleSeed = async () => {
    setLoading(true);
    setError('');
    try {
      const { BRANDS, PROPERTIES } = window.IPSEM_DATA;
      await window.IPSEM_API.seed({ brands: BRANDS, properties: PROPERTIES });
      onSeeded();
    } catch (err) {
      setError(err.message || 'Seed failed. Check your backend console.');
      setLoading(false);
    }
  };

  return (
    <div style={{
      minHeight: '100vh',
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      background: 'var(--bg)',
    }}>
      <div style={{ width: 420, textAlign: 'center' }}>
        {/* Logo */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, justifyContent: 'center', marginBottom: 32 }}>
          <div style={{
            width: 34, height: 34,
            background: 'var(--ink)', color: 'var(--bg)',
            borderRadius: 8,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontFamily: 'var(--f-display)', fontSize: 22, paddingTop: 2,
          }}>i</div>
          <div>
            <div style={{ fontWeight: 600, fontSize: 14 }}>IPSEM</div>
            <div style={{ fontSize: 11, color: 'var(--ink-3)', lineHeight: 1 }}>Sponsorship Prospecting OS</div>
          </div>
        </div>

        <div className="card card-pad-lg">
          <div style={{ fontSize: 16, fontWeight: 600, marginBottom: 10 }}>Database is empty</div>
          <p style={{ color: 'var(--ink-3)', marginBottom: 24, lineHeight: 1.6, fontSize: 13.5 }}>
            Load the initial brand and property data to get started.
            This only needs to be done once — all future brands will be added by the daily scanner.
          </p>

          {error && (
            <div style={{
              background: 'var(--negative-soft)', color: 'var(--negative)',
              padding: '10px 14px', borderRadius: 'var(--radius-sm)',
              marginBottom: 16, fontSize: 13,
            }}>
              {error}
            </div>
          )}

          <button
            className="btn btn-primary btn-lg"
            onClick={handleSeed}
            disabled={loading}
            style={{ width: '100%' }}
          >
            {loading ? 'Loading data…' : 'Load initial data'}
          </button>
        </div>

        <button
          className="btn btn-ghost text-sm"
          onClick={onLogout}
          style={{ marginTop: 16, color: 'var(--ink-3)' }}
        >
          Sign out
        </button>
      </div>
    </div>
  );
}
