// gs-auth.jsx — layar login/daftar gs.town (email + password)
function LoginScreen({ onAuthed, onClose }) {
  const [mode, setMode] = React.useState('login'); // login | signup
  const [name, setName] = React.useState('');
  const [email, setEmail] = React.useState('');
  const [pass, setPass] = React.useState('');
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState('');
  const [info, setInfo] = React.useState('');

  const submit = async () => {
    setErr(''); setInfo('');
    if (!email.trim() || !pass) return setErr('Email dan kata sandi wajib diisi');
    if (mode === 'signup' && !name.trim()) return setErr('Nama wajib diisi');
    if (pass.length < 6) return setErr('Kata sandi minimal 6 karakter');
    setBusy(true);
    try {
      if (mode === 'signup') {
        const res = await gsData.signUp(email.trim(), pass, name.trim());
        if (res.error) { setErr(res.error.message); setBusy(false); return; }
        if (res.data && res.data.session) { onAuthed(); return; }
        setInfo('Akun dibuat. Cek email untuk verifikasi, lalu masuk.');
        setMode('login'); setBusy(false); return;
      } else {
        const res = await gsData.signIn(email.trim(), pass);
        if (res.error) { setErr(res.error.message); setBusy(false); return; }
        onAuthed(); return;
      }
    } catch (e) { setErr(String(e.message || e)); setBusy(false); }
  };

  const field = (label, value, set, type, ph) => (
    <div>
      <label style={{ display: 'block', fontSize: 12.5, fontWeight: 700, color: 'var(--text-2)', marginBottom: 7 }}>{label}</label>
      <input value={value} type={type || 'text'} onChange={e => { set(e.target.value); setErr(''); }} placeholder={ph}
        autoCapitalize={type === 'email' ? 'none' : 'sentences'} autoCorrect="off"
        style={{ width: '100%', padding: '14px 15px', borderRadius: 'var(--r-md)', border: '1px solid var(--border)',
          background: 'var(--surface-2)', fontFamily: 'var(--font)', fontSize: 15, fontWeight: 500, color: 'var(--text-1)', outline: 'none' }} />
    </div>
  );

  return (
    <div style={{ position: 'relative', height: '100%', display: 'flex', flexDirection: 'column', background: 'var(--surface)', overflowY: 'auto' }}>
      {onClose && <button onClick={onClose} style={{ position: 'absolute', top: 'max(16px, env(safe-area-inset-top))', right: 16, zIndex: 5, width: 38, height: 38, borderRadius: '50%', border: '1px solid var(--border)', background: 'var(--surface)', display: 'grid', placeItems: 'center', cursor: 'pointer' }}><Icon name="x" size={18} color="var(--text-2)" /></button>}
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center', padding: '32px 26px', maxWidth: 460, width: '100%', margin: '0 auto' }}>
        <div style={{ marginBottom: 28 }}>
          <Logo size={34} />
          <h1 style={{ fontSize: 25, fontWeight: 800, letterSpacing: '-0.03em', color: 'var(--text-1)', marginTop: 22 }}>
            {mode === 'login' ? 'Selamat datang kembali' : 'Gabung warga Gading Serpong'}
          </h1>
          <p style={{ fontSize: 14.5, color: 'var(--text-2)', marginTop: 6 }}>
            {mode === 'login' ? 'Masuk untuk lapor & pantau lingkunganmu.' : 'Buat akun untuk mulai melapor dan kumpulkan poin.'}
          </p>
        </div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          {mode === 'signup' && field('Nama lengkap', name, setName, 'text', 'cth. Rama Aditya')}
          {field('Email', email, setEmail, 'email', 'kamu@email.com')}
          {field('Kata sandi', pass, setPass, 'password', 'minimal 6 karakter')}

          {err && (
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '11px 14px', borderRadius: 'var(--r-md)',
              background: 'var(--coral-50)', color: 'var(--coral-700)', fontSize: 13, fontWeight: 600 }}>
              <Icon name="shield" size={16} color="var(--coral-700)" /> {err}
            </div>
          )}
          {info && (
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '11px 14px', borderRadius: 'var(--r-md)',
              background: 'var(--lime-50)', color: 'var(--lime-700)', fontSize: 13, fontWeight: 600 }}>
              <Icon name="check" size={16} color="var(--lime-700)" /> {info}
            </div>
          )}

          <button onClick={submit} disabled={busy} style={{ width: '100%', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8,
            padding: '15px', borderRadius: 'var(--r-chip)', border: 'none', cursor: busy ? 'default' : 'pointer', opacity: busy ? 0.7 : 1,
            background: 'var(--primary)', color: '#fff', fontFamily: 'var(--font)', fontWeight: 800, fontSize: 15 }}>
            {busy ? 'Memproses...' : (mode === 'login' ? 'Masuk' : 'Daftar')}
            {!busy && <Icon name="arrow" size={18} color="#fff" sw={2.4} />}
          </button>
        </div>

        <div style={{ textAlign: 'center', marginTop: 22, fontSize: 13.5, color: 'var(--text-2)' }}>
          {mode === 'login' ? 'Belum punya akun? ' : 'Sudah punya akun? '}
          <button onClick={() => { setMode(mode === 'login' ? 'signup' : 'login'); setErr(''); setInfo(''); }}
            style={{ border: 'none', background: 'none', cursor: 'pointer', color: 'var(--primary)', fontWeight: 800, fontSize: 13.5, fontFamily: 'var(--font)' }}>
            {mode === 'login' ? 'Daftar sekarang' : 'Masuk'}
          </button>
        </div>
      </div>
    </div>
  );
}
window.LoginScreen = LoginScreen;
