// screen-login.jsx — email + password login, wired to POST /auth/login.
// Styled with the design's own primitives (Field, Btn, Watt, SHWordmark) so it
// reads as part of the app. On success it hands the session up via onLoggedIn.

function LoginScreen({ c, onLoggedIn }) {
  const { useState } = React;
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState('');
  const [busy, setBusy] = useState(false);

  const canSubmit = email.trim() && password && !busy;

  const submit = async (e) => {
    if (e) e.preventDefault();
    if (!canSubmit) return;
    setBusy(true);
    setError('');
    try {
      const data = await SaveHorAPI.login(email.trim(), password);
      onLoggedIn?.(data);
    } catch (err) {
      setError(err.message || 'Login failed.');
      setBusy(false);
    }
  };

  return (
    <div style={{
      flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center',
      padding: '0 28px', minHeight: 0, background: c.bg,
    }}>
      {/* brand + welcome */}
      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 14, marginBottom: 28 }}>
        <Watt size={72} color={c.primary} bg={c.primarySoft} mood="wave" />
        <SHWordmark size={22} color={c.text} />
        <div style={{ textAlign: 'center' }}>
          <div style={{ fontSize: 24, fontWeight: 700, color: c.text, letterSpacing: -0.5 }}>Welcome back</div>
          <div style={{ fontSize: 14, color: c.textMuted, marginTop: 4 }}>Log in to see today's energy use.</div>
        </div>
      </div>

      {/* form */}
      <form onSubmit={submit} style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
        <Field
          label="Email" type="email" placeholder="you@savehor.com"
          value={email} onChange={(e) => { setEmail(e.target.value); setError(''); }}
          c={c} />
        <Field
          label="Password" type="password" placeholder="••••••••"
          value={password} onChange={(e) => { setPassword(e.target.value); setError(''); }}
          c={c} />

        {error && (
          <div style={{
            fontSize: 13, fontWeight: 500, color: c.danger,
            background: c.dangerSoft, borderRadius: 12, padding: '10px 14px', lineHeight: 1.4,
          }}>{error}</div>
        )}

        {/* Btn renders a <button> with no type, so inside this form it acts as
            the submit button — the form's onSubmit fires submit(). */}
        <Btn kind="primary" size="lg" c={c} full disabled={!canSubmit}
          style={{ marginTop: 4 }}>
          {busy ? 'Logging in…' : 'Log in'}
        </Btn>
      </form>
    </div>
  );
}

Object.assign(window, { LoginScreen });
