// auth-login.jsx — login screen (pilih nama + PIN)
const { useState: useSL, useEffect: useEL } = React;

function Login({ onLogin }) {
  const [emps, setEmps] = useSL(null);
  const [sel, setSel] = useSL(null);
  const [pickerOpen, setPickerOpen] = useSL(false);
  const [pin, setPin] = useSL('');
  const [err, setErr] = useSL('');
  const [busy, setBusy] = useSL(false);
  const [q, setQ] = useSL('');

  useEL(() => { MA.getEmployees().then(r => setEmps(r.ok ? r.employees : [])); }, []);

  const submit = async (code) => {
    if (!sel) { setErr('Pilih nama dulu'); return; }
    setBusy(true); setErr('');
    const r = await MA.login(sel.id, code);
    setBusy(false);
    if (r.ok) { MA.saveSession(r.user); onLogin(r.user); }
    else { setErr(r.err || 'Login gagal'); setPin(''); }
  };

  const tapKey = (d) => {
    if (busy) return;
    setErr('');
    if (d === 'del') { setPin(p => p.slice(0, -1)); return; }
    setPin(p => {
      const np = (p + d).slice(0, 4);
      if (np.length === 4) setTimeout(() => submit(np), 120);
      return np;
    });
  };

  const list = (emps || []).filter(e => e.name.toLowerCase().includes(q.toLowerCase()) || e.jabatan.toLowerCase().includes(q.toLowerCase()));

  return (
    <div className="screen" style={{ background: 'var(--app-bg)' }}>
      <div className="scroll" style={{ display: 'flex', flexDirection: 'column', padding: '0 24px 24px' }}>
        {/* hero */}
        <div style={{ textAlign: 'center', paddingTop: 30, paddingBottom: 8 }}>
          <div style={{ display: 'inline-flex', background: '#fff', borderRadius: 22, padding: '16px 20px', boxShadow: 'var(--shadow-md)' }}>
            <img src="assets/motoart-logo.png" alt="MOTOART" style={{ height: 66, width: 'auto', display: 'block' }} />
          </div>
          <div className="display" style={{ fontWeight: 800, fontSize: 23, color: 'var(--text)', marginTop: 22, letterSpacing: '-.4px' }}>Absensi Karyawan</div>
          <div style={{ fontSize: 14, color: 'var(--text-dim)', fontWeight: 500, marginTop: 4 }}>{MA.DEALER.branch}</div>
        </div>

        <div style={{ flex: 1 }}></div>

        {/* name field */}
        <div className="label-cap" style={{ marginBottom: 8 }}>Nama Karyawan</div>
        <button onClick={() => setPickerOpen(true)} style={{ display: 'flex', alignItems: 'center', gap: 13, width: '100%', padding: 14, borderRadius: 16, background: 'var(--surface)', border: '1px solid var(--border)', boxShadow: 'var(--shadow-sm)' }}>
          {sel ? <Avatar init={sel.init} size={42} /> : <div style={{ width: 42, height: 42, borderRadius: '50%', background: 'var(--surface-3)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon name="user" size={22} stroke="var(--text-mute)" /></div>}
          <div style={{ flex: 1, textAlign: 'left' }}>
            <div style={{ fontSize: 15, fontWeight: 700, color: sel ? 'var(--text)' : 'var(--text-mute)' }}>{sel ? sel.name : 'Pilih nama Anda…'}</div>
            {sel && <div style={{ fontSize: 12.5, color: 'var(--text-dim)', fontWeight: 500 }}>{sel.jabatan}</div>}
          </div>
          <Icon name="chevronDown" size={20} stroke="var(--text-mute)" />
        </button>

        {/* PIN */}
        <div className="label-cap" style={{ margin: '20px 0 10px' }}>Masukkan PIN</div>
        <div style={{ display: 'flex', gap: 12, justifyContent: 'center', marginBottom: 6 }}>
          {[0, 1, 2, 3].map(i => (
            <div key={i} style={{ width: 16, height: 16, borderRadius: '50%', background: pin.length > i ? 'var(--accent)' : 'var(--surface-3)', border: pin.length > i ? 'none' : '2px solid var(--border-2)', transition: 'all .15s' }}></div>
          ))}
        </div>
        <div style={{ height: 22, textAlign: 'center', color: 'var(--danger)', fontSize: 13, fontWeight: 600 }}>{busy ? 'Memeriksa…' : err}</div>

        {/* keypad */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 12, marginTop: 4 }}>
          {['1','2','3','4','5','6','7','8','9'].map(d => (
            <button key={d} onClick={() => tapKey(d)} className="display" style={keyStyle}>{d}</button>
          ))}
          <div></div>
          <button onClick={() => tapKey('0')} className="display" style={keyStyle}>0</button>
          <button onClick={() => tapKey('del')} style={{ ...keyStyle, background: 'transparent', boxShadow: 'none' }}><Icon name="chevron" size={24} stroke="var(--text-dim)" style={{ transform: 'rotate(180deg)' }} /></button>
        </div>

        {MA.DEMO && (
          <div style={{ marginTop: 18, padding: '11px 14px', background: 'var(--accent-weak)', borderRadius: 12, fontSize: 12, color: 'var(--text-dim)', fontWeight: 500, textAlign: 'center' }}>
            <b style={{ color: 'var(--accent)' }}>Mode Demo</b> · PIN karyawan <b>1234</b>, pemilik <b>0000</b>
          </div>
        )}
      </div>

      {/* name picker sheet */}
      {pickerOpen && (
        <div className="sheet-scrim" onClick={() => setPickerOpen(false)}>
          <div className="sheet" onClick={e => e.stopPropagation()} style={{ maxHeight: '78%', display: 'flex', flexDirection: 'column' }}>
            <div className="sheet-grab"></div>
            <div className="display" style={{ fontWeight: 800, fontSize: 18, color: 'var(--text)', marginBottom: 12 }}>Pilih Nama</div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 9, background: 'var(--surface-2)', border: '1px solid var(--border)', borderRadius: 12, padding: '10px 13px', marginBottom: 8 }}>
              <Icon name="search" size={18} stroke="var(--text-mute)" />
              <input autoFocus value={q} onChange={e => setQ(e.target.value)} placeholder="Cari nama…" style={{ border: 'none', outline: 'none', background: 'transparent', flex: 1, fontSize: 14, color: 'var(--text)', fontFamily: 'inherit' }} />
            </div>
            <div style={{ overflowY: 'auto', margin: '0 -4px' }}>
              {emps === null && <div style={{ padding: 24, textAlign: 'center', color: 'var(--text-mute)', fontSize: 14 }}>Memuat…</div>}
              {list.map(e => (
                <button key={e.id} onClick={() => { setSel(e); setPin(''); setErr(''); setPickerOpen(false); setQ(''); }} style={{ display: 'flex', alignItems: 'center', gap: 13, width: '100%', padding: '11px 6px', textAlign: 'left' }}>
                  <Avatar init={e.init} size={40} />
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 14.5, fontWeight: 700, color: 'var(--text)' }}>{e.name}</div>
                    <div style={{ fontSize: 12.5, color: 'var(--text-dim)', fontWeight: 500 }}>{e.jabatan}</div>
                  </div>
                  {e.role === 'pemilik' && <span className="chip neutral" style={{ fontSize: 10.5, color: 'var(--accent)', background: 'var(--accent-weak)' }}>Pemilik</span>}
                </button>
              ))}
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

const keyStyle = {
  height: 58, borderRadius: 16, background: 'var(--surface)', border: '1px solid var(--border)',
  boxShadow: 'var(--shadow-sm)', fontSize: 24, fontWeight: 700, color: 'var(--text)',
};

window.Login = Login;
