const { useState: useStateLogin } = React;

function LoginScreen({ onLogin }) {
  const [mode, setMode] = useStateLogin('login');
  const [email, setEmail] = useStateLogin('');
  const [password, setPassword] = useStateLogin('');
  const [error, setError] = useStateLogin('');
  const [loading, setLoading] = useStateLogin(false);
  const [googleLoading, setGoogleLoading] = useStateLogin(false);
  const [facebookLoading, setFacebookLoading] = useStateLogin(false);
  const [resetMode, setResetMode] = useStateLogin(false);
  const [success, setSuccess] = useStateLogin('');

  async function handleSubmit(e) {
    e.preventDefault();
    setError(''); setSuccess(''); setLoading(true);
    try {
      if (mode === 'signup') {
        const { error } = await supabaseClient.auth.signUp({ email, password });
        if (error) throw error;
        setSuccess('Check your email to confirm your account, then log in.');
        setMode('login');
      } else {
        const { data, error } = await supabaseClient.auth.signInWithPassword({ email, password });
        if (error) throw error;
        onLogin(data.session);
      }
    } catch (err) {
      setError(err.message || 'Something went wrong');
    } finally {
      setLoading(false);
    }
  }

  async function handleGoogle() {
    setGoogleLoading(true);
    setError('');
    const { error } = await supabaseClient.auth.signInWithOAuth({
      provider: 'google',
      options: { redirectTo: 'https://fliptaxy.netlify.com' }
    });
    if (error) { setError(error.message); setGoogleLoading(false); }
  }

  async function handleFacebook() {
    setFacebookLoading(true);
    setError('');
    const { error } = await supabaseClient.auth.signInWithOAuth({
      provider: 'facebook',
      options: { redirectTo: 'https://fliptaxy.netlify.com' }
    });
    if (error) { setError(error.message); setFacebookLoading(false); }
  }

  async function handlePasswordReset(e) {
    e.preventDefault();
    setError(''); setSuccess(''); setLoading(true);
    try {
      const { error } = await supabaseClient.auth.resetPasswordForEmail(email, {
        redirectTo: 'https://fliptaxy.netlify.com/reset-password'
      });
      if (error) throw error;
      setSuccess('Password reset link sent! Check your email.');
      setResetMode(false);
    } catch (err) {
      setError(err.message || 'Failed to send reset link');
    } finally {
      setLoading(false);
    }
  }

  return (
    <div style={{
      minHeight: '100vh',
      background: 'var(--bg)',
      display: 'flex',
      flexDirection: 'column',
      alignItems: 'center',
      justifyContent: 'center',
      padding: '0 24px',
      fontFamily: 'Inter, -apple-system, sans-serif',
    }}>
      {/* Logo */}
      <div style={{marginBottom:40, textAlign:'center'}}>
        <div style={{fontSize:32, fontWeight:700, letterSpacing:'-1px', color:'#1a1a1a'}}>
          flip<span style={{color:'#2d7a14'}}>taxy</span>
        </div>
        <div style={{fontSize:14, color:'#888', marginTop:6}}>Detailed tax-supportive flipping log</div>
      </div>

      {/* Card */}
      <div style={{background:'white', borderRadius:24, padding:'28px 24px', width:'100%', maxWidth:380, boxShadow:'0 2px 24px rgba(0,0,0,0.07)'}}>

        {/* Google button */}
        <button onClick={handleGoogle} disabled={googleLoading}
          style={{
            width:'100%', padding:'13px', border:'1.5px solid #e5e5ea',
            borderRadius:14, fontSize:15, fontWeight:600, cursor: googleLoading ? 'not-allowed' : 'pointer',
            background:'white', color:'#1a1a1a', display:'flex', alignItems:'center',
            justifyContent:'center', gap:10, marginBottom:12, fontFamily:'inherit',
            opacity: googleLoading ? 0.6 : 1, transition:'opacity 0.15s',
          }}>
          <svg width="18" height="18" viewBox="0 0 48 48">
            <path fill="#EA4335" d="M24 9.5c3.54 0 6.71 1.22 9.21 3.6l6.85-6.85C35.9 2.38 30.47 0 24 0 14.62 0 6.51 5.38 2.56 13.22l7.98 6.19C12.43 13.72 17.74 9.5 24 9.5z"/>
            <path fill="#4285F4" d="M46.98 24.55c0-1.57-.15-3.09-.38-4.55H24v9.02h12.94c-.58 2.96-2.26 5.48-4.78 7.18l7.73 6c4.51-4.18 7.09-10.36 7.09-17.65z"/>
            <path fill="#FBBC05" d="M10.53 28.59c-.48-1.45-.76-2.99-.76-4.59s.27-3.14.76-4.59l-7.98-6.19C.92 16.46 0 20.12 0 24c0 3.88.92 7.54 2.56 10.78l7.97-6.19z"/>
            <path fill="#34A853" d="M24 48c6.48 0 11.93-2.13 15.89-5.81l-7.73-6c-2.18 1.48-4.97 2.35-8.16 2.35-6.26 0-11.57-4.22-13.47-9.91l-7.98 6.19C6.51 42.62 14.62 48 24 48z"/>
          </svg>
          {googleLoading ? 'Redirecting…' : 'Continue with Google'}
        </button>

        {/* Facebook button */}
        <button onClick={handleFacebook} disabled={facebookLoading}
          style={{
            width:'100%', padding:'13px', border:'1.5px solid #e5e5ea',
            borderRadius:14, fontSize:15, fontWeight:600, cursor: facebookLoading ? 'not-allowed' : 'pointer',
            background:'white', color:'#1a1a1a', display:'flex', alignItems:'center',
            justifyContent:'center', gap:10, marginBottom:16, fontFamily:'inherit',
            opacity: facebookLoading ? 0.6 : 1, transition:'opacity 0.15s',
          }}>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="#1877F2">
            <path d="M24 12.073c0-6.627-5.373-12-12-12s-12 5.373-12 12c0 5.99 4.388 10.954 10.125 11.854v-8.385H7.078v-3.47h3.047V9.43c0-3.007 1.792-4.669 4.533-4.669 1.312 0 2.686.235 2.686.235v2.953H15.83c-1.491 0-1.956.925-1.956 1.874v2.25h3.328l-.532 3.47h-2.796v8.385C19.612 23.027 24 18.062 24 12.073z"/>
          </svg>
          {facebookLoading ? 'Redirecting…' : 'Continue with Facebook'}
        </button>

        {/* Divider */}
        <div style={{display:'flex', alignItems:'center', gap:10, marginBottom:16}}>
          <div style={{flex:1, height:1, background:'#e5e5ea'}} />
          <div style={{fontSize:12, color:'#aaa', fontWeight:500}}>or</div>
          <div style={{flex:1, height:1, background:'#e5e5ea'}} />
        </div>

        {resetMode ? (
          <>
            <div style={{textAlign:'center', marginBottom:20}}>
              <div style={{fontSize:18, fontWeight:600, color:'#1a1a1a', marginBottom:8}}>Reset Password</div>
              <div style={{fontSize:13, color:'#888'}}>Enter your email to receive a reset link</div>
            </div>
            <form onSubmit={handlePasswordReset} style={{display:'flex', flexDirection:'column', gap:14}}>
              <div>
                <div style={{fontSize:12, fontWeight:600, color:'#888', textTransform:'uppercase', letterSpacing:'0.4px', marginBottom:8}}>Email</div>
                <input type="email" value={email} onChange={e => setEmail(e.target.value)}
                  placeholder="you@example.com" required
                  style={{width:'100%', padding:'13px 15px', border:'1.5px solid #e5e5ea', borderRadius:14, fontSize:16, outline:'none', boxSizing:'border-box', fontFamily:'inherit'}} />
              </div>

              {error && <div style={{fontSize:13, color:'#cc3333', background:'#ffe5e5', borderRadius:10, padding:'10px 14px'}}>{error}</div>}
              {success && <div style={{fontSize:13, color:'#2d7a14', background:'#e8f5e0', borderRadius:10, padding:'10px 14px'}}>{success}</div>}

              <button type="submit" disabled={loading}
                style={{
                  width:'100%', padding:'15px', background: loading ? '#888' : '#1a1a1a',
                  color:'white', border:'none', borderRadius:16, fontSize:16, fontWeight:700,
                  cursor: loading ? 'not-allowed' : 'pointer', marginTop:4,
                  fontFamily:'inherit', transition:'background 0.15s',
                }}>
                {loading ? 'Sending…' : 'Send Reset Link'}
              </button>
              
              <button type="button" onClick={() => { setResetMode(false); setError(''); setSuccess(''); }}
                style={{
                  width:'100%', padding:'12px', background:'transparent',
                  color:'#888', border:'none', borderRadius:16, fontSize:14, fontWeight:500,
                  cursor:'pointer', fontFamily:'inherit',
                }}>
                Back to Login
              </button>
            </form>
          </>
        ) : (
          <>
            {/* Login/Signup tabs */}
            <div style={{display:'flex', background:'#f2f2f7', borderRadius:12, padding:4, marginBottom:20}}>
              {['login','signup'].map(m => (
                <button key={m} onClick={() => { setMode(m); setError(''); setSuccess(''); }}
                  style={{
                    flex:1, padding:'9px 0', border:'none', borderRadius:10, fontSize:14,
                    fontWeight:600, cursor:'pointer',
                    background: mode === m ? 'white' : 'transparent',
                    color: mode === m ? '#1a1a1a' : '#888',
                    boxShadow: mode === m ? '0 1px 4px rgba(0,0,0,0.1)' : 'none',
                    transition:'all 0.15s', fontFamily:'inherit',
                  }}>
                  {m === 'login' ? 'Log in' : 'Sign up'}
                </button>
              ))}
            </div>

            <form onSubmit={handleSubmit} style={{display:'flex', flexDirection:'column', gap:14}}>
                <div>
                  <div style={{fontSize:12, fontWeight:600, color:'#888', textTransform:'uppercase', letterSpacing:'0.4px', marginBottom:8}}>Email</div>
                  <input type="email" value={email} onChange={e => setEmail(e.target.value)}
                    placeholder="you@example.com" required
                    style={{width:'100%', padding:'13px 15px', border:'1.5px solid #e5e5ea', borderRadius:14, fontSize:16, outline:'none', boxSizing:'border-box', fontFamily:'inherit'}} />
                </div>
                <div>
                  <div style={{fontSize:12, fontWeight:600, color:'#888', textTransform:'uppercase', letterSpacing:'0.4px', marginBottom:8}}>Password</div>
                  <input type="password" value={password} onChange={e => setPassword(e.target.value)}
                    placeholder="••••••••" required minLength={6}
                    style={{width:'100%', padding:'13px 15px', border:'1.5px solid #e5e5ea', borderRadius:14, fontSize:16, outline:'none', boxSizing:'border-box', fontFamily:'inherit'}} />
                </div>

                {error && <div style={{fontSize:13, color:'#cc3333', background:'#ffe5e5', borderRadius:10, padding:'10px 14px'}}>{error}</div>}
                {success && <div style={{fontSize:13, color:'#2d7a14', background:'#e8f5e0', borderRadius:10, padding:'10px 14px'}}>{success}</div>}

                <button type="submit" disabled={loading}
                  style={{
                    width:'100%', padding:'15px', background: loading ? '#888' : '#1a1a1a',
                    color:'white', border:'none', borderRadius:16, fontSize:16, fontWeight:700,
                    cursor: loading ? 'not-allowed' : 'pointer', marginTop:4,
                    fontFamily:'inherit', transition:'background 0.15s',
                  }}>
                  {loading ? 'Please wait…' : mode === 'login' ? 'Log in' : 'Create account'}
                </button>

                {mode === 'login' && (
                  <button type="button" onClick={() => { setResetMode(true); setError(''); setSuccess(''); }}
                    style={{
                      width:'100%', padding:'12px', background:'transparent',
                      color:'#888', border:'none', borderRadius:16, fontSize:14, fontWeight:500,
                      cursor:'pointer', fontFamily:'inherit', marginTop:8,
                    }}>
                    Forgot password?
                  </button>
                )}
              </form>
          </>
        )}
      </div>

      <div style={{marginTop: 16, textAlign: 'center'}}>
        <div style={{fontSize: 13, color: '#aaa', marginBottom: 10}}>
          Just want to look around?
        </div>
        <button
          onClick={async () => {
            setLoading(true);
            const { data, error } = await supabaseClient.auth.signInAnonymously();
            if (error) {
              setError('Could not start demo. Please try again.');
              setLoading(false);
              return;
            }
            localStorage.setItem('fliptaxy_is_demo', 'true');
            onLogin(data.session);
          }}
          disabled={loading}
          style={{
            padding: '12px 32px',
            background: 'transparent',
            border: '1.5px solid #e5e5ea',
            borderRadius: 14,
            fontSize: 14,
            fontWeight: 600,
            cursor: loading ? 'not-allowed' : 'pointer',
            color: '#1a1a1a',
            fontFamily: 'inherit',
            opacity: loading ? 0.6 : 1,
          }}>
          {loading ? 'Starting demo…' : 'Try Demo — no signup needed'}
        </button>
      </div>

      <div style={{fontSize:12, color:'#aaa', marginTop:24, textAlign:'center'}}>
        Your data is private and encrypted.
      </div>
    </div>
  );
}

Object.assign(window, { LoginScreen });