const LoginPage = ({ onLogin }) => {
  const [username, setUsername] = React.useState('');
  const [password, setPassword] = React.useState('');
  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState('');

  const submitLogin = async (e) => {
    e?.preventDefault?.();
    if (!username || !password) {
      setError('Username and password required');
      return;
    }
    setLoading(true);
    setError('');
    try {
      const resp = await fetch(window.location.origin + '/api/auth/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ username, password })
      });
      const data = await resp.json();
      if (!resp.ok || !data.ok) {
        setError(data.error || 'Login failed');
        setLoading(false);
        return;
      }
      localStorage.setItem('accessToken', data.accessToken);
      localStorage.setItem('refreshToken', data.refreshToken);
      onLogin?.(data.accessToken, data.user);
      setLoading(false);
    } catch (err) {
      setError(err.message);
      setLoading(false);
    }
  };

  return (
    <div style={{
      minHeight: '100vh', background: 'var(--bg-app)', display: 'flex',
      alignItems: 'center', justifyContent: 'center', padding: 24, fontFamily: 'var(--font-sans)',
    }}>
      <div style={{ width: 440, maxWidth: '100%' }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 12, marginBottom: 28 }}>
          <div style={{ width: 44, height: 44, borderRadius: 12, background: 'linear-gradient(135deg,#40D0F0,#30D090)', display: 'flex', alignItems: 'center', justifyContent: 'center', boxShadow: 'var(--shadow-sm)', border: '1px solid rgba(255,255,255,0.3)' }}>
            <svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="2.75" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12 l4 4 l10 -10"/></svg>
          </div>
          <div>
            <div style={{ fontWeight: 800, fontSize: 24, color: 'var(--fg-1)', letterSpacing: '-0.02em' }}>
              ivac<span style={{ color: 'var(--fg-3)', fontWeight: 500, marginLeft: 4 }}>booking</span>
            </div>
            <div style={{ fontSize: 11, color: 'var(--fg-3)', marginTop: 2 }}>Booking Automation Control Plane</div>
          </div>
        </div>
        <Card style={{ padding: '32px 32px 28px' }}>
          <div style={{ marginBottom: 24 }}>
            <SectionLabel>Dashboard Access</SectionLabel>
            <div style={{ fontSize: 13, color: 'var(--fg-3)', marginTop: 4 }}>
              Operator access — secure authentication required.
            </div>
          </div>
          {error && <div style={{ marginBottom: 16 }}><InlineAlert variant='error'>{error}</InlineAlert></div>}
          <form onSubmit={submitLogin} style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
            <Input label="Username" icon="user" value={username} onChange={setUsername} placeholder="operator@ivacbd.com" autoComplete="username" />
            <Input label="Password" icon="lock" type="password" value={password} onChange={setPassword} placeholder="Enter your password" autoComplete="current-password" />
            <Button variant="primary-green" icon="log-in" style={{ width: '100%', justifyContent: 'center', marginTop: 6, height: 44 }} disabled={loading}>
              {loading ? 'Logging in…' : 'Login'}
            </Button>
          </form>
          <div style={{ marginTop: 18 }}>
            <InlineAlert variant='info'>
              Enter your username and password to access the dashboard.
            </InlineAlert>
          </div>
        </Card>
        <div style={{ textAlign: 'center', marginTop: 16, fontSize: 11, color: 'var(--fg-3)', fontFamily: 'var(--font-mono)' }}>
          v2.1 · build 4a8f · appointment.ivacbd.com
        </div>
      </div>
    </div>
  );
};
Object.assign(window, { LoginPage });
