// Forgot Password Modal
const ForgotPasswordModal = ({ onClose, onSubmit }) => {
  const [step, setStep] = React.useState(1);
  const [email, setEmail] = React.useState('');
  const [otp, setOtp] = React.useState('');
  const [newPassword, setNewPassword] = React.useState('');
  const [confirmPassword, setConfirmPassword] = React.useState('');
  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState('');
  const [success, setSuccess] = React.useState('');

  const handleStep1 = async () => {
    if (!email) { setError('Email is required'); return; }
    setLoading(true);
    setError('');
    try {
      const res = await fetch('http://localhost:3001/api/v1/auth/forgot-password', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email })
      });
      if (!res.ok) {
        const data = await res.json();
        setError(data.message || 'Failed to send OTP');
        return;
      }
      setSuccess('OTP sent to your email');
      setStep(2);
    } catch (err) {
      setError(err.message || 'Network error');
    } finally {
      setLoading(false);
    }
  };

  const handleStep3 = async () => {
    if (!otp || !newPassword || !confirmPassword) { setError('All fields required'); return; }
    if (newPassword !== confirmPassword) { setError('Passwords do not match'); return; }
    if (newPassword.length < 8) { setError('Password must be at least 8 characters'); return; }

    setLoading(true);
    setError('');
    try {
      const res = await fetch('http://localhost:3001/api/v1/auth/reset-password', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email, otp, newPassword })
      });
      if (!res.ok) {
        const data = await res.json();
        setError(data.message || 'Invalid OTP');
        return;
      }
      setSuccess('Password reset successfully!');
      setTimeout(onClose, 2000);
    } catch (err) {
      setError(err.message || 'Network error');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.5)', display: 'grid', placeItems: 'center', zIndex: 1000 }}>
      <div style={{ background: 'white', borderRadius: 12, padding: 32, maxWidth: 420, width: '90%', boxShadow: '0 20px 60px rgba(0,0,0,0.3)' }}>
        <h2 style={{ margin: '0 0 24px', fontSize: 22, fontWeight: 600 }}>Reset Password</h2>

        {error && <div style={{ background: '#fee2e2', color: '#991b1b', padding: '12px 14px', borderRadius: 8, marginBottom: 16, fontSize: 13 }}>⚠️ {error}</div>}
        {success && <div style={{ background: '#dcfce7', color: '#166534', padding: '12px 14px', borderRadius: 8, marginBottom: 16, fontSize: 13 }}>✓ {success}</div>}

        {step === 1 && (
          <>
            <label style={{ display: 'block', marginBottom: 8, fontSize: 13, fontWeight: 600 }}>Email Address</label>
            <input type="email" value={email} onChange={(e) => setEmail(e.target.value)} placeholder="your@email.com" style={{ width: '100%', padding: '10px 12px', border: '1px solid #d1d5db', borderRadius: 8, marginBottom: 16, boxSizing: 'border-box' }} disabled={loading} />
            <button onClick={handleStep1} disabled={loading} style={{ width: '100%', padding: '10px 12px', background: '#5b5bd6', color: 'white', border: 'none', borderRadius: 8, fontWeight: 600, cursor: loading ? 'not-allowed' : 'pointer', opacity: loading ? 0.7 : 1 }}>
              {loading ? 'Sending...' : 'Send OTP'}
            </button>
          </>
        )}

        {step === 2 && (
          <>
            <label style={{ display: 'block', marginBottom: 8, fontSize: 13, fontWeight: 600 }}>OTP (from email)</label>
            <input type="text" value={otp} onChange={(e) => setOtp(e.target.value)} placeholder="000000" maxLength="6" style={{ width: '100%', padding: '10px 12px', border: '1px solid #d1d5db', borderRadius: 8, marginBottom: 12, boxSizing: 'border-box', fontSize: 18, letterSpacing: 4, textAlign: 'center' }} />

            <label style={{ display: 'block', marginBottom: 8, fontSize: 13, fontWeight: 600 }}>New Password</label>
            <input type="password" value={newPassword} onChange={(e) => setNewPassword(e.target.value)} placeholder="Min 8 characters" style={{ width: '100%', padding: '10px 12px', border: '1px solid #d1d5db', borderRadius: 8, marginBottom: 12, boxSizing: 'border-box' }} disabled={loading} />

            <label style={{ display: 'block', marginBottom: 8, fontSize: 13, fontWeight: 600 }}>Confirm Password</label>
            <input type="password" value={confirmPassword} onChange={(e) => setConfirmPassword(e.target.value)} placeholder="Min 8 characters" style={{ width: '100%', padding: '10px 12px', border: '1px solid #d1d5db', borderRadius: 8, marginBottom: 16, boxSizing: 'border-box' }} disabled={loading} />

            <button onClick={handleStep3} disabled={loading} style={{ width: '100%', padding: '10px 12px', background: '#5b5bd6', color: 'white', border: 'none', borderRadius: 8, fontWeight: 600, cursor: loading ? 'not-allowed' : 'pointer', opacity: loading ? 0.7 : 1 }}>
              {loading ? 'Resetting...' : 'Reset Password'}
            </button>
          </>
        )}

        <button onClick={onClose} style={{ marginTop: 16, width: '100%', padding: '10px 12px', background: 'transparent', border: '1px solid #d1d5db', borderRadius: 8, fontWeight: 600, cursor: 'pointer' }}>
          Cancel
        </button>
      </div>
    </div>
  );
};

function LoginScreen({ onLogin, error, loading }) {
  const [email, setEmail] = React.useState('');
  const [password, setPassword] = React.useState('');
  const [showPassword, setShowPassword] = React.useState(false);
  const [localError, setLocalError] = React.useState(null);
  const [showForgotPassword, setShowForgotPassword] = React.useState(false);

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!email || !password) {
      setLocalError('Email and password are required');
      return;
    }
    setLocalError(null);
    await onLogin(email, password);
  };

  return (
    <div style={{
      display: 'grid',
      gridTemplateColumns: '1fr 1fr',
      height: '100vh',
      background: 'white',
      overflow: 'hidden',
    }}>
      {/* LEFT: Illustration */}
      <div style={{
        background: 'linear-gradient(160deg, #3730a3 0%, #4f46e5 55%, #6366f1 100%)',
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        justifyContent: 'center',
        padding: '30px 25px',
        color: 'white',
        position: 'relative',
        overflow: 'hidden',
      }}>
        {/* Abstract background orbs */}
        <div style={{ position: 'absolute', inset: 0, pointerEvents: 'none' }}>
          <div style={{ position: 'absolute', top: '-80px', left: '-80px', width: '320px', height: '320px', borderRadius: '50%', background: 'rgba(255,255,255,0.06)', filter: 'blur(2px)' }} />
          <div style={{ position: 'absolute', bottom: '-60px', right: '-60px', width: '260px', height: '260px', borderRadius: '50%', background: 'rgba(255,255,255,0.07)' }} />
          <div style={{ position: 'absolute', top: '50%', left: '60%', transform: 'translate(-50%,-50%)', width: '180px', height: '180px', borderRadius: '50%', background: 'rgba(255,255,255,0.04)' }} />
          <div style={{ position: 'absolute', top: '20%', right: '-30px', width: '120px', height: '120px', borderRadius: '50%', border: '1.5px solid rgba(255,255,255,0.12)' }} />
          <div style={{ position: 'absolute', bottom: '22%', left: '-20px', width: '90px', height: '90px', borderRadius: '50%', border: '1.5px solid rgba(255,255,255,0.1)' }} />
          <div style={{ position: 'absolute', top: '38%', left: '12%', width: '48px', height: '48px', borderRadius: '50%', background: 'rgba(255,255,255,0.09)' }} />
          <div style={{ position: 'absolute', bottom: '30%', right: '14%', width: '32px', height: '32px', borderRadius: '50%', background: 'rgba(255,255,255,0.11)' }} />
          <div style={{ position: 'absolute', top: '68%', left: '38%', width: '16px', height: '16px', borderRadius: '50%', background: 'rgba(255,255,255,0.15)' }} />
          <div style={{ position: 'absolute', top: '14%', left: '30%', width: '10px', height: '10px', borderRadius: '50%', background: 'rgba(255,255,255,0.2)' }} />
        </div>

        <div style={{ position: 'relative', zIndex: 1, textAlign: 'center' }}>
          <div style={{
            width: '68px',
            height: '68px',
            borderRadius: '16px',
            background: 'rgba(255,255,255,0.15)',
            display: 'grid',
            placeItems: 'center',
            margin: '0 auto 20px',
            backdropFilter: 'blur(12px)',
            border: '1px solid rgba(255,255,255,0.25)',
            overflow: 'hidden',
            boxShadow: '0 8px 32px rgba(0,0,0,0.15)',
          }}><img src="favicon.ico" alt="Merida HostOps" style={{ width: 48, height: 48, objectFit: 'contain' }} /></div>

          <h2 style={{ fontSize: '27px', fontWeight: '700', margin: '0 0 8px 0', letterSpacing: '-0.3px' }}>Merida HostOps</h2>
          <p style={{ fontSize: '13px', fontWeight: '400', margin: 0, opacity: 0.75, lineHeight: 1.5 }}>
            Subscription & Domain<br />Management Platform
          </p>
        </div>
      </div>

      {/* RIGHT: Form */}
      <div style={{
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        justifyContent: 'center',
        padding: '25px 35px',
        background: '#fafbfc',
        overflow: 'auto',
      }}>
        <div style={{ width: '100%', maxWidth: '340px' }}>
          <div style={{ marginBottom: '20px' }}>
            <h1 style={{ fontSize: '22px', fontWeight: '700', margin: '0 0 5px 0', color: '#1f2937' }}>Sign In</h1>
            <p style={{ fontSize: '12px', color: '#6b7280', margin: '0', lineHeight: 1.4 }}>Enter your credentials to access your account</p>
          </div>

          <form onSubmit={handleSubmit} style={{ display: 'flex', flexDirection: 'column', gap: '14px', marginBottom: '14px' }}>
            <div>
              <label style={{ display: 'block', marginBottom: '6px', fontSize: '12px', fontWeight: '600', color: '#374151' }}>EMAIL</label>
              <input type="email" value={email} onChange={(e) => setEmail(e.target.value)} disabled={loading} placeholder="you@example.com" style={{
                width: '100%', padding: '10px 12px', border: '1px solid #d1d5db', borderRadius: '6px', fontSize: '13px', boxSizing: 'border-box', fontFamily: 'inherit', background: 'white', transition: 'all 200ms', outline: 'none'
              }} onFocus={(e) => e.target.style.borderColor = '#5b5bd6'} onBlur={(e) => e.target.style.borderColor = '#d1d5db'} />
            </div>

            <div>
              <label style={{ display: 'block', marginBottom: '6px', fontSize: '12px', fontWeight: '600', color: '#374151' }}>PASSWORD</label>
              <div style={{ position: 'relative', display: 'flex', alignItems: 'center' }}>
                <input type={showPassword ? 'text' : 'password'} value={password} onChange={(e) => setPassword(e.target.value)} disabled={loading} placeholder="••••••••" style={{
                  flex: 1, padding: '10px 12px', paddingRight: '40px', border: '1px solid #d1d5db', borderRadius: '6px', fontSize: '13px', boxSizing: 'border-box', fontFamily: 'inherit', background: 'white', transition: 'all 200ms', outline: 'none'
                }} onFocus={(e) => e.target.style.borderColor = '#5b5bd6'} onBlur={(e) => e.target.style.borderColor = '#d1d5db'} />
                <button type="button" onClick={() => setShowPassword(!showPassword)} disabled={loading} style={{
                  position: 'absolute', right: '12px', background: 'none', border: 'none', cursor: loading ? 'not-allowed' : 'pointer', padding: '4px', display: 'flex', alignItems: 'center', color: 'var(--text-muted)', opacity: loading ? 0.5 : 1
                }}>
                  {showPassword ? '👁' : '👁‍🗨'}
                </button>
              </div>
            </div>

            {(localError || error) && (
              <div style={{ background: '#fee2e2', border: '1px solid #fecaca', borderRadius: '6px', padding: '10px 12px', fontSize: '12px', color: '#991b1b', display: 'flex', alignItems: 'center', gap: '8px' }}>
                <span>⚠️</span> {localError || error}
              </div>
            )}

            <button type="submit" disabled={loading} style={{
              background: loading ? '#9ca3af' : 'linear-gradient(135deg, #4338ca, #6366f1)',
              color: 'white', border: 'none', borderRadius: '6px', padding: '10px 14px', fontSize: '13px', fontWeight: '600', cursor: loading ? 'not-allowed' : 'pointer', marginTop: '4px', transition: 'all 200ms', boxShadow: loading ? 'none' : '0 4px 14px rgba(79, 70, 229, 0.35)'
            }}>
              {loading ? 'Signing in...' : 'Sign In'}
            </button>
          </form>

          <div style={{ textAlign: 'center', fontSize: '12px' }}>
            <button onClick={() => setShowForgotPassword(true)} style={{ color: '#5b5bd6', fontWeight: '500', cursor: 'pointer', background: 'none', border: 'none', fontSize: 12, textDecoration: 'underline' }}>Forgot password?</button>
          </div>

          {showForgotPassword && <ForgotPasswordModal onClose={() => setShowForgotPassword(false)} />}
        </div>
      </div>
    </div>
  );
}

window.LoginScreen = LoginScreen;
