/* global React */
const { useState: useStateToast, useEffect: useEffectToast } = React;

// =====================================================================
// TOAST com botão de desfazer — fica 5s, ou até clicar
// =====================================================================
function UndoToast({ mensagem, onUndo, onDismiss }) {
  const [progresso, setProgresso] = useStateToast(100);

  useEffectToast(() => {
    const total = 5000;
    const step = 50;
    let restante = total;
    const t = setInterval(() => {
      restante -= step;
      setProgresso(Math.max(0, (restante / total) * 100));
      if (restante <= 0) {
        clearInterval(t);
        onDismiss();
      }
    }, step);
    return () => clearInterval(t);
  }, []); // eslint-disable-line

  return (
    <div style={{
      position: 'fixed', bottom: 32, left: '50%',
      transform: 'translateX(-50%)',
      zIndex: 60,
      background: 'var(--ink)',
      color: 'var(--bg)',
      borderRadius: 'var(--r-pill)',
      padding: '12px 20px',
      display: 'flex', alignItems: 'center', gap: 'var(--s-4)',
      boxShadow: 'var(--shadow-lg)',
      fontFamily: 'var(--font-body)',
      fontSize: 14, fontWeight: 500,
      animation: 'toastIn var(--dur-2) var(--ease)',
      minWidth: 320,
    }}>
      <style>{`@keyframes toastIn { from { transform: translate(-50%, 20px); opacity: 0; } to { transform: translate(-50%, 0); opacity: 1; } }`}</style>
      <span style={{flex: 1}}>{mensagem}</span>
      <button onClick={onUndo} style={{
        border: '1px solid rgba(255,255,255,0.2)',
        background: 'transparent',
        color: '#FFB37C',
        padding: '6px 12px',
        borderRadius: 'var(--r-pill)',
        fontSize: 13, fontWeight: 700,
        cursor: 'pointer',
        fontFamily: 'inherit',
      }}>Desfazer</button>
      <button onClick={onDismiss} style={{
        border: 0, background: 'transparent',
        color: 'rgba(255,255,255,0.4)',
        cursor: 'pointer', display: 'grid', placeItems: 'center',
        width: 22, height: 22,
      }}>
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
      </button>
      <span style={{
        position: 'absolute', bottom: 0, left: 12, right: 12,
        height: 2,
        background: 'rgba(255,255,255,0.15)', borderRadius: 999,
        overflow: 'hidden',
      }}>
        <span style={{
          display: 'block', height: '100%',
          width: `${progresso}%`,
          background: '#FFB37C',
          transition: 'width 50ms linear',
        }}/>
      </span>
    </div>
  );
}

// =====================================================================
// CONFLITOS PANEL — aparece dentro do FAB e do drawer de edição
// =====================================================================
function ConflitosPanel({ conflitos, cadeia, hospitais }) {
  const HOSPS = hospitais || window.HOSPITAIS;
  if ((!conflitos || conflitos.length === 0) && !cadeia) return null;
  const cadeiaCritica = cadeia && cadeia.horas > 24;

  return (
    <div style={{
      padding: 'var(--s-3) var(--s-4)',
      background: cadeiaCritica ? 'var(--err-bg)' : 'var(--warn-bg)',
      borderRadius: 'var(--r-md)',
      border: `1px solid ${cadeiaCritica ? 'var(--err)' : 'var(--warn)'}33`,
      display: 'flex', gap: 'var(--s-3)', alignItems: 'flex-start',
    }}>
      <div style={{
        flexShrink: 0, color: cadeiaCritica ? 'var(--err)' : 'var(--warn)',
        marginTop: 2,
      }}>
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0Z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>
      </div>
      <div style={{flex: 1, minWidth: 0}}>
        {conflitos && conflitos.length > 0 && (
          <div>
            <div style={{fontWeight: 700, fontSize: 13, color: 'var(--ink)'}}>
              Sobrepõe {conflitos.length} {conflitos.length === 1 ? 'plantão existente' : 'plantões existentes'}
            </div>
            <ul style={{margin: '4px 0 0', padding: '0 0 0 16px', fontSize: 12, color: 'var(--ink-2)'}}>
              {conflitos.slice(0, 3).map(c => {
                const h = c.tipo === 'plantao' ? window.getHospital(c.hospitalId, HOSPS) :
                          c.tipo === 'deslocamento' ? window.getHospital(c.hospitalDestinoId, HOSPS) : null;
                return (
                  <li key={c.id}>
                    {h ? h.abrev : (c.tipo === 'sono' ? 'Sono protegido' : c.tipo)} ·{' '}
                    {window.fmtDataCurto(c.data)} {window.fmtHora(c.horaInicio)} ({c.duracao}h)
                  </li>
                );
              })}
            </ul>
          </div>
        )}
        {cadeia && (
          <div style={{marginTop: conflitos?.length ? 8 : 0}}>
            <div style={{fontWeight: 700, fontSize: 13, color: 'var(--ink)'}}>
              {cadeiaCritica ? `Cria cadeia contínua de ${Math.round(cadeia.horas)}h` : 'Estende cadeia contínua'}
            </div>
            <div style={{fontSize: 12, color: 'var(--ink-2)', marginTop: 2}}>
              {cadeiaCritica
                ? 'Acima de 24h sem pausa. Considere proteger um descanso.'
                : `${Math.round(cadeia.horas)}h trabalhando sem intervalo significativo.`}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { UndoToast, ConflitosPanel });
