// ──────────────────────────── Login / Lock screen ────────────────────────────
const { useState: useStateL } = React;

// storeId: null = accesso multi-negozio libero; valorizzato = bloccato su quel punto vendita.
// pin: default '1234' per tutti — cambiabile dal pannello profilo.
// active: false = disattivato, non compare al login.
// canMagazzinoWrite: permesso extra per Cassiere (attivabile da Admin/Manager).
const OPERATORS = [
  { id: 'sara',    name: 'Sara Vitale',    initials: 'SV', role: 'Admin',         storeId: null,          pin: '1234', active: true, lastAccess: '27/05/2026 16:30', canMagazzinoWrite: false },
  { id: 'roberto', name: 'Roberto Manca',  initials: 'RM', role: 'Manager',       storeId: null,          pin: '1234', active: true, lastAccess: '28/05/2026 08:15', canMagazzinoWrite: false },
  { id: 'luca',    name: 'Luca De Santis', initials: 'LD', role: 'Store Manager', storeId: 'roma-spagna', pin: '1234', active: true, lastAccess: '28/05/2026 10:00', canMagazzinoWrite: false },
  { id: 'giulia',  name: 'Giulia Moretti', initials: 'GM', role: 'Cassiere',      storeId: 'roma-spagna', pin: '1234', active: true, lastAccess: '28/05/2026 09:42', canMagazzinoWrite: false },
  { id: 'marco',   name: 'Marco Ferretti', initials: 'MF', role: 'Magazziniere',  storeId: 'roma-spagna', pin: '1234', active: true, lastAccess: '28/05/2026 09:55', canMagazzinoWrite: false },
];

// Login a due porte: si entra con USERNAME + PASSWORD.
//  • account NEGOZIO (postazione): username = id negozio → vede tutto quel negozio
//  • persona privilegiata (Admin / Area Manager) — login diretto con password
// Niente più griglia di volti. Dentro il negozio, ognuno si identifica con username+PIN.
const LoginScreen = ({ onLogin }) => {
  const [username, setUsername] = useStateL('');
  const [password, setPassword] = useStateL('');
  const [error, setError] = useStateL(false);
  const [busy, setBusy] = useStateL(false);

  const submit = async (e) => {
    if (e) e.preventDefault();
    if (!username.trim() || !password || busy) return;
    setBusy(true); setError(false);
    const ok = window.__API__ ? await window.__API__.login(username.trim(), password) : true;
    setBusy(false);
    if (ok) { onLogin(); }
    else { setError(true); setPassword(''); } // l'errore resta finché non si riscrive
  };

  const today = new Date().toLocaleDateString('it-IT', { weekday: 'long', day: 'numeric', month: 'long' });

  return (
    <div className="min-h-screen bg-canvas flex flex-col items-center justify-center p-6">
      <form onSubmit={submit} className={`w-full max-w-[360px] ${error ? 'animate-apple-shake' : ''}`}>
        <div className="mb-8 text-center">
          <div className="mx-auto w-fit mb-5"><Logo size={60}/></div>
          <div className="text-[30px] font-semibold tracking-tight text-ink">Easy2Sell</div>
          <div className="text-[14px] text-muted mt-1">Accedi al gestionale</div>
        </div>

        <div className="bg-surface rounded-2xl shadow-soft p-6 space-y-4">
          <div>
            <label className="block text-[11px] uppercase tracking-[0.06em] text-muted font-semibold mb-1.5">Utente</label>
            <input
              autoFocus value={username} onChange={(e) => { setUsername(e.target.value); if (error) setError(false); }}
              placeholder="negozio o utente" autoCapitalize="off" autoCorrect="off" spellCheck={false}
              className="w-full h-12 px-4 rounded-md border border-line bg-surface text-[15px] text-ink focus:border-strong transition-colors"
            />
          </div>
          <div>
            <label className="block text-[11px] uppercase tracking-[0.06em] text-muted font-semibold mb-1.5">Password</label>
            <input
              type="password" value={password} onChange={(e) => { setPassword(e.target.value); if (error) setError(false); }}
              placeholder="password"
              className="w-full h-12 px-4 rounded-md border border-line bg-surface text-[15px] text-ink focus:border-strong transition-colors"
            />
          </div>
          {error && <div className="text-[12.5px] text-[var(--danger-700)]">Credenziali non valide. Riprova.</div>}
          <button
            type="submit" disabled={busy || !username.trim() || !password}
            className="btn-bubble btn-bubble-blue w-full h-12 rounded-lg text-[var(--text-inverse)] font-semibold text-[15px] disabled:opacity-40 disabled:cursor-not-allowed transition-all duration-fast ease-standard"
          >
            {busy ? 'Accesso…' : 'Entra'}
          </button>
        </div>

        {/* Account demo: clic per compilare utente+password (password demo: easy2sell) */}
        <div className="mt-5 rounded-xl bg-surface shadow-sm p-3.5">
          <div className="text-[11px] uppercase tracking-[0.06em] text-muted font-semibold mb-2">Account demo · password <span className="num text-ink">easy2sell</span></div>
          <div className="grid grid-cols-2 gap-1.5">
            {[
              { u: 'admin', l: 'Admin' },
              { u: 'roberto', l: 'Area Manager' },
              { u: 'roma-spagna', l: 'Negozio' },
              { u: 'milano-montenap', l: 'Negozio' },
            ].map(d => (
              <button key={d.u} type="button"
                onClick={() => { setUsername(d.u); setPassword('easy2sell'); setError(false); }}
                className="focus-ring text-left px-3 py-2 rounded-lg bg-paper hover:bg-[var(--bg-hover)] transition-colors">
                <span className="block num text-[12.5px] font-medium text-ink truncate">{d.u}</span>
                <span className="block text-[11px] text-muted">{d.l}</span>
              </button>
            ))}
          </div>
          <div className="text-[10.5px] text-muted mt-2">In negozio, gli operatori usano il PIN <span className="num text-ink">1234</span>.</div>
        </div>

        <div className="mt-6 text-center text-[12px] text-muted capitalize">{today}</div>
      </form>
    </div>
  );
};

Object.assign(window, { LoginScreen, OPERATORS });
