// Auth modal — Beautiful login interface
const AuthModal = ({ onAuthSuccess }) => {
  const [step, setStep] = React.useState('main'); // main, email, verify
  const [email, setEmail] = React.useState('');
  const [error, setError] = React.useState('');
  const [loading, setLoading] = React.useState(false);
  const hiddenGoogleButtonRef = React.useRef(null);

  // Initialize Google Sign-in with popup behavior on mount
  React.useEffect(() => {
    if (!window.google?.accounts?.id || !window.GOOGLE_CLIENT_ID) return;
    if (!hiddenGoogleButtonRef.current) return;

    window.google.accounts.id.initialize({
      client_id: window.GOOGLE_CLIENT_ID,
      ux_mode: 'popup',
      callback: async (response) => {
        if (!response.credential) return;
        setLoading(true);
        setError('');
        try {
          await window.AuthService.googleSignIn(response.credential);
          onAuthSuccess?.();
        } catch (err) {
          setError(err.message || 'Google sign-in failed');
        } finally {
          setLoading(false);
        }
      },
    });

    window.google.accounts.id.renderButton(hiddenGoogleButtonRef.current, {
      type: 'standard',
      theme: 'filled_blue',
      size: 'large',
      width: 300,
    });
  }, [onAuthSuccess]);

  const triggerGoogleSignIn = () => {
    setError('');
    const realGoogleBtn = hiddenGoogleButtonRef.current?.querySelector('div[role="button"]');
    if (realGoogleBtn) {
      realGoogleBtn.click();
    } else {
      setError('Google Sign-in not available');
    }
  };

  const handleEmailSubmit = async (e) => {
    e.preventDefault();
    if (!email.trim()) {
      setError('Please enter your email');
      return;
    }
    setLoading(true);
    setError('');
    try {
      await window.AuthService.requestLoginLink(email);
      setStep('verify');
    } catch (err) {
      setError(err.message || 'Failed to send magic link');
    } finally {
      setLoading(false);
    }
  };

  const handleGoogleSignIn = async (googleUser) => {
    setLoading(true);
    setError('');
    try {
      const idToken = googleUser.credential;
      await window.AuthService.googleSignIn(idToken);
      onAuthSuccess?.();
    } catch (err) {
      setError(err.message || 'Google sign-in failed');
    } finally {
      setLoading(false);
    }
  };

  const handleAppleSignIn = async () => {
    setLoading(true);
    setError('');
    try {
      if (!window.AppleID) {
        setError('Apple Sign-in is not available. Check your configuration.');
        setLoading(false);
        return;
      }

      const config = {
        clientId: window.APPLE_CLIENT_ID,
        scope: 'name email',
        redirectURI: window.location.origin,
        usePopup: true,
      };

      console.log('Apple Sign-in config:', config);

      window.AppleID.auth.init(config);

      const response = await window.AppleID.auth.signIn();
      if (response?.authorization?.id_token) {
        await window.AuthService.appleSignIn(response.authorization.id_token);
        onAuthSuccess?.();
      } else {
        setError('Apple Sign-in failed: No identity token received');
      }
    } catch (err) {
      console.error('Apple sign-in error:', err);
      setError(err.message || 'Apple sign-in failed');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div style={{
      position: 'fixed', inset: 0, zIndex: 9999,
      background: 'rgba(10,8,22,0.95)', backdropFilter: 'blur(8px)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      padding: 20
    }}>
      <div style={{
        width: '100%', maxWidth: 420, borderRadius: 24,
        background: 'rgba(255,255,255,0.05)', border: '1px solid rgba(255,255,255,0.1)',
        padding: 32, boxShadow: '0 20px 60px rgba(0,0,0,0.3)'
      }}>
        {step === 'main' && (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
            <div style={{ textAlign: 'center' }}>
              <h1 style={{ fontSize: 32, fontWeight: 700, margin: '0 0 8px', color: '#f4f1ff' }}>
                Sleepagotchi
              </h1>
              <p style={{ fontSize: 14, color: 'rgba(255,255,255,0.6)', margin: 0 }}>
                Your sleep, your way
              </p>
            </div>

            <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
              {/* Hidden Google button used to trigger official popup */}
              <div ref={hiddenGoogleButtonRef} style={{ position: 'absolute', left: '-9999px', visibility: 'hidden' }} />

              {/* Google Sign-in - Custom Button */}
              <button
                onClick={triggerGoogleSignIn}
                style={{
                  padding: 14, borderRadius: 12, border: '1px solid rgba(255,255,255,0.15)',
                  background: 'rgba(255,255,255,0.08)', cursor: 'pointer',
                  color: '#f4f1ff', fontSize: 15, fontWeight: 500,
                  display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10,
                  transition: 'all 0.2s',
                  fontFamily: 'inherit'
                }}
                onMouseOver={(e) => e.target.style.background = 'rgba(255,255,255,0.12)'}
                onMouseOut={(e) => e.target.style.background = 'rgba(255,255,255,0.08)'}
                disabled={loading}
              >
                <svg width="18" height="18" viewBox="0 0 24 24">
                  <path 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" fill="currentColor"/>
                  <path 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" fill="currentColor"/>
                  <path 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" fill="currentColor"/>
                  <path 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" fill="currentColor"/>
                </svg>
                {loading ? 'Signing in...' : 'Continue with Google'}
              </button>

              <button
                onClick={handleAppleSignIn}
                disabled={loading}
                style={{
                  padding: 14, borderRadius: 12, border: '1px solid rgba(255,255,255,0.15)',
                  background: 'rgba(255,255,255,0.08)', cursor: loading ? 'not-allowed' : 'pointer',
                  color: '#f4f1ff', fontSize: 15, fontWeight: 500,
                  display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10,
                  transition: 'all 0.2s', opacity: loading ? 0.7 : 1,
                  fontFamily: 'inherit'
                }}
                onMouseOver={(e) => !loading && (e.target.style.background = 'rgba(255,255,255,0.12)')}
                onMouseOut={(e) => !loading && (e.target.style.background = 'rgba(255,255,255,0.08)')}
              >
                <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor">
                  <path d="M18.71 19.5c-.83 1.24-1.71 2.45-3.05 2.47-1.34.02-1.77-.63-3.29-.63-1.52 0-2 .63-3.29.65-1.33.02-2.29-1.22-3.12-2.47C5.61 18.17 4.75 14.6 6.27 11.93c.79-1.35 2.37-2.2 4.04-2.23 1.28-.02 2.5.74 3.29.74.79 0 2.38-1 3.98-.85 1.75.15 3.23 1.1 4.04 2.47-1.7.98-2.75 2.73-2.91 4.64-.17 2.31.97 4.35 2.87 5.33zM12 5.38c1.62-1.45 2.71-3.32 2.57-5.38-.25.01-.56.15-.91.46-1.22 1.04-2.26 2.73-1.66 4.92z"/>
                </svg>
                {loading ? 'Signing in...' : 'Continue with Apple'}
              </button>

              <div style={{
                display: 'flex', alignItems: 'center', gap: 12, margin: '12px 0',
                color: 'rgba(255,255,255,0.4)', fontSize: 13
              }}>
                <div style={{ flex: 1, height: 1, background: 'rgba(255,255,255,0.1)' }} />
                <span>or</span>
                <div style={{ flex: 1, height: 1, background: 'rgba(255,255,255,0.1)' }} />
              </div>

              <button
                onClick={() => setStep('email')}
                style={{
                  padding: 14, borderRadius: 12, border: 'none',
                  background: 'linear-gradient(135deg, #a78bfa 0%, #8fe3b8 100%)',
                  color: '#000', fontSize: 15, fontWeight: 600,
                  cursor: 'pointer', fontFamily: 'inherit',
                  transition: 'transform 0.2s'
                }}
                onMouseOver={(e) => e.target.style.transform = 'scale(1.02)'}
                onMouseOut={(e) => e.target.style.transform = 'scale(1)'}
              >
                Continue with Email
              </button>
            </div>

            <p style={{
              fontSize: 12, color: 'rgba(255,255,255,0.5)', textAlign: 'center', margin: 0,
              lineHeight: 1.5
            }}>
              By signing in, you agree to our Terms of Service and Privacy Policy
            </p>
          </div>
        )}

        {step === 'email' && (
          <form onSubmit={handleEmailSubmit} style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
            <div>
              <h2 style={{ fontSize: 24, fontWeight: 600, margin: '0 0 8px', color: '#f4f1ff' }}>
                Enter your email
              </h2>
              <p style={{ fontSize: 14, color: 'rgba(255,255,255,0.6)', margin: 0 }}>
                We'll send you a magic link
              </p>
            </div>

            <input
              type="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              placeholder="your@email.com"
              style={{
                padding: '12px 16px', borderRadius: 12, border: '1px solid rgba(255,255,255,0.15)',
                background: 'rgba(255,255,255,0.05)', color: '#f4f1ff', fontSize: 15,
                fontFamily: 'inherit',
                outline: 'none', transition: 'all 0.2s'
              }}
              onFocus={(e) => e.target.style.borderColor = 'rgba(255,255,255,0.3)'}
              onBlur={(e) => e.target.style.borderColor = 'rgba(255,255,255,0.15)'}
            />

            {error && <p style={{ color: '#ff6b6b', fontSize: 14, margin: 0 }}>{error}</p>}

            <button
              type="submit"
              disabled={loading}
              style={{
                padding: 14, borderRadius: 12, border: 'none',
                background: 'linear-gradient(135deg, #a78bfa 0%, #8fe3b8 100%)',
                color: '#000', fontSize: 15, fontWeight: 600,
                cursor: loading ? 'not-allowed' : 'pointer', opacity: loading ? 0.7 : 1,
                fontFamily: 'inherit'
              }}
            >
              {loading ? 'Sending...' : 'Send Magic Link'}
            </button>

            <button
              type="button"
              onClick={() => { setStep('main'); setError(''); }}
              style={{
                padding: 12, borderRadius: 12, border: 'none',
                background: 'transparent', color: 'rgba(255,255,255,0.6)',
                fontSize: 14, cursor: 'pointer', fontFamily: 'inherit'
              }}
            >
              ← Back
            </button>
          </form>
        )}

        {step === 'verify' && (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 20, textAlign: 'center' }}>
            <div style={{
              width: 72, height: 72, borderRadius: '50%',
              background: 'linear-gradient(135deg, rgba(167,139,250,0.25), rgba(143,227,184,0.25))',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              margin: '0 auto 4px', border: '1px solid rgba(255,255,255,0.1)'
            }}>
              <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="#a78bfa" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
                <rect x="2" y="4" width="20" height="16" rx="2"/>
                <path d="M22 7L12 14 2 7"/>
              </svg>
            </div>

            <div>
              <h2 style={{ fontSize: 24, fontWeight: 600, margin: '0 0 10px', color: '#f4f1ff' }}>
                Check your inbox
              </h2>
              <p style={{ fontSize: 14, color: 'rgba(255,255,255,0.65)', margin: 0, lineHeight: 1.6 }}>
                We've sent a magic link to
              </p>
              <p style={{
                fontSize: 15, color: '#f4f1ff', margin: '6px 0 0',
                fontWeight: 600, wordBreak: 'break-all'
              }}>
                {email}
              </p>
              <p style={{
                fontSize: 13, color: 'rgba(255,255,255,0.5)', margin: '14px 0 0', lineHeight: 1.6
              }}>
                Open the email and tap the link to sign in.
              </p>
            </div>

            <button
              type="button"
              onClick={() => { setStep('main'); setError(''); setEmail(''); }}
              style={{
                padding: 12, borderRadius: 12, border: '1px solid rgba(255,255,255,0.15)',
                background: 'rgba(255,255,255,0.05)', color: '#f4f1ff',
                fontSize: 14, cursor: 'pointer', fontFamily: 'inherit',
                marginTop: 4
              }}
            >
              ← Back to sign-in options
            </button>
          </div>
        )}
      </div>
    </div>
  );
};
