// ──────────────────────────── Timbrature (turni dipendenti) ────────────────
// Tre sezioni: Timbra (entrata/uscita col PIN) · In turno ora · Storico turni.
// Lo storico è visibile a tutti ma SOLO del proprio negozio (scoping forzato lato
// server). Niente emoji (solo icone), niente alert browser (solo toast).
const { useState: useStateT, useEffect: useEffectT, useCallback: useCallbackT } = React;

const TimbraturePanel = ({ session, activeStoreId = STORE.id }) => {
  const storeId = (activeStoreId && activeStoreId !== 'all') ? activeStoreId : (STORE.id);
  const storeName = STORES.find(s => s.id === storeId)?.name || STORE.name;
  const ops = (typeof OPERATORS !== 'undefined' ? OPERATORS : (window.OPERATORS || [])).filter(o => o.active !== false);

  // ── Form timbra ──
  const [opId, setOpId] = useStateT('');
  const [tipo, setTipo] = useStateT('entrata');
  const [pin, setPin]   = useStateT('');
  const [note, setNote] = useStateT('');
  const [busy, setBusy] = useStateT(false);

  // ── Liste ──
  const [inTurno, setInTurno] = useStateT([]);
  const [storico, setStorico] = useStateT([]);

  const loadLists = useCallbackT(async () => {
    if (!window.__API__ || !window.__API__.get) return;
    const qs = '?storeId=' + encodeURIComponent(storeId);
    const a = await window.__API__.get('/api/timbrature/in-turno' + qs);
    if (a && a.ok) setInTurno(a.operatori || []);
    const b = await window.__API__.get('/api/timbrature/storico' + qs);
    if (b && b.ok) setStorico(b.turni || []);
  }, [storeId]);

  useEffectT(() => { loadLists(); }, [loadLists]);
  // refresh "in turno" ogni 60s
  useEffectT(() => {
    const t = setInterval(loadLists, 60000);
    return () => clearInterval(t);
  }, [loadLists]);

  // PIN digitabile da tastiera (la pagina ha un campo input, ma teniamo coerenza)
  const submit = async () => {
    if (!opId) { if (window.__toast) window.__toast('Scegli il dipendente', 'error'); return; }
    if (pin.length < 4) { if (window.__toast) window.__toast('Inserisci il PIN (min. 4 cifre)', 'error'); return; }
    if (busy) return;
    setBusy(true);
    try {
      await window.__API__.post('/api/timbrature/timbra', { operatorId: opId, pin, tipo, storeId, note: note.trim() || undefined });
      if (window.__toast) window.__toast((tipo === 'entrata' ? 'Entrata registrata' : 'Uscita registrata'), 'success');
      setPin(''); setNote('');
      await loadLists();
    } catch (e) {
      const err = e && e.response && e.response.error;
      const msg = err === 'pin_errato' ? 'PIN errato'
        : err === 'gia_in_turno' ? 'Sei già in turno'
        : err === 'non_in_turno' ? 'Non risulti in turno'
        : 'Timbratura non riuscita';
      if (window.__toast) window.__toast(msg, 'error');
      setPin('');
    } finally { setBusy(false); }
  };

  const fmtDur = (m) => m == null ? '—' : (m >= 60 ? `${Math.floor(m / 60)}h ${m % 60}m` : `${m}m`);
  const tone = (s) => s === 'OPEN' ? 'pos' : 'neutral';

  // ── Correzione turni (solo manager) ──
  const role = session?.op?.role;
  const canManage = ['Admin', 'Manager', 'Area Manager'].includes(role); // correzione: solo ruoli alti
  const [editId, setEditId] = useStateT(null);
  const [edIn, setEdIn] = useStateT('');
  const [edOut, setEdOut] = useStateT('');

  const startEdit = (t) => { setEditId(t.id); setEdIn(t.openedAt || ''); setEdOut(t.closedAt || ''); };
  const saveEdit = async (t) => {
    const body = { openedAt: edIn.trim(), closedAt: edOut.trim() }; // '' su uscita → riapre il turno
    try {
      const r = await fetch('/api/timbrature/' + encodeURIComponent(t.id), { method: 'PATCH', credentials: 'same-origin', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
      if (!r.ok) throw new Error('patch');
      if (window.__toast) window.__toast('Timbratura corretta', 'success');
      setEditId(null); await loadLists();
    } catch (e) { if (window.__toast) window.__toast('Correzione non riuscita · controlla il formato GG/MM/AAAA HH:MM', 'error'); }
  };
  const removeTurno = async (t) => {
    try {
      const r = await fetch('/api/timbrature/' + encodeURIComponent(t.id), { method: 'DELETE', credentials: 'same-origin' });
      if (!r.ok) throw new Error('del');
      if (window.__toast) window.__toast('Timbratura eliminata', 'info');
      setEditId(null); await loadLists();
    } catch (e) { if (window.__toast) window.__toast('Eliminazione non riuscita', 'error'); }
  };

  return (
    <>
      <Topbar eyebrow={`Timbrature · ${storeName}`} title="Timbrature" />
      <div className="px-7 py-6 grid grid-cols-1 xl:grid-cols-[minmax(0,380px)_minmax(0,1fr)] gap-6 items-start">

        {/* ── Colonna sinistra: TIMBRA + in turno ── */}
        <div className="space-y-6">
          <Card title="Timbra entrata / uscita">
            <div className="space-y-3.5">
              <label className="block">
                <span className="text-[12px] text-muted">Dipendente</span>
                <select className="w-full h-11 px-3 rounded-md border border-line bg-surface text-[14px] mt-1"
                  value={opId} onChange={e => setOpId(e.target.value)}>
                  <option value="">— scegli —</option>
                  {ops.map(o => <option key={o.id} value={o.id}>{o.name}</option>)}
                </select>
              </label>

              <div className="grid grid-cols-2 gap-2">
                <button onClick={() => setTipo('entrata')}
                  className={`focus-ring h-11 rounded-md text-[13.5px] font-medium transition-colors ${tipo === 'entrata' ? 'text-[var(--text-inverse)]' : 'text-ink bg-paper hover:bg-[var(--bg-hover)]'}`}
                  style={tipo === 'entrata' ? { background: 'var(--success-500)' } : null}>
                  Entrata
                </button>
                <button onClick={() => setTipo('uscita')}
                  className={`focus-ring h-11 rounded-md text-[13.5px] font-medium transition-colors ${tipo === 'uscita' ? 'text-[var(--text-inverse)] bg-ink' : 'text-ink bg-paper hover:bg-[var(--bg-hover)]'}`}>
                  Uscita
                </button>
              </div>

              <label className="block">
                <span className="text-[12px] text-muted">PIN</span>
                <input type="password" inputMode="numeric" maxLength={8} autoComplete="off"
                  className="w-full h-11 px-3 rounded-md border border-line bg-surface text-[15px] num mt-1 tracking-[0.3em]"
                  placeholder="••••" value={pin}
                  onChange={e => setPin(e.target.value.replace(/\D/g, ''))}
                  onKeyDown={e => { if (e.key === 'Enter') submit(); }}/>
              </label>

              <label className="block">
                <span className="text-[12px] text-muted">Nota (facoltativa)</span>
                <input className="w-full h-11 px-3 rounded-md border border-line bg-surface text-[14px] mt-1"
                  value={note} onChange={e => setNote(e.target.value)} placeholder="es. cambio turno"/>
              </label>

              <Btn variant="primary" size="lg" className="w-full" onClick={submit} disabled={busy}>
                {busy ? 'Registro…' : (tipo === 'entrata' ? 'Registra entrata' : 'Registra uscita')}
              </Btn>
            </div>
          </Card>

          <Card title={`In turno adesso · ${inTurno.length}`} padded={false}>
            {inTurno.length === 0
              ? <div className="px-5 py-7 flex flex-col items-center text-center gap-2 text-muted">
                  <span className="w-10 h-10 rounded-xl bg-paper flex items-center justify-center"><I.Clock size={18}/></span>
                  <span className="text-[13px]">Nessuno in turno adesso</span>
                </div>
              : inTurno.map(o => (
                <div key={o.id} className="flex items-center justify-between px-5 py-3 border-b border-line2 last:border-0">
                  <div className="flex items-center gap-3 min-w-0">
                    <span className="w-8 h-8 rounded-md bg-[var(--success-500)] text-[var(--text-inverse)] text-[11px] font-semibold flex items-center justify-center shrink-0">{o.initials}</span>
                    <span className="text-[13.5px] font-medium text-ink truncate">{o.name}</span>
                  </div>
                  <span className="num text-[12px] text-muted">dalle {(o.openedAt || '').slice(-5)}</span>
                </div>
              ))}
          </Card>
        </div>

        {/* ── Colonna destra: STORICO ── */}
        <Card title={`Storico turni · ${storeName}`} padded={false}
          actions={<button onClick={loadLists} className="focus-ring inline-flex items-center gap-1.5 text-[12.5px] text-muted hover:text-ink"><I.Refresh size={13}/> Aggiorna</button>}>
          {storico.length === 0 ? (
            <div className="py-20 flex flex-col items-center text-center gap-3 text-muted">
              <span className="w-14 h-14 rounded-2xl bg-paper flex items-center justify-center"><I.Clock size={26}/></span>
              <div>
                <div className="text-[14px] font-medium text-ink">Nessuna timbratura registrata</div>
                <div className="text-[12.5px] mt-0.5">Le entrate e uscite dei dipendenti compariranno qui.</div>
              </div>
            </div>
          ) : (
            <table className="w-full text-[13px]">
              <thead>
                <tr className="text-left text-[11px] uppercase tracking-[0.06em] text-muted hairline">
                  <th className="px-5 py-3 font-semibold">Dipendente</th>
                  <th className="px-3 py-3 font-semibold">Entrata</th>
                  <th className="px-3 py-3 font-semibold">Uscita</th>
                  <th className="px-3 py-3 font-semibold">Durata</th>
                  <th className="px-3 py-3 font-semibold text-right">Stato</th>
                  {canManage && <th className="px-5 py-3 font-semibold text-right">Azioni</th>}
                </tr>
              </thead>
              <tbody>
                {storico.map(t => editId === t.id ? (
                  <tr key={t.id} className="border-t border-line2 bg-[var(--bg-selected)]">
                    <td className="px-5 py-2.5 text-ink font-medium">{t.operatorName}</td>
                    <td className="px-3 py-2" colSpan={3}>
                      <div className="flex items-center gap-2 flex-wrap">
                        <input className="w-[150px] h-9 px-2 rounded-md border border-line bg-surface text-[12.5px] num" value={edIn} onChange={e => setEdIn(e.target.value)} placeholder="GG/MM/AAAA HH:MM"/>
                        <span className="text-muted text-[12px]">→</span>
                        <input className="w-[150px] h-9 px-2 rounded-md border border-line bg-surface text-[12.5px] num" value={edOut} onChange={e => setEdOut(e.target.value)} placeholder="vuoto = in turno"/>
                      </div>
                    </td>
                    <td className="px-5 py-2 text-right whitespace-nowrap" colSpan={canManage ? 2 : 1}>
                      <button onClick={() => saveEdit(t)} className="focus-ring text-[12.5px] font-medium text-[var(--accent-blue)] hover:underline mr-3">Salva</button>
                      <button onClick={() => setEditId(null)} className="focus-ring text-[12.5px] text-muted hover:text-ink">Annulla</button>
                    </td>
                  </tr>
                ) : (
                  <tr key={t.id} className="border-t border-line2 hover:bg-paper transition-colors">
                    <td className="px-5 py-3 text-ink font-medium">
                      <span className="inline-flex items-center gap-2.5">
                        <span className="w-7 h-7 rounded-md bg-line2 text-[var(--text-secondary)] text-[10.5px] font-semibold flex items-center justify-center shrink-0">{(t.operatorName || '').split(/\s+/).map(w => w[0]).slice(0, 2).join('').toUpperCase()}</span>
                        {t.operatorName}
                      </span>
                    </td>
                    <td className="px-3 py-3 num text-muted whitespace-nowrap">{t.openedAt}</td>
                    <td className="px-3 py-3 num text-muted whitespace-nowrap">{t.closedAt || '—'}</td>
                    <td className="px-3 py-3 num text-ink">{fmtDur(t.durataMin)}</td>
                    <td className="px-3 py-3 text-right"><Pill tone={tone(t.status)}>{t.status === 'OPEN' ? 'In turno' : 'Concluso'}</Pill></td>
                    {canManage && (
                      <td className="px-5 py-3 text-right whitespace-nowrap">
                        <button onClick={() => startEdit(t)} title="Correggi" className="focus-ring text-[12.5px] font-medium text-[var(--accent-blue)] hover:underline mr-3">Correggi</button>
                        <button onClick={() => removeTurno(t)} title="Elimina" className="focus-ring text-[12.5px] text-[var(--danger-700)] hover:underline">Elimina</button>
                      </td>
                    )}
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </Card>
      </div>
    </>
  );
};

Object.assign(window, { TimbraturePanel });
