// Login screen for LineageLens — powered by Supabase Auth
const { useState, useEffect } = React;

function LoginScreen() {
  const [mode, setMode] = useState('signin'); // 'signin' | 'signup' | 'forgot'
  const [email, setEmail] = useState(() => localStorage.getItem('ll_email') || '');
  const [password, setPassword] = useState('');
  const [rememberMe, setRememberMe] = useState(() => localStorage.getItem('ll_remember') !== 'false');
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [oauthLoading, setOauthLoading] = useState(''); // 'google' | 'github' | ''
  const [error, setError] = useState('');
  const [successMsg, setSuccessMsg] = useState('');
  const [needsConfirm, setNeedsConfirm] = useState(false);
  const [mousePos, setMousePos] = useState({ x: 0, y: 0 });

  const savedEmail = localStorage.getItem('ll_email') || '';

  const persistEmail = (addr) => {
    localStorage.setItem('ll_remember', 'true');
    localStorage.setItem('ll_email', addr);
  };
  const forgetEmail = () => {
    localStorage.removeItem('ll_email');
    localStorage.setItem('ll_remember', 'false');
    setEmail('');
  };

  // Handle OAuth redirect back (Google/GitHub send user back with tokens in URL)
  useEffect(() => {
    const sb = window.supabaseClient;
    if (!sb) return;

    // If we're returning from an OAuth redirect, supabase picks it up automatically
    // via detectSessionInUrl: true. We just need to redirect if a session exists.
    sb.auth.getSession().then(({ data: { session } }) => {
      if (session) {
        if (session.user?.email) persistEmail(session.user.email);
        window.location.href = '/';
      }
    });
  }, []);

  const handleMouseMove = (e) => {
    const rect = e.currentTarget.getBoundingClientRect();
    setMousePos({ x: e.clientX - rect.left, y: e.clientY - rect.top });
  };

  const getFriendlyError = (message) => {
    if (!message) return 'Something went wrong. Please try again.';
    if (message.includes('Invalid login credentials')) return 'Incorrect email or password. Please try again.';
    if (message.includes('Email not confirmed')) return 'Please check your email and click the confirmation link before signing in.';
    if (message.includes('User already registered')) return 'An account with this email already exists. Try signing in instead.';
    if (message.includes('Password should be')) return 'Password must be at least 6 characters.';
    if (message.includes('Unable to validate email')) return 'Please enter a valid email address.';
    if (message.includes('rate limit')) return 'Too many attempts. Please wait a minute and try again.';
    return message;
  };

  const handleOAuth = async (provider) => {
    const sb = window.supabaseClient;
    if (!sb) { setError('Authentication service unavailable. Please reload the page.'); return; }
    setOauthLoading(provider);
    setError('');
    try {
      const { error: oauthErr } = await sb.auth.signInWithOAuth({
        provider,
        options: {
          redirectTo: window.location.origin + '/',
        }
      });
      if (oauthErr) throw oauthErr;
      // Browser will redirect to provider — no need to do anything else
    } catch (err) {
      setError(getFriendlyError(err.message));
      setOauthLoading('');
    }
  };

  const handleResendConfirmation = async () => {
    const sb = window.supabaseClient;
    if (!sb || !email) return;
    const { error: resendErr } = await sb.auth.resend({ type: 'signup', email });
    if (resendErr) setError(getFriendlyError(resendErr.message));
    else setSuccessMsg('Confirmation email resent! Check your inbox (and spam folder).');
    setNeedsConfirm(false);
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setError('');
    setSuccessMsg('');
    setNeedsConfirm(false);
    setIsSubmitting(true);

    const sb = window.supabaseClient;
    if (!sb) {
      setError('Authentication service is unavailable. Please reload the page and try again.');
      setIsSubmitting(false);
      return;
    }

    try {
      if (mode === 'signup') {
        const { data, error: signUpError } = await sb.auth.signUp({
          email,
          password,
          options: { emailRedirectTo: window.location.origin + '/' }
        });
        if (signUpError) throw signUpError;

        if (data.user && data.user.identities && data.user.identities.length === 0) {
          // User already exists
          setError('An account with this email already exists. Try signing in instead.');
        } else if (data.session) {
          // Email confirmation disabled — logged in straight away
          if (rememberMe) persistEmail(email); else forgetEmail();
          window.location.href = '/';
        } else {
          // Email confirmation required
          setSuccessMsg('Account created! Check your email for a confirmation link, then come back to sign in.');
        }
      } else {
        const { data, error: signInError } = await sb.auth.signInWithPassword({ email, password });
        if (signInError) {
          if (signInError.message.includes('Email not confirmed')) {
            setNeedsConfirm(true);
          }
          throw signInError;
        }
        if (data.session) {
          if (rememberMe) persistEmail(email); else forgetEmail();
          window.location.href = '/';
        }
      }
    } catch (err) {
      setError(getFriendlyError(err.message));
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleForgotPassword = async (e) => {
    e.preventDefault();
    if (!email) { setError('Please enter your email address.'); return; }
    const sb = window.supabaseClient;
    if (!sb) { setError('Authentication service unavailable. Please reload.'); return; }
    setIsSubmitting(true);
    setError('');
    const { error: resetErr } = await sb.auth.resetPasswordForEmail(email, {
      redirectTo: window.location.origin + '/login',
    });
    setIsSubmitting(false);
    if (resetErr) setError(getFriendlyError(resetErr.message));
    else setSuccessMsg('Reset link sent! Check your inbox (and spam folder).');
  };

  const switchMode = (m) => { setMode(m); setError(''); setSuccessMsg(''); setNeedsConfirm(false); };

  const isSignUp = mode === 'signup';
  const isForgot = mode === 'forgot';

  return (
    <section className="login-section" style={{
      minHeight: '100vh', display: 'flex', alignItems: 'center',
      justifyContent: 'center', padding: '120px 24px 80px',
      position: 'relative', overflow: 'hidden'
    }}>
      {/* Background ambient glows */}
      <div style={{ position: 'absolute', top: '10%', left: '20%', width: 500, height: 500, background: 'radial-gradient(circle, rgba(88, 166, 255, 0.15) 0%, transparent 70%)', zIndex: 0, pointerEvents: 'none' }} />
      <div style={{ position: 'absolute', bottom: '10%', right: '20%', width: 600, height: 600, background: 'radial-gradient(circle, rgba(163, 113, 247, 0.1) 0%, transparent 70%)', zIndex: 0, pointerEvents: 'none' }} />

      <div
        className="login-card reveal"
        onMouseMove={handleMouseMove}
        style={{
          width: '100%', maxWidth: 440,
          background: 'rgba(13, 17, 23, 0.85)',
          backdropFilter: 'blur(20px)', WebkitBackdropFilter: 'blur(20px)',
          border: '1px solid var(--border)', borderRadius: 24, padding: 40,
          position: 'relative', zIndex: 1, boxShadow: '0 24px 80px rgba(0,0,0,0.5)', overflow: 'hidden'
        }}
      >
        {/* Hover spotlight */}
        <div style={{ position: 'absolute', top: mousePos.y, left: mousePos.x, width: 300, height: 300, background: 'radial-gradient(circle, rgba(255,255,255,0.05) 0%, transparent 60%)', transform: 'translate(-50%, -50%)', pointerEvents: 'none', zIndex: 0 }} />

        <div style={{ position: 'relative', zIndex: 1 }}>
          {/* Header */}
          <div style={{ textAlign: 'center', marginBottom: 28 }}>
            <div style={{ display: 'inline-flex', padding: 12, borderRadius: 16, background: 'var(--bg-3)', marginBottom: 18, border: '1px solid var(--border)' }}>
              {isForgot ? (
                <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ color: 'var(--solo)' }}>
                  <rect x="3" y="11" width="18" height="11" rx="2" ry="2" />
                  <path d="M7 11V7a5 5 0 0 1 10 0v4" />
                </svg>
              ) : (
                <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ color: 'var(--solo)' }}>
                  <path d="M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4" />
                  <polyline points="10 17 15 12 10 7" />
                  <line x1="15" y1="12" x2="3" y2="12" />
                </svg>
              )}
            </div>
            <h1 style={{ fontSize: 26, fontWeight: 600, marginBottom: 6, letterSpacing: '-0.5px' }}>
              {isForgot ? 'Reset password' : isSignUp ? 'Create account' : 'Welcome back'}
            </h1>
            <p style={{ color: 'var(--text-muted)', fontSize: 14 }}>
              {isForgot
                ? "Enter your email and we'll send you a reset link"
                : isSignUp
                  ? 'Start your LineageLens journey'
                  : 'Sign in to your LineageLens account'}
            </p>
          </div>

          {/* Mode toggle — hidden on forgot screen */}
          {!isForgot && (
            <div style={{ display: 'flex', background: 'var(--bg-2)', borderRadius: 12, padding: 4, marginBottom: 24, border: '1px solid var(--border)' }}>
              {['signin', 'signup'].map(m => (
                <button key={m} onClick={() => switchMode(m)} style={{
                  flex: 1, padding: '8px 16px', borderRadius: 9, fontSize: 14, fontWeight: 500,
                  border: 'none', cursor: 'pointer', transition: 'all 0.2s',
                  background: mode === m ? 'var(--bg-3)' : 'transparent',
                  color: mode === m ? 'var(--text)' : 'var(--text-muted)',
                  boxShadow: mode === m ? '0 1px 4px rgba(0,0,0,0.3)' : 'none',
                }}>
                  {m === 'signin' ? 'Sign in' : 'Sign up'}
                </button>
              ))}
            </div>
          )}

          {/* OAuth buttons — hidden on forgot screen */}
          {!isForgot && (
            <>
              <div style={{ display: 'flex', gap: 10, marginBottom: 20 }}>
                <button
                  id="google-login-btn"
                  onClick={() => handleOAuth('google')}
                  disabled={oauthLoading !== ''}
                  style={{ ...socialBtnStyle, opacity: oauthLoading === 'google' ? 0.7 : 1 }}
                >
                  <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor">
                    <path d="M12.48 10.92v3.28h7.84c-.24 1.84-.853 3.187-1.787 4.133-1.147 1.147-2.933 2.4-6.053 2.4-4.827 0-8.6-3.893-8.6-8.72s3.773-8.72 8.6-8.72c2.6 0 4.507 1.027 5.907 2.347l2.307-2.307C18.747 1.44 16.133 0 12.48 0 5.867 0 .307 5.387.307 12s5.56 12 12.173 12c3.573 0 6.267-1.173 8.373-3.36 2.16-2.16 2.84-5.213 2.84-7.667 0-.76-.053-1.467-.173-2.053H12.48z"/>
                  </svg>
                  {oauthLoading === 'google' ? 'Redirecting...' : 'Google'}
                </button>
                <button
                  id="github-login-btn"
                  onClick={() => handleOAuth('github')}
                  disabled={oauthLoading !== ''}
                  style={{ ...socialBtnStyle, opacity: oauthLoading === 'github' ? 0.7 : 1 }}
                >
                  <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor">
                    <path d="M12 0c-6.626 0-12 5.373-12 12 0 5.302 3.438 9.8 8.207 11.387.599.111.793-.261.793-.577v-2.234c-3.338.726-4.033-1.416-4.033-1.416-.546-1.387-1.333-1.756-1.333-1.756-1.089-.745.083-.729.083-.729 1.205.084 1.839 1.237 1.839 1.237 1.07 1.834 2.807 1.304 3.492.997.107-.775.418-1.305.762-1.604-2.665-.305-5.467-1.334-5.467-5.931 0-1.311.469-2.381 1.236-3.221-.124-.303-.535-1.524.117-3.176 0 0 1.008-.322 3.301 1.23.957-.266 1.983-.399 3.003-.404 1.02.005 2.047.138 3.006.404 2.291-1.552 3.297-1.23 3.297-1.23.653 1.653.242 2.874.118 3.176.77.84 1.235 1.911 1.235 3.221 0 4.609-2.807 5.624-5.479 5.921.43.372.823 1.102.823 2.222v3.293c0 .319.192.694.801.576 4.765-1.589 8.199-6.086 8.199-11.386 0-6.627-5.373-12-12-12z"/>
                  </svg>
                  {oauthLoading === 'github' ? 'Redirecting...' : 'GitHub'}
                </button>
              </div>

              <div style={{ display: 'flex', alignItems: 'center', marginBottom: 20, color: 'var(--text-muted)' }}>
                <div style={{ flex: 1, height: 1, background: 'var(--border)' }} />
                <span style={{ padding: '0 12px', fontSize: 12, textTransform: 'uppercase', letterSpacing: '0.5px' }}>or with email</span>
                <div style={{ flex: 1, height: 1, background: 'var(--border)' }} />
              </div>
            </>
          )}

          {/* Error / Success */}
          {error && (
            <div style={{ padding: '12px 16px', borderRadius: 10, marginBottom: 16, background: 'rgba(248,81,73,0.12)', border: '1px solid rgba(248,81,73,0.3)', color: '#F85149', fontSize: 14, lineHeight: 1.5 }}>
              {error}
              {needsConfirm && (
                <button onClick={handleResendConfirmation} style={{ display: 'block', marginTop: 8, background: 'none', border: 'none', color: '#F85149', textDecoration: 'underline', cursor: 'pointer', padding: 0, fontSize: 13 }}>
                  Resend confirmation email →
                </button>
              )}
            </div>
          )}
          {successMsg && (
            <div style={{ padding: '12px 16px', borderRadius: 10, marginBottom: 16, background: 'rgba(63,185,80,0.12)', border: '1px solid rgba(63,185,80,0.3)', color: '#3FB950', fontSize: 14, lineHeight: 1.5 }}>
              {successMsg}
            </div>
          )}

          {/* ---- FORGOT PASSWORD FORM ---- */}
          {isForgot ? (
            <>
              <form onSubmit={handleForgotPassword} style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
                <div>
                  <label style={labelStyle}>Email address</label>
                  <input
                    type="email" value={email} onChange={e => setEmail(e.target.value)}
                    placeholder="you@company.com" required autoFocus style={inputStyle}
                  />
                </div>
                <button
                  type="submit" disabled={isSubmitting} className="btn btn-primary"
                  style={{ width: '100%', justifyContent: 'center', padding: '12px 24px', opacity: isSubmitting ? 0.7 : 1, cursor: isSubmitting ? 'wait' : 'pointer' }}
                >
                  {isSubmitting ? 'Sending...' : 'Send reset link'}
                </button>
              </form>

              <p style={{ textAlign: 'center', marginTop: 24, fontSize: 14, color: 'var(--text-muted)' }}>
                <button onClick={() => switchMode('signin')} style={{ background: 'none', border: 'none', color: 'var(--solo)', fontWeight: 500, cursor: 'pointer', fontSize: 14, display: 'inline-flex', alignItems: 'center', gap: 4 }}>
                  ← Back to sign in
                </button>
              </p>
            </>
          ) : (
            /* ---- SIGN IN / SIGN UP FORM ---- */
            <>
              <form onSubmit={handleSubmit} style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
                <div>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
                    <label style={{ ...labelStyle, marginBottom: 0 }}>Email address</label>
                    {savedEmail && email === savedEmail && (
                      <button type="button" onClick={forgetEmail}
                        style={{ fontSize: 12, color: 'var(--text-dim)', background: 'none', border: 'none', cursor: 'pointer', padding: 0 }}>
                        Not you?
                      </button>
                    )}
                  </div>
                  <input
                    type="email" value={email} onChange={e => setEmail(e.target.value)}
                    placeholder="you@company.com" required style={inputStyle} id="login-email"
                    autoComplete="email"
                  />
                </div>
                <div>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                    <label style={labelStyle}>Password</label>
                    <button type="button" onClick={() => switchMode('forgot')}
                      style={{ fontSize: 13, color: 'var(--solo)', background: 'none', border: 'none', cursor: 'pointer', padding: 0, marginBottom: 8 }}>
                      Forgot password?
                    </button>
                  </div>
                  <input
                    type="password" value={password} onChange={e => setPassword(e.target.value)}
                    placeholder="••••••••" required minLength={6} style={inputStyle} id="login-password"
                    autoComplete={isSignUp ? 'new-password' : 'current-password'}
                  />
                  {isSignUp && <p style={{ fontSize: 12, color: 'var(--text-muted)', marginTop: 6 }}>Minimum 6 characters</p>}
                </div>

                {/* Remember me */}
                <label style={{ display: 'flex', alignItems: 'center', gap: 10, cursor: 'pointer', userSelect: 'none' }}>
                  <input
                    type="checkbox" checked={rememberMe}
                    onChange={e => {
                      setRememberMe(e.target.checked);
                      localStorage.setItem('ll_remember', e.target.checked ? 'true' : 'false');
                      if (!e.target.checked) localStorage.removeItem('ll_email');
                    }}
                    style={{ width: 16, height: 16, accentColor: 'var(--solo)', cursor: 'pointer' }}
                  />
                  <span style={{ fontSize: 14, color: 'var(--text-muted)' }}>Remember me</span>
                </label>

                <button
                  type="submit" disabled={isSubmitting} className="btn btn-primary" id="login-submit"
                  style={{ width: '100%', justifyContent: 'center', padding: '12px 24px', marginTop: 4, opacity: isSubmitting ? 0.7 : 1, cursor: isSubmitting ? 'wait' : 'pointer' }}
                >
                  {isSubmitting
                    ? (isSignUp ? 'Creating account...' : 'Signing in...')
                    : (isSignUp ? 'Create account' : 'Sign in')}
                </button>
              </form>

              <p style={{ textAlign: 'center', marginTop: 24, fontSize: 14, color: 'var(--text-muted)' }}>
                {isSignUp
                  ? <>Already have an account?{' '}<button onClick={() => switchMode('signin')} style={{ background: 'none', border: 'none', color: 'var(--text)', fontWeight: 500, cursor: 'pointer', fontSize: 14 }}>Sign in</button></>
                  : <>Don't have an account?{' '}<button onClick={() => switchMode('signup')} style={{ background: 'none', border: 'none', color: 'var(--text)', fontWeight: 500, cursor: 'pointer', fontSize: 14 }}>Sign up</button></>
                }
              </p>
              <p style={{ textAlign: 'center', marginTop: 10, fontSize: 13, color: 'var(--text-dim)' }}>
                <button onClick={() => switchMode('forgot')} style={{ background: 'none', border: 'none', color: 'var(--text-muted)', cursor: 'pointer', fontSize: 13, textDecoration: 'underline' }}>
                  Forgot your password?
                </button>
              </p>
            </>
          )}
        </div>
      </div>
    </section>
  );
}

const socialBtnStyle = {
  flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center',
  gap: 8, padding: '10px 16px', background: 'var(--bg-2)',
  border: '1px solid var(--border)', borderRadius: 12,
  color: 'var(--text)', fontSize: 14, fontWeight: 500,
  cursor: 'pointer', transition: 'all 0.2s', outline: 'none',
};
const labelStyle = { display: 'block', fontSize: 14, fontWeight: 500, marginBottom: 8, color: 'var(--text)' };
const inputStyle = {
  width: '100%', padding: '12px 16px', background: 'var(--bg-2)',
  border: '1px solid var(--border)', borderRadius: 12,
  color: 'var(--text)', fontSize: 15, outline: 'none',
  transition: 'border-color 0.2s, box-shadow 0.2s', boxSizing: 'border-box'
};

if (typeof document !== 'undefined') {
  const s = document.createElement('style');
  s.textContent = `
    .login-card input:focus { border-color: var(--solo) !important; box-shadow: 0 0 0 3px rgba(88,166,255,0.2) !important; }
    #google-login-btn:hover, #github-login-btn:hover { background: var(--bg-3) !important; border-color: var(--border-muted) !important; }
  `;
  document.head.appendChild(s);
}

Object.assign(window, { LoginScreen });
