/* global React */
const { useState: useStateConf } = React;

// =====================================================================
// ConflitosView — tela dedicada para resolver conflitos de horário
// =====================================================================
function ConflitosView({ blocos, hospitais, onSelecionarBloco, onAceitarGrupo, onReabrirGrupo, onIrPara }) {
  const HOSPS = hospitais || window.HOSPITAIS;
  const grupos = window.detectarTodosConflitos(blocos);

  const pendentes = grupos.filter(g => !g.every(b => b.aceitouConflito));
  const aceitos = grupos.filter(g => g.every(b => b.aceitouConflito));

  return (
    <div style={{display:'grid', gap: 'var(--s-5)', maxWidth: 980}}>
      <header>
        <div style={{display:'flex', alignItems:'baseline', gap: 12, flexWrap:'wrap'}}>
          <h2 className="h2" style={{fontSize: 28, margin: 0}}>Conflitos da agenda</h2>
          {pendentes.length > 0 && (
            <span style={{
              padding: '4px 12px',
              background: 'var(--err)', color: '#fff',
              borderRadius: 'var(--r-pill)',
              fontSize: 12, fontWeight: 700, letterSpacing: '0.04em',
              textTransform: 'uppercase',
            }}>{pendentes.length} pendente{pendentes.length === 1 ? '' : 's'}</span>
          )}
        </div>
        <p className="lede" style={{marginTop: 6, fontSize: 14, maxWidth: 640}}>
          Plantões em horários sobrepostos. Resolva cedendo, trocando, excluindo, ou marcando como aceito
          (caso a coordenação já tenha alinhado).
        </p>
      </header>

      {pendentes.length === 0 && aceitos.length === 0 && (
        <div style={{
          padding: 'var(--s-7)',
          background: 'var(--ok-bg)',
          border: '1px solid var(--ok)',
          borderRadius: 'var(--r-lg)',
          textAlign: 'center',
        }}>
          <div style={{
            fontFamily: 'var(--font-display)',
            fontSize: 26, fontWeight: 500,
            color: 'var(--ink)',
            marginBottom: 6,
          }}>Tudo certo, nada conflitando.</div>
          <div className="handwritten" style={{fontSize: 22, color: 'var(--ok)'}}>
            respira.
          </div>
        </div>
      )}

      {pendentes.map((grupo, idx) => (
        <ConflitoCard key={`p${idx}`} grupo={grupo} hospitais={HOSPS}
          onSelecionarBloco={onSelecionarBloco}
          onAceitar={() => onAceitarGrupo(grupo)}
          onIrPara={onIrPara}/>
      ))}

      {aceitos.length > 0 && (
        <details style={{marginTop: 'var(--s-4)'}}>
          <summary style={{
            cursor: 'pointer', fontSize: 13, fontWeight: 600, color: 'var(--ink-2)',
            padding: 'var(--s-3) var(--s-4)',
            background: 'var(--bg-alt)',
            borderRadius: 'var(--r-md)',
            border: '1px solid var(--line)',
            display: 'inline-block',
          }}>
            {aceitos.length} resolvido{aceitos.length === 1 ? '' : 's'} manualmente · ver
          </summary>
          <div style={{display:'grid', gap: 'var(--s-4)', marginTop: 'var(--s-3)'}}>
            {aceitos.map((grupo, idx) => (
              <ConflitoCard key={`a${idx}`} grupo={grupo} hospitais={HOSPS} resolvido
                onSelecionarBloco={onSelecionarBloco}
                onReabrir={() => onReabrirGrupo(grupo)}
                onIrPara={onIrPara}/>
            ))}
          </div>
        </details>
      )}
    </div>
  );
}

// =====================================================================
// ConflitoCard — um grupo de blocos sobrepostos
// =====================================================================
function ConflitoCard({ grupo, hospitais, onSelecionarBloco, onAceitar, onReabrir, onIrPara, resolvido }) {
  // Pega data do primeiro bloco pra cabeçalho
  const dataBase = grupo[0].data;
  const dia = window.diaSemanaBR(dataBase);

  return (
    <article style={{
      background: resolvido ? 'var(--bg-alt)' : 'var(--bg)',
      border: resolvido ? '1px dashed var(--line-2)' : '2px solid var(--err)',
      borderRadius: 'var(--r-lg)',
      padding: 'var(--s-5)',
      boxShadow: resolvido ? 'none' : 'var(--shadow-sm)',
      opacity: resolvido ? 0.75 : 1,
    }}>
      <header style={{
        display:'flex', justifyContent:'space-between', alignItems:'flex-start', flexWrap:'wrap', gap: 8,
        marginBottom: 'var(--s-4)',
      }}>
        <div>
          <div className="eyebrow" style={{
            color: resolvido ? 'var(--ok)' : 'var(--err)',
            fontSize: 11,
          }}>
            {resolvido ? '✓ Resolvido manualmente' : `⚠ Conflito · ${grupo.length} blocos sobrepõem`}
          </div>
          <h3 style={{
            fontFamily: 'var(--font-display)', fontSize: 22, fontWeight: 500,
            margin: 0, marginTop: 4, color: 'var(--ink)',
          }}>
            {window.DIAS_COMPLETO[dia]}, {window.fmtDataLongo(dataBase)}
          </h3>
        </div>
        <button onClick={() => onIrPara && onIrPara(dataBase)} className="btn btn--ghost"
          style={{fontSize: 12}}>
          Ver na grade →
        </button>
      </header>

      <div style={{
        display: 'grid',
        gridTemplateColumns: `repeat(${Math.min(grupo.length, 2)}, 1fr)`,
        gap: 'var(--s-3)',
      }}>
        {grupo.map(bloco => (
          <BlocoConflitoMini key={bloco.id} bloco={bloco} hospitais={hospitais}
            onClick={() => onSelecionarBloco(bloco)}/>
        ))}
      </div>

      <div style={{
        display: 'flex', gap: 'var(--s-2)', marginTop: 'var(--s-4)',
        paddingTop: 'var(--s-3)', borderTop: '1px solid var(--line)',
        flexWrap: 'wrap',
      }}>
        {!resolvido && (
          <>
            <p className="small" style={{flex:1, fontSize: 12, margin: 0, alignSelf: 'center'}}>
              <strong>Como resolver:</strong> clique em um dos blocos pra ceder/trocar/excluir.
              Ou marque como aceito se você já alinhou com a coordenação.
            </p>
            <button onClick={onAceitar} className="btn btn--ghost"
              style={{justifyContent:'center', borderColor: 'var(--ok)', color: 'var(--ok)'}}>
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12"/></svg>
              Aceitar (resolvido manualmente)
            </button>
          </>
        )}
        {resolvido && (
          <button onClick={onReabrir} className="btn btn--ghost"
            style={{justifyContent:'center', marginLeft: 'auto'}}>
            Reabrir conflito
          </button>
        )}
      </div>
    </article>
  );
}

function BlocoConflitoMini({ bloco, hospitais, onClick }) {
  const HOSPS = hospitais || window.HOSPITAIS;
  let titulo, sub, color, wash;
  if (bloco.tipo === 'plantao') {
    const h = window.getHospital(bloco.hospitalId, HOSPS);
    titulo = h.abrev;
    sub = h.nome;
    color = h.corDeep;
    wash = h.corWash;
  } else if (bloco.tipo === 'sono') {
    titulo = 'Sono protegido';
    sub = 'Janela de descanso planejada';
    color = '#5A6E50';
    wash = 'var(--colo-sage-50)';
  } else {
    titulo = 'Bloqueio';
    sub = bloco.motivo || 'Indisponível';
    color = 'var(--ink-2)';
    wash = 'var(--bg-alt)';
  }
  const fim = (bloco.horaInicio + bloco.duracao);

  return (
    <button onClick={onClick} style={{
      display: 'block', width: '100%', textAlign: 'left',
      padding: 'var(--s-4)',
      background: wash,
      border: `1px solid ${color}33`,
      borderLeft: `4px solid ${color}`,
      borderRadius: 'var(--r-md)',
      cursor: 'pointer',
      fontFamily: 'var(--font-body)',
      transition: 'transform var(--dur-1) var(--ease)',
    }}
    onMouseEnter={e => e.currentTarget.style.transform = 'translateY(-1px)'}
    onMouseLeave={e => e.currentTarget.style.transform = 'none'}>
      <div style={{
        fontFamily: 'var(--font-display)',
        fontSize: 24, fontWeight: 600, color,
        letterSpacing: '-0.01em', lineHeight: 1.1,
      }}>{titulo}</div>
      <div style={{fontSize: 13, color: 'var(--ink-2)', marginTop: 4}}>{sub}</div>
      <div style={{
        marginTop: 'var(--s-3)',
        display: 'flex', alignItems: 'center', gap: 8,
        fontSize: 13, color: 'var(--ink)',
      }}>
        <span style={{
          fontFamily: 'var(--font-display)', fontSize: 16, fontWeight: 600, color,
        }}>{window.fmtHora(bloco.horaInicio)}</span>
        <span style={{color: 'var(--ink-3)'}}>—</span>
        <span style={{fontFamily:'var(--font-display)', fontSize: 16, fontWeight: 600, color}}>
          {window.fmtHora(fim)}
        </span>
        <span style={{
          marginLeft: 'auto',
          padding: '2px 8px', borderRadius: 'var(--r-pill)',
          background: color, color: '#fff',
          fontSize: 11, fontWeight: 700,
        }}>{bloco.duracao}h</span>
      </div>
      {bloco.observacao && (
        <div className="small" style={{
          fontSize: 11, color: 'var(--ink-3)', marginTop: 6,
          fontStyle: 'italic',
        }}>{bloco.observacao}</div>
      )}
      <div style={{
        fontSize: 11, color: 'var(--colo-blue-tag)', fontWeight: 600,
        marginTop: 'var(--s-3)', textDecoration: 'underline',
      }}>
        Abrir e resolver →
      </div>
    </button>
  );
}

Object.assign(window, { ConflitosView });
