// Login.jsx — staff sign in. Used in phone frame (compact) and desktop chrome.
const { useState: useStateLogin } = React;

function Login({ accounts, onLogin, authenticate, online, compact, onBack, lang = 'en', onLang }) {
  const T = window.TOK, B = window.BRAND, D = window.dict(lang);
  const [id, setId] = useStateLogin('');
  const [pw, setPw] = useStateLogin('');
  const [err, setErr] = useStateLogin('');
  const [show, setShow] = useStateLogin(false);
  const [busy, setBusy] = useStateLogin(false);

  const submit = async () => {
    if (busy) return;
    setBusy(true); setErr('');
    try {
      const run = authenticate || (async (i, p) => {
        const a = accounts.find(x => x.id.toLowerCase() === i.trim().toLowerCase() && x.password === p);
        if (!a) throw new Error('invalid'); return a;
      });
      const acc = await run(id, pw);
      onLogin(acc);
    } catch (e) {
      setErr(D.login_err);
    } finally {
      setBusy(false);
    }
  };

  const field = (label, value, onChange, props = {}) => (
    <label style={{ display: 'block' }}>
      <span style={{ display: 'block', fontSize: 13, fontWeight: 600, color: T.inkSoft, marginBottom: 7 }}>{label}</span>
      <input value={value} onChange={e => { onChange(e.target.value); setErr(''); }} {...props}
        onKeyDown={e => { if (e.key === 'Enter') submit(); }}
        style={{ width: '100%', boxSizing: 'border-box', height: 50, padding: '0 14px', fontFamily: 'inherit', fontSize: 16, color: T.ink, background: T.surface, border: `1px solid ${err ? '#E0A09433' : T.line}`, borderRadius: 12, outline: 'none' }}
        onFocus={e => e.target.style.borderColor = T.accent} onBlur={e => e.target.style.borderColor = T.line} />
    </label>
  );

  const form = (
    <div style={{ width: '100%', maxWidth: 380, margin: '0 auto' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 11, marginBottom: 6 }}>
        <span style={{ width: 38, height: 38, borderRadius: 11, background: T.accent, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <svg width="22" height="22" viewBox="0 0 24 24" fill="none"><path d="M3 12h3l2-5 3 9 2.5-6 1.5 2H21" stroke="#fff" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"/></svg>
        </span>
        <span style={{ fontFamily: "'Instrument Serif', serif", fontSize: 24, color: T.ink }}>{B.name}</span>
      </div>
      <div style={{ fontFamily: "'Anek Bangla', 'Hind Siliguri', sans-serif", fontWeight: 600, fontSize: compact ? 28 : 32, color: T.ink, lineHeight: 1.15, margin: '18px 0 6px' }}>{D.staff_login}</div>
      <div style={{ fontSize: 14.5, color: T.muted, marginBottom: 24 }}>{D.login_sub}</div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
        {field(D.l_id, id, setId, { placeholder: 'reception', autoCapitalize: 'none' })}
        <div>
          <span style={{ display: 'block', fontSize: 13, fontWeight: 600, color: T.inkSoft, marginBottom: 7 }}>{D.l_pw}</span>
          <div style={{ position: 'relative' }}>
            <input value={pw} onChange={e => { setPw(e.target.value); setErr(''); }} type={show ? 'text' : 'password'}
              onKeyDown={e => { if (e.key === 'Enter') submit(); }} placeholder="••••••••"
              style={{ width: '100%', boxSizing: 'border-box', height: 50, padding: '0 46px 0 14px', fontFamily: 'inherit', fontSize: 16, color: T.ink, background: T.surface, border: `1px solid ${T.line}`, borderRadius: 12, outline: 'none' }}
              onFocus={e => e.target.style.borderColor = T.accent} onBlur={e => e.target.style.borderColor = T.line} />
            <button onClick={() => setShow(s => !s)} style={{ position: 'absolute', right: 6, top: 6, width: 38, height: 38, border: 'none', background: 'none', cursor: 'pointer', color: T.faint, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none"><path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7-10-7-10-7Z" stroke="currentColor" strokeWidth="1.8"/><circle cx="12" cy="12" r="2.6" stroke="currentColor" strokeWidth="1.8"/>{!show && <path d="M4 4l16 16" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"/>}</svg>
            </button>
          </div>
        </div>

        {err && <div style={{ fontSize: 13.5, color: '#C0492B', background: '#FBEAE5', padding: '10px 12px', borderRadius: 10 }}>{err}</div>}

        <button onClick={submit} disabled={busy} style={{ height: 52, cursor: busy ? 'wait' : 'pointer', opacity: busy ? 0.7 : 1, fontFamily: 'inherit', fontSize: 17, fontWeight: 600, color: '#fff', background: T.accent, border: 'none', borderRadius: 13, boxShadow: '0 10px 24px rgba(28,119,206,0.28)' }}>{busy ? '…' : D.login_enter}</button>
      </div>

      {/* demo credentials — prototype/offline only; removed when wired to the real backend */}
      {!online && (
      <div style={{ marginTop: 22, border: `1px dashed ${T.line}`, borderRadius: 14, padding: '14px 16px', background: T.bone }}>
        <div style={{ fontSize: 11.5, fontWeight: 700, letterSpacing: 1.2, color: T.faint, textTransform: 'uppercase', marginBottom: 10 }}>{D.demo_label}</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {accounts.filter(a => a.created === 'Owner').map(a => (
            <button key={a.id} onClick={() => { setId(a.id); setPw(a.password); setErr(''); }} style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10, padding: '9px 11px', background: T.surface, border: `1px solid ${T.line}`, borderRadius: 10, cursor: 'pointer', fontFamily: 'inherit', textAlign: 'left' }}>
              <span>
                <span style={{ display: 'block', fontSize: 14, fontWeight: 600, color: T.ink }}>{D['role_' + a.role]}</span>
                <span style={{ display: 'block', fontSize: 12.5, color: T.muted, fontFamily: 'monospace', marginTop: 1 }}>{a.id} · {a.password}</span>
              </span>
              <span style={{ fontSize: 12.5, fontWeight: 600, color: T.accent }}>{D.demo_fill}</span>
            </button>
          ))}
        </div>
      </div>
      )}

      {onBack && (
        <button onClick={onBack} style={{ marginTop: 18, width: '100%', height: 44, cursor: 'pointer', fontFamily: 'inherit', fontSize: 14.5, fontWeight: 600, color: T.muted, background: 'none', border: 'none' }}>{D.login_back}</button>
      )}
    </div>
  );

  if (compact) {
    return (
      <div style={{ position: 'relative', height: '100%', background: T.bone, fontFamily: "'Hanken Grotesk', sans-serif" }}>
        <window.LangToggle lang={lang} onLang={onLang} style={{ position: 'absolute', top: 56, right: 22, zIndex: 10 }} />
        <div style={{ height: '100%', overflowY: 'auto', padding: '64px 26px 36px' }}>
          {form}
        </div>
      </div>
    );
  }

  // desktop — split: brand panel + form
  return (
    <div style={{ height: '100%', display: 'flex', fontFamily: "'Hanken Grotesk', sans-serif", background: T.surface }}>
      <div style={{ flex: '0 0 44%', position: 'relative', overflow: 'hidden', background: 'linear-gradient(168deg, #1C77CE 0%, #134d86 100%)', color: '#fff', padding: '56px 52px', display: 'flex', flexDirection: 'column', justifyContent: 'space-between' }}>
        <div style={{ fontSize: 12, fontWeight: 600, letterSpacing: 2.4, textTransform: 'uppercase', opacity: 0.85 }}>{B.caption}</div>
        <div>
          <div style={{ fontFamily: "'Anek Bangla', 'Hind Siliguri', sans-serif", fontWeight: 600, fontSize: 46, lineHeight: 1.1 }}>{D.staff_portal}</div>
          <div style={{ fontSize: 16.5, lineHeight: 1.7, opacity: 0.9, marginTop: 16, maxWidth: 360 }}>{D.portal_blurb}</div>
        </div>
        <div style={{ fontSize: 13.5, opacity: 0.82 }}>{B.doctor} · {B.hospital}</div>
      </div>
      <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 40, overflowY: 'auto', position: 'relative' }}>
        <window.LangToggle lang={lang} onLang={onLang} style={{ position: 'absolute', top: 22, right: 22, zIndex: 10 }} />
        {form}
      </div>
    </div>
  );
}

window.Login = Login;
