// ═══ MovimentacaoModal — modal ÚNICO de registro de embarque/desembarque ═══
// Padrão "crew change": as pessoas selecionadas aparecem agrupadas em
// Entrando / Saindo; cada grupo tem sua data/hora (default: agora) e seu
// porto (default: porto atual do Portaló). Visitantes que entram escolhem o
// crachá aqui mesmo. Nenhum registro acontece sem o Confirmar.
// Usado por: perfil da pessoa, ações em massa (Pessoas), listas do Portaló
// e fila de embarque. A gangway por QR/câmera segue com fluxo próprio de 1 toque.
//
// pessoas: [{ id, nome, genesis_id, role, empresa, funcao, foto_url, initials, tipo }]
// tipo: 'embarque' | 'desembarque' — quem chama deriva do status atual.
const MovimentacaoModal = ({ pessoas, onClose, onDone }) => {
  const toast = useToast();
  const tk = () => localStorage.getItem('genesis_token');

  const entrando = pessoas.filter(p => p.tipo === 'embarque');
  const saindo   = pessoas.filter(p => p.tipo === 'desembarque');
  const guestsEntrando = entrando.filter(p => p.role === 'guest');

  // datetime-local quer "AAAA-MM-DDTHH:mm" no fuso local
  const agoraLocal = () => { const d = new Date(); d.setMinutes(d.getMinutes() - d.getTimezoneOffset()); return d.toISOString().slice(0, 16); };
  const [quando, setQuando] = useState({ embarque: agoraLocal(), desembarque: agoraLocal() });
  const [portos, setPortos] = useState([]);
  const [porto, setPorto] = useState({ embarque: '', desembarque: '' });
  const [slotsLivres, setSlotsLivres] = useState([]);
  const [slotSel, setSlotSel] = useState({}); // userId -> slot (só visitantes entrando)
  const [salvando, setSalvando] = useState(false);

  useEffect(() => {
    fetch('/api/ports', { headers: { Authorization: `Bearer ${tk()}` } })
      .then(r => r.ok ? r.json() : { ports: [], current: null })
      .then(d => { setPortos(d.ports || []); if (d.current) setPorto({ embarque: d.current, desembarque: d.current }); })
      .catch(() => {});
  }, []);

  useEffect(() => {
    if (!guestsEntrando.length) return;
    fetch('/api/boarding/slots-livres', { headers: { Authorization: `Bearer ${tk()}` } })
      .then(r => r.ok ? r.json() : [])
      .then(livres => {
        setSlotsLivres(Array.isArray(livres) ? livres : []);
        // Pré-atribui crachás livres em sequência, um por visitante
        const auto = {};
        guestsEntrando.forEach((g, i) => { if (livres[i] != null) auto[g.id] = livres[i]; });
        setSlotSel(auto);
      })
      .catch(() => {});
  }, []);

  const semCracha = guestsEntrando.filter(g => !slotSel[g.id]);

  const confirmar = async () => {
    if (salvando) return;
    setSalvando(true);
    const items = pessoas.map(p => ({
      user_id: p.id,
      tipo: p.tipo,
      visitor_slot: (p.role === 'guest' && p.tipo === 'embarque') ? slotSel[p.id] : undefined,
      porto: porto[p.tipo] || undefined,
      data_hora: quando[p.tipo] ? new Date(quando[p.tipo]).toISOString() : undefined,
    }));
    try {
      const res = await fetch('/api/boarding/movimentar', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${tk()}` },
        body: JSON.stringify({ items }),
      });
      const d = await res.json();
      if (res.ok && !(d.falhas && d.falhas.length)) {
        const emb = d.ok.filter(x => x.tipo === 'embarque').length;
        const des = d.ok.filter(x => x.tipo === 'desembarque').length;
        const partes = [];
        if (emb) partes.push(`${emb} embarque${emb !== 1 ? 's' : ''}`);
        if (des) partes.push(`${des} saída${des !== 1 ? 's' : ''}`);
        toast.push({ icon: 'check', title: 'Movimentação registrada', body: partes.join(' · ') });
        onDone && onDone(d);
        onClose();
      } else if (res.ok) {
        toast.push({ icon: 'x', title: 'Parcialmente registrado', body: `${d.ok.length} ok · ${d.falhas.length} falharam: ${d.falhas.map(f => f.erro).join(' · ')}` });
        onDone && onDone(d);
        onClose();
      } else {
        toast.push({ icon: 'x', title: 'Erro ao registrar', body: d.error });
        setSalvando(false);
      }
    } catch (e) {
      toast.push({ icon: 'x', title: 'Erro de conexão' });
      setSalvando(false);
    }
  };

  const corAcao = (entrando.length && saindo.length) ? 'var(--accent)' : entrando.length ? 'var(--leaf)' : 'var(--accent-2)';

  const Grupo = ({ tipo, titulo, cor, bg, lista }) => (
    <div style={{ marginBottom: 18 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
        <span style={{ width: 10, height: 10, borderRadius: 'var(--r-circle)', background: cor, flexShrink: 0 }} />
        <span style={{ fontFamily: 'var(--fm)', fontSize: 'var(--text-xs)', fontWeight: 600, letterSpacing: '.08em', textTransform: 'uppercase', color: cor }}>{titulo}</span>
        <span style={{ fontFamily: 'var(--fm)', fontSize: 'var(--text-xs)', color: 'var(--muted)', background: bg, padding: '2px 8px', borderRadius: 'var(--r-sm)' }}>{lista.length}</span>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginBottom: 10 }}>
        <div>
          <label className="label">Data e hora</label>
          <input type="datetime-local" className="input" style={{ width: '100%', boxSizing: 'border-box' }}
            value={quando[tipo]} max={agoraLocal()}
            onChange={e => setQuando(q => ({ ...q, [tipo]: e.target.value }))} />
        </div>
        <div>
          <label className="label">Porto</label>
          <select className="input" style={{ width: '100%', boxSizing: 'border-box' }}
            value={porto[tipo]} onChange={e => setPorto(p => ({ ...p, [tipo]: e.target.value }))}>
            <option value="">— sem porto —</option>
            {portos.map(pp => <option key={pp.id} value={pp.nome}>{pp.nome}</option>)}
          </select>
        </div>
      </div>
      <div style={{ display: 'grid', gap: 6 }}>
        {lista.map(p => (
          <div key={p.id} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 10px', background: 'var(--surface)', border: '1px solid var(--line-soft)', borderRadius: 'var(--r-md)' }}>
            <Avatar user={p} size="sm" />
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 'var(--text-base)', fontWeight: 500, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{p.nome}</div>
              <div style={{ fontSize: 'var(--text-xs)', color: 'var(--muted)', fontFamily: 'var(--fm)', marginTop: 1 }}>{[p.empresa, p.funcao].filter(Boolean).join(' · ') || p.genesis_id}</div>
            </div>
            {p.role === 'guest' && tipo === 'embarque' && (
              <select className="input" style={{ width: 110, padding: '6px 8px', fontFamily: 'var(--fm)' }}
                value={slotSel[p.id] || ''}
                onChange={e => setSlotSel(s => ({ ...s, [p.id]: e.target.value ? parseInt(e.target.value) : null }))}>
                <option value="">crachá…</option>
                {slotsLivres
                  .filter(s => s === slotSel[p.id] || !Object.values(slotSel).includes(s))
                  .map(s => <option key={s} value={s}>#{String(s).padStart(2, '0')}</option>)}
              </select>
            )}
            {p.role === 'guest' && tipo === 'desembarque' && (
              <span style={{ fontSize: 'var(--text-xs)', color: 'var(--muted)', fontFamily: 'var(--fm)', whiteSpace: 'nowrap' }}>crachá liberado</span>
            )}
          </div>
        ))}
      </div>
    </div>
  );

  return (
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'var(--overlay)', backdropFilter: 'blur(8px)', zIndex: 'var(--z-toast)', display: 'grid', placeItems: 'center', padding: 20 }}>
      <div onClick={e => e.stopPropagation()} style={{
        width: '100%', maxWidth: 560, maxHeight: '90vh', overflowY: 'auto', background: 'var(--cream)',
        borderRadius: 'var(--r-xl)', padding: '28px 30px',
        boxShadow: '0 32px 80px -20px var(--line-strong)', animation: 'slideIn .25s both'
      }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 16 }}>
          <div>
            <div className="t-eyebrow">movimentação de bordo</div>
            <div style={{ fontFamily: 'var(--fs)', fontSize: 'var(--text-2xl)', letterSpacing: '-0.4px', marginTop: 4 }}>
              Registrar movimenta<em style={{ fontStyle: 'italic', color: 'var(--accent)' }}>ção.</em>
            </div>
          </div>
          <button className="btn ghost btn-sm" onClick={onClose} disabled={salvando}><Icon n="x" size={14} /></button>
        </div>

        {entrando.length > 0 && (
          <Grupo tipo="embarque" titulo="Entrando · sign on" cor="var(--leaf)" bg="var(--leaf-soft)" lista={entrando} />
        )}
        {saindo.length > 0 && (
          <Grupo tipo="desembarque" titulo="Saindo · sign off" cor="var(--accent-2)" bg="var(--accent-soft)" lista={saindo} />
        )}

        {semCracha.length > 0 && (
          <div style={{ padding: '10px 14px', background: 'var(--coral-soft)', borderRadius: 'var(--r-md)', fontSize: 'var(--text-sm)', color: 'var(--accent-2)', marginBottom: 12 }}>
            ⚠️ {semCracha.length === 1 ? 'Um visitante está' : `${semCracha.length} visitantes estão`} sem crachá selecionado.
          </div>
        )}

        <div style={{ display: 'flex', gap: 10, marginTop: 4 }}>
          <button className="btn" style={{ flex: 1 }} onClick={onClose} disabled={salvando}>Cancelar</button>
          <button onClick={confirmar} disabled={salvando || semCracha.length > 0}
            style={{
              flex: 2, padding: '13px', borderRadius: 'var(--r-md)', border: 'none',
              cursor: (salvando || semCracha.length > 0) ? 'default' : 'pointer',
              background: corAcao, color: 'white', fontFamily: 'var(--fs)', fontStyle: 'italic',
              fontSize: 'var(--text-xl)', fontWeight: 600, opacity: (salvando || semCracha.length > 0) ? 0.4 : 1
            }}>
            {salvando ? 'registrando…' : `Confirmar · ${pessoas.length} pessoa${pessoas.length !== 1 ? 's' : ''}`}
          </button>
        </div>
      </div>
    </div>
  );
};
