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

function Drawer({ bloco, hospitais, blocosTodos, recorrencias, onClose, onCeder, onTrocar, onEditar, onExcluir, onReverter, onExcluirOcorrencia, onExcluirSerie }) {
  const HOSPS = hospitais || window.HOSPITAIS;
  const [modo, setModo] = useStateDrawer('detalhes'); // 'detalhes' | 'ceder' | 'trocar' | 'editar'
  const [colega, setColega] = useStateDrawer({ nome: '', motivo: '' });

  // Defaults pra troca: próxima semana, mesmo hospital, 7h, 12h
  const proximaSemana = bloco ? window.addDias(bloco.data || window.HOJE_ISO, 7) : window.HOJE_ISO;
  const [novo, setNovo] = useStateDrawer({
    hospitalId: HOSPS[0]?.id || 1,
    data: proximaSemana,
    horaInicio: 7, duracao: 12,
  });

  // Estado do modo "editar" — espelha bloco atual
  const [edit, setEdit] = useStateDrawer(() => bloco ? {
    hospitalId: bloco.hospitalId || HOSPS[0]?.id || 1,
    data: bloco.data || window.HOJE_ISO,
    horaInicio: bloco.horaInicio || 7,
    duracao: bloco.duracao || 12,
  } : null);

  React.useEffect(() => {
    if (bloco) {
      setEdit({
        hospitalId: bloco.hospitalId || HOSPS[0]?.id || 1,
        data: bloco.data || window.HOJE_ISO,
        horaInicio: bloco.horaInicio || 7,
        duracao: bloco.duracao || 12,
      });
      setModo('detalhes');
    }
  }, [bloco?.id]); // eslint-disable-line

  if (!bloco) return null;

  let titulo, sub, family, color;
  const fim = bloco.horaInicio + bloco.duracao;

  if (bloco.tipo === 'plantao') {
    const h = window.getHospital(bloco.hospitalId, HOSPS);
    titulo = h.nome; sub = h.endereco; family = h.family; color = h.cor;
  } else if (bloco.tipo === 'deslocamento') {
    if (bloco.paraCasa) {
      const hOrig = bloco.hospitalOrigemId ? window.getHospital(bloco.hospitalOrigemId, HOSPS) : null;
      titulo = 'Voltando pra casa';
      sub = hOrig ? `Saindo de ${hOrig.nome}` : 'Retorno pra casa';
      family = 'olive'; color = '#C5BE99';
    } else if (bloco.deCasa) {
      const h = window.getHospital(bloco.hospitalDestinoId, HOSPS);
      titulo = 'Saindo de casa';
      sub = `Indo para ${h.nome}`;
      family = h.family; color = h.cor;
    } else {
      const h = window.getHospital(bloco.hospitalDestinoId, HOSPS);
      const hOrig = bloco.hospitalOrigemId ? window.getHospital(bloco.hospitalOrigemId, HOSPS) : null;
      titulo = 'Deslocamento entre hospitais';
      sub = hOrig ? `${hOrig.abrev} → ${h.nome}` : `Até ${h.nome}`;
      family = h.family; color = h.cor;
    }
  } else if (bloco.tipo === 'sono') {
    titulo = 'Sono protegido'; sub = 'Janela de descanso planejada'; family = 'sage'; color = '#A4D498';
  } else if (bloco.tipo === 'trocado') {
    titulo = 'Plantão trocado'; sub = `Com ${bloco.trocadoCom}`; family = 'lavender'; color = '#A299CB';
  } else {
    titulo = 'Plantão cedido'; sub = `Para ${bloco.cedidoPara}`; family = 'olive'; color = '#C5BE99';
  }

  const themeClass = `theme-${family}`;
  const fechar = () => { onClose(); setModo('detalhes'); setColega({nome:'', motivo:''}); };

  const dataLabel = bloco.data ? window.fmtDataLongo(bloco.data) : '';
  const dowBR = bloco.data ? window.diaSemanaBR(bloco.data) : 0;
  const novoH = HOSPS.find(h => h.id === novo.hospitalId) || HOSPS[0];
  const novoFim = novo.horaInicio + novo.duracao;

  return (
    <>
      <div onClick={fechar} style={{
        position: 'fixed', inset: 0, zIndex: 30,
        background: 'rgba(58, 46, 42, 0.18)',
        backdropFilter: 'blur(2px)',
      }}/>
      <aside className={`drawer-panel ${themeClass}`} role="dialog" aria-modal="true">
        <div style={{display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 'var(--s-5)'}}>
          {modo !== 'detalhes' ? (
            <button onClick={() => setModo('detalhes')} style={{
              border: 0, background: 'transparent', cursor: 'pointer',
              fontSize: 13, color: 'var(--ink-2)', fontFamily: 'var(--font-body)',
              display: 'flex', alignItems: 'center', gap: 4,
            }}>
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><polyline points="15 18 9 12 15 6"/></svg>
              Voltar
            </button>
          ) : <div/>}
          <button onClick={fechar} aria-label="Fechar" style={{
            width: 44, height: 44, border: 0, background: 'transparent',
            borderRadius: 999, cursor: 'pointer', color: 'var(--ink-2)',
            display: 'grid', placeItems: 'center',
          }}>
            <svg width="18" height="18" 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>
        </div>

        {modo === 'detalhes' && (
          <>
            <div style={{display:'flex', gap: 6, flexWrap:'wrap', marginBottom: 'var(--s-3)'}}>
              <span style={{
                display: 'inline-block', padding: '4px 12px',
                background: color, color: '#fff',
                fontSize: 11, fontWeight: 700, letterSpacing: '0.04em',
                borderRadius: 'var(--r-pill)', textTransform: 'uppercase',
              }}>{bloco.tipo}</span>
              {bloco.auto && (
                <span title="Gerado automaticamente. Some quando os plantões em volta mudam." style={{
                  display: 'inline-block', padding: '4px 12px',
                  background: 'var(--bg-alt)', color: 'var(--ink-2)',
                  fontSize: 11, fontWeight: 700, letterSpacing: '0.04em',
                  borderRadius: 'var(--r-pill)', textTransform: 'uppercase',
                  border: '1px dashed var(--line-2)',
                }}>auto</span>
              )}
            </div>
            <h2 className="h2" style={{fontSize: 32, lineHeight: 1.1}}>{titulo}</h2>
            <p className="small" style={{marginTop: 4}}>{sub}</p>

            {bloco.viaTroca && (
              <div style={{
                marginTop: 'var(--s-4)', padding: 'var(--s-3) var(--s-4)',
                background: 'var(--colo-lavender-50)',
                borderRadius: 'var(--r-md)',
                fontSize: 12, color: 'var(--ink-2)',
                display: 'flex', gap: 8, alignItems: 'center',
              }}>
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#A299CB" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="17 1 21 5 17 9"/><path d="M3 11V9a4 4 0 0 1 4-4h14"/><polyline points="7 23 3 19 7 15"/><path d="M21 13v2a4 4 0 0 1-4 4H3"/></svg>
                <span>Recebido em troca de {bloco.trocaCom}</span>
              </div>
            )}

            <div style={{marginTop: 'var(--s-6)', display: 'grid', gap: 'var(--s-5)'}}>
              <Row label="Quando" value={dataLabel}/>
              <Row label="Horário" value={`${window.fmtHora(bloco.horaInicio)} — ${window.fmtHora(fim)}`}/>
              <Row label="Duração" value={bloco.duracao < 1 ? `${Math.round(bloco.duracao*60)} minutos` : `${bloco.duracao} horas`}/>

              {/* Turno incerto: botão pra estender noitinha→noite ou confirmar como noitinha */}
              {bloco.turnoIncerto === 'noitinha-ou-noite' && bloco.tipo === 'plantao' && (
                <div style={{
                  padding: 'var(--s-3) var(--s-4)',
                  background: 'var(--warn-bg, #FBF1E1)',
                  border: '1px solid var(--warn, #B98A3F)',
                  borderRadius: 'var(--r-md)',
                  display:'grid', gap: 8,
                }}>
                  <div>
                    <div className="eyebrow" style={{fontSize: 10, color:'var(--warn, #B98A3F)'}}>⚠ Turno incerto</div>
                    <div style={{fontSize: 12, fontWeight: 600, marginTop: 2}}>
                      Esse plantão pode ser noitinha (5h) ou virar noite (12h) dependendo dos pacientes.
                    </div>
                  </div>
                  <div style={{display:'flex', gap: 8}}>
                    <button type="button" className="btn btn--ghost"
                      onClick={() => onEditar(bloco.id, { duracao: 5, turnoIncerto: undefined, turno: 'noitinha' })}
                      style={{flex: 1, justifyContent:'center', fontSize: 12, padding: '6px 10px'}}>
                      Noitinha (5h)
                    </button>
                    <button type="button" className="btn"
                      onClick={() => onEditar(bloco.id, { duracao: 12, turnoIncerto: undefined, turno: 'noite' })}
                      style={{flex: 1, justifyContent:'center', fontSize: 12, padding: '6px 10px',
                        background:'var(--warn, #B98A3F)', color:'var(--bg)', border:'none'}}>
                      Estender p/ noite (12h)
                    </button>
                  </div>
                </div>
              )}

              {(bloco.tipo === 'plantao' || bloco.viaTroca) && (() => {
                const hosp = window.getHospital(bloco.hospitalId, HOSPS);
                if (!hosp?.remuneracao?.ativo || !hosp.remuneracao?.valorHoraBase) return null;
                const r = window.calcRemuneracao(bloco, hosp);
                return (
                  <div>
                    <div className="eyebrow" style={{marginBottom: 6}}>Remuneração</div>
                    <div style={{
                      padding: 'var(--s-3) var(--s-4)',
                      background: hosp.corWash || 'var(--bg-alt)',
                      border: `1px solid ${hosp.cor || 'var(--line)'}55`,
                      borderRadius: 'var(--r-md)',
                      display:'grid', gap: 4, fontSize: 12,
                    }}>
                      {r.breakdown.map((b, i) => (
                        <div key={i} style={{display:'flex', justifyContent:'space-between', color:'var(--ink-2)'}}>
                          <span>
                            {b.horas}h {b.tipo === 'base' ? 'base' : `${b.tipo} (+${b.pctAdic}%)`}
                          </span>
                          <span style={{fontFamily:'ui-monospace, SFMono-Regular, monospace'}}>
                            {window.fmtBRL(b.valor)}
                          </span>
                        </div>
                      ))}
                      <div style={{
                        display:'flex', justifyContent:'space-between',
                        marginTop: 4, paddingTop: 6, borderTop: `1px solid ${hosp.cor || 'var(--line)'}33`,
                        fontWeight: 700, color: hosp.corDeep || 'var(--ink)',
                        fontSize: 14,
                      }}>
                        <span>Bruto</span>
                        <span style={{fontFamily:'ui-monospace, SFMono-Regular, monospace'}}>
                          {window.fmtBRL(r.bruto)}
                        </span>
                      </div>
                      {r.descontoPct > 0 && (
                        <>
                          <div style={{display:'flex', justifyContent:'space-between', fontSize: 11, color:'var(--err, #B25A4D)'}}>
                            <span>− desconto {r.descontoPct}%</span>
                            <span style={{fontFamily:'ui-monospace, monospace'}}>−{window.fmtBRL(r.descontoValor)}</span>
                          </div>
                          <div style={{
                            display:'flex', justifyContent:'space-between',
                            fontWeight: 700, color: 'var(--ok, #5A6E50)', fontSize: 14,
                          }}>
                            <span>Líquido</span>
                            <span style={{fontFamily:'ui-monospace, monospace'}}>{window.fmtBRL(r.liquido)}</span>
                          </div>
                        </>
                      )}
                    </div>
                  </div>
                );
              })()}
              {(bloco.tipo === 'plantao' || bloco.tipo === 'deslocamento') && (() => {
                const [, fimAtual] = window.intervaloMin(bloco);
                const candidatos = (blocosTodos || [])
                  .filter(b => b.id !== bloco.id && (b.tipo === 'plantao' || b.tipo === 'deslocamento'))
                  .map(b => ({ b, ini: window.intervaloMin(b)[0] }))
                  .filter(x => x.ini >= fimAtual)
                  .sort((a, b) => a.ini - b.ini);
                if (candidatos.length === 0) {
                  return <Row label="Próximo plantão" value="Nada à vista."/>;
                }
                const next = candidatos[0];
                const gapMin = next.ini - fimAtual;
                const gapH = gapMin / 60;
                const proxH = next.b.tipo === 'plantao'
                  ? window.getHospital(next.b.hospitalId, HOSPS)
                  : window.getHospital(next.b.hospitalDestinoId, HOSPS);
                const apertado = gapH < 6;
                const texto = gapH < 24
                  ? `Em ${gapH < 1 ? Math.round(gapMin) + ' min' : gapH.toFixed(gapH % 1 ? 1 : 0) + 'h'}`
                  : `Em ${Math.floor(gapH/24)} dia${Math.floor(gapH/24)>1?'s':''}`;
                return (
                  <div>
                    <div className="eyebrow" style={{marginBottom: 4}}>Próximo plantão</div>
                    <div style={{
                      fontSize: 16, fontWeight: 500,
                      color: apertado ? 'var(--err)' : 'var(--ink)',
                    }}>
                      {texto} · {proxH.abrev}
                    </div>
                    <div className="small" style={{marginTop: 2, fontSize: 11}}>
                      {window.fmtDataCurto(next.b.data)} {window.fmtHora(next.b.horaInicio)}
                      {apertado && ' · janela de descanso curta'}
                    </div>
                  </div>
                );
              })()}
              {bloco.motivo && <Row label="Motivo" value={bloco.motivo}/>}
              {bloco.tipo === 'trocado' && bloco.trocaInfo && (
                <Row label="Recebeu em troca" value={bloco.trocaInfo}/>
              )}
              {bloco.fromRecorrencia && (() => {
                const rec = (recorrencias || []).find(r => r.id === bloco.fromRecorrencia);
                return <Row label="Origem" value={`Série recorrente · ${window.descreverRecorrencia(rec)}`}/>;
              })()}
            </div>

            {bloco.tipo === 'plantao' && bloco.fromRecorrencia && (
              <div style={{marginTop: 'var(--s-7)', paddingTop: 'var(--s-5)', borderTop: '1px solid var(--line)', display: 'grid', gap: 'var(--s-2)'}}>
                <div style={{
                  padding: 'var(--s-3) var(--s-4)',
                  background: 'var(--colo-lavender-50)',
                  borderRadius: 'var(--r-md)',
                  fontSize: 12, color: 'var(--ink-2)', marginBottom: 4,
                }}>
                  <strong style={{color:'var(--ink)'}}>Plantão de uma série.</strong> Edição e troca operam só nesta ocorrência.
                </div>
                <div style={{display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 'var(--s-2)'}}>
                  <button className="btn btn--ghost" onClick={() => setModo('trocar')} style={{justifyContent:'center'}}>
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="17 1 21 5 17 9"/><path d="M3 11V9a4 4 0 0 1 4-4h14"/><polyline points="7 23 3 19 7 15"/><path d="M21 13v2a4 4 0 0 1-4 4H3"/></svg>
                    Trocar
                  </button>
                  <button className="btn btn--ghost" onClick={() => setModo('ceder')} style={{justifyContent:'center'}}>
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><polyline points="16 11 18 13 22 9"/></svg>
                    Ceder
                  </button>
                </div>
                <button onClick={() => { onExcluirOcorrencia && onExcluirOcorrencia(bloco.fromRecorrencia, bloco.data); fechar(); }} style={{
                  padding: '10px 14px', background:'transparent',
                  border: '1px solid var(--line)', color: 'var(--err)',
                  borderRadius: 'var(--r-pill)', cursor:'pointer',
                  fontFamily:'var(--font-body)', fontSize: 13, fontWeight: 600,
                  display:'flex', alignItems:'center', justifyContent:'center', gap: 6,
                }}>
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>
                  Excluir só este dia
                </button>
                <button onClick={() => { onExcluirSerie && onExcluirSerie(bloco.fromRecorrencia); fechar(); }} style={{
                  padding: '10px 14px', background:'transparent',
                  border: '1px dashed var(--err)', color: 'var(--err)',
                  borderRadius: 'var(--r-pill)', cursor:'pointer',
                  fontFamily:'var(--font-body)', fontSize: 13, fontWeight: 600,
                  display:'flex', alignItems:'center', justifyContent:'center', gap: 6,
                }}>
                  Excluir toda a série
                </button>
              </div>
            )}

            {bloco.tipo === 'plantao' && !bloco.fromRecorrencia && (
              <div style={{marginTop: 'var(--s-7)', paddingTop: 'var(--s-5)', borderTop: '1px solid var(--line)', display: 'grid', gap: 'var(--s-2)'}}>
                <div style={{display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 'var(--s-2)'}}>
                  <button className="btn btn--ghost" onClick={() => setModo('editar')} style={{justifyContent: 'center'}}>
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>
                    Editar
                  </button>
                  <button onClick={() => { onExcluir && onExcluir(bloco.id); fechar(); }} style={{
                    padding: '10px 14px', background: 'transparent',
                    border: '1px solid var(--line)', color: 'var(--err)',
                    borderRadius: 'var(--r-pill)', cursor: 'pointer',
                    fontFamily: 'var(--font-body)', fontSize: 13, fontWeight: 600,
                    display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
                  }}>
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>
                    Excluir
                  </button>
                </div>
                <button className="btn btn--ghost" onClick={() => setModo('trocar')} style={{width:'100%', justifyContent: 'center'}}>
                  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="17 1 21 5 17 9"/><path d="M3 11V9a4 4 0 0 1 4-4h14"/><polyline points="7 23 3 19 7 15"/><path d="M21 13v2a4 4 0 0 1-4 4H3"/></svg>
                  Trocar com colega
                </button>
                <button className="btn btn--ghost" onClick={() => setModo('ceder')} style={{width:'100%', justifyContent: 'center'}}>
                  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><polyline points="16 11 18 13 22 9"/></svg>
                  Ceder a colega
                </button>
              </div>
            )}

            {(bloco.tipo === 'cedido' || bloco.tipo === 'trocado') && (
              <div style={{marginTop: 'var(--s-7)', paddingTop: 'var(--s-5)', borderTop: '1px solid var(--line)'}}>
                <button className="btn btn--ghost" onClick={() => { onReverter && onReverter(bloco.id); fechar(); }}
                  style={{width:'100%', justifyContent: 'center'}}>
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="1 4 1 10 7 10"/><path d="M3.51 15a9 9 0 1 0 2.13-9.36L1 10"/></svg>
                  Reverter — voltei a assumir
                </button>
                <p className="small" style={{textAlign:'center', marginTop: 8, fontSize: 11}}>
                  O bloco volta como plantão na sua agenda.
                </p>
              </div>
            )}

            {(bloco.tipo === 'sono' || bloco.tipo === 'bloqueio' || bloco.tipo === 'deslocamento') && (
              <div style={{marginTop: 'var(--s-7)', paddingTop: 'var(--s-5)', borderTop: '1px solid var(--line)'}}>
                <button onClick={() => { onExcluir && onExcluir(bloco.id); fechar(); }} style={{
                  width: '100%', padding: '10px 14px', background: 'transparent',
                  border: '1px solid var(--line)', color: 'var(--err)',
                  borderRadius: 'var(--r-pill)', cursor: 'pointer',
                  fontFamily: 'var(--font-body)', fontSize: 13, fontWeight: 600,
                  display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
                }}>
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>
                  Excluir
                </button>
              </div>
            )}
          </>
        )}

        {modo === 'editar' && edit && (
          <>
            <h2 className="h2" style={{fontSize: 28, lineHeight: 1.1}}>Editar plantão</h2>
            <p className="small" style={{marginTop: 4, marginBottom: 'var(--s-5)'}}>
              Conflitos e cadeias são recalculados ao vivo.
            </p>

            <div style={{display: 'grid', gap: 'var(--s-4)'}}>
              <div>
                <label className="eyebrow" style={{display:'block', marginBottom: 6}}>Hospital</label>
                <select className="input" value={edit.hospitalId} onChange={e => setEdit({...edit, hospitalId: parseInt(e.target.value)})}>
                  {HOSPS.map(h => <option key={h.id} value={h.id}>{h.nome}</option>)}
                </select>
              </div>
              <div>
                <label className="eyebrow" style={{display:'block', marginBottom: 6}}>Data</label>
                <input className="input" type="date" value={edit.data}
                  onChange={e => setEdit({...edit, data: e.target.value})}/>
                <div className="small" style={{marginTop: 4, fontSize: 11}}>
                  {window.DIAS_COMPLETO[window.diaSemanaBR(edit.data)]}
                </div>
              </div>
              <div style={{display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 'var(--s-3)'}}>
                <div>
                  <label className="eyebrow" style={{display:'block', marginBottom: 6}}>Início (h)</label>
                  <input className="input" type="number" min="0" max="23" value={edit.horaInicio}
                    onChange={e => setEdit({...edit, horaInicio: parseInt(e.target.value) || 0})}/>
                </div>
                <div>
                  <label className="eyebrow" style={{display:'block', marginBottom: 6}}>Duração (h)</label>
                  <input className="input" type="number" min="1" max="36" value={edit.duracao}
                    onChange={e => setEdit({...edit, duracao: parseInt(e.target.value) || 1})}/>
                </div>
              </div>

              {/* Conflitos ao vivo */}
              {(() => {
                const projetado = { ...bloco, ...edit };
                const conflitos = window.detectarConflitos(projetado, blocosTodos || [], bloco.id);
                const cadeia = window.cadeiaSeAdicionar(projetado, (blocosTodos || []).filter(b => b.id !== bloco.id));
                if (conflitos.length === 0 && (!cadeia || cadeia.horas <= 24)) return null;
                return <window.ConflitosPanel conflitos={conflitos} cadeia={cadeia} hospitais={HOSPS}/>;
              })()}

              <div style={{display: 'flex', gap: 'var(--s-2)', marginTop: 'var(--s-3)'}}>
                <button className="btn btn--ghost" onClick={() => setModo('detalhes')} style={{flex:1, justifyContent:'center'}}>Cancelar</button>
                <button className="btn" onClick={() => { onEditar && onEditar(bloco.id, edit); fechar(); }}
                  style={{flex:1, justifyContent:'center', background:'var(--ink)', color:'var(--bg)'}}>
                  Salvar
                </button>
              </div>
            </div>
          </>
        )}

        {modo === 'ceder' && (
          <>
            <h2 className="h2" style={{fontSize: 28, lineHeight: 1.1}}>Ceder a colega</h2>
            <p className="small" style={{marginTop: 4, marginBottom: 'var(--s-5)'}}>
              Esse plantão sai da sua semana sem nada em troca. Você pode reverter depois.
            </p>
            <div style={{display: 'grid', gap: 'var(--s-4)'}}>
              <div>
                <label className="eyebrow" style={{display:'block', marginBottom: 6}}>Nome do colega</label>
                <input className="input" value={colega.nome} onChange={e => setColega({...colega, nome: e.target.value})} placeholder="Ex.: Dra. Mariana"/>
              </div>
              <div>
                <label className="eyebrow" style={{display:'block', marginBottom: 6}}>Motivo (opcional)</label>
                <textarea className="input" value={colega.motivo} onChange={e => setColega({...colega, motivo: e.target.value})} rows={3}
                  placeholder="Ex.: carga acumulada, evento familiar..." style={{resize:'vertical', fontFamily:'inherit'}}/>
              </div>
              <button className="btn" disabled={!colega.nome}
                onClick={() => { onCeder(bloco.id, colega); fechar(); }}
                style={{justifyContent:'center', opacity: colega.nome ? 1 : 0.5, marginTop: 8, background:'var(--ink)', color:'var(--bg)'}}>
                Confirmar cessão
              </button>
            </div>
          </>
        )}

        {modo === 'trocar' && (
          <>
            <h2 className="h2" style={{fontSize: 28, lineHeight: 1.1}}>Trocar com colega</h2>
            <p className="small" style={{marginTop: 4, marginBottom: 'var(--s-5)'}}>
              Você cede este plantão e recebe outro no lugar. Os dois entram na conta da sua semana.
            </p>

            {/* Resumo: o que sai vs. o que entra */}
            <div style={{
              display: 'grid', gridTemplateColumns: '1fr auto 1fr',
              gap: 'var(--s-2)', alignItems: 'stretch',
              marginBottom: 'var(--s-5)',
            }}>
              <div style={{
                padding: 'var(--s-3)',
                background: 'var(--colo-sand-50)',
                borderRadius: 'var(--r-md)',
                borderLeft: `3px solid ${color}`,
              }}>
                <div className="eyebrow" style={{fontSize: 10}}>Sai</div>
                <div style={{fontWeight: 700, fontSize: 13, marginTop: 4, lineHeight: 1.2}}>
                  {bloco.tipo === 'plantao' ? window.getHospital(bloco.hospitalId, HOSPS).abrev : titulo}
                </div>
                <div style={{fontSize: 11, color: 'var(--ink-2)', marginTop: 2}}>
                  {bloco.data && window.fmtDataCurto(bloco.data)} · {window.fmtHora(bloco.horaInicio)} · {bloco.duracao}h
                </div>
              </div>
              <div style={{display:'grid', placeItems:'center', color:'var(--ink-3)'}}>
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="17 1 21 5 17 9"/><path d="M3 11V9a4 4 0 0 1 4-4h14"/><polyline points="7 23 3 19 7 15"/><path d="M21 13v2a4 4 0 0 1-4 4H3"/></svg>
              </div>
              <div style={{
                padding: 'var(--s-3)',
                background: 'var(--colo-lavender-50)',
                borderRadius: 'var(--r-md)',
                borderLeft: `3px solid ${novoH.cor}`,
              }}>
                <div className="eyebrow" style={{fontSize: 10}}>Entra</div>
                <div style={{fontWeight: 700, fontSize: 13, marginTop: 4, lineHeight: 1.2}}>
                  {novoH.abrev}
                </div>
                <div style={{fontSize: 11, color: 'var(--ink-2)', marginTop: 2}}>
                  {window.fmtDataCurto(novo.data)} · {window.fmtHora(novo.horaInicio)} · {novo.duracao}h
                </div>
              </div>
            </div>

            <div style={{display: 'grid', gap: 'var(--s-4)'}}>
              <div>
                <label className="eyebrow" style={{display:'block', marginBottom: 6}}>Nome do colega</label>
                <input className="input" value={colega.nome} onChange={e => setColega({...colega, nome: e.target.value})} placeholder="Ex.: Dr. Felipe"/>
              </div>

              <div style={{
                padding: 'var(--s-4)', background: 'var(--bg-alt)',
                borderRadius: 'var(--r-md)', border: '1px solid var(--line)',
              }}>
                <div className="eyebrow" style={{marginBottom: 'var(--s-3)'}}>Plantão que vou assumir</div>
                <div style={{display:'grid', gap: 'var(--s-3)'}}>
                  <div>
                    <label className="eyebrow" style={{display:'block', marginBottom: 4, fontSize: 10}}>Hospital</label>
                    <select className="input" value={novo.hospitalId}
                      onChange={e => setNovo({...novo, hospitalId: parseInt(e.target.value)})}>
                      {HOSPS.map(h => <option key={h.id} value={h.id}>{h.nome}</option>)}
                    </select>
                  </div>
                  <div>
                    <label className="eyebrow" style={{display:'block', marginBottom: 4, fontSize: 10}}>Data</label>
                    <input className="input" type="date" value={novo.data}
                      onChange={e => setNovo({...novo, data: e.target.value})}/>
                    <div className="small" style={{marginTop: 4, fontSize: 11}}>
                      {window.DIAS_COMPLETO[window.diaSemanaBR(novo.data)]}
                      {' · '}
                      <button type="button" onClick={() => setNovo({...novo, data: window.addDias(window.HOJE_ISO, 7)})}
                        style={{border:0, background:'transparent', color:'var(--colo-blue-tag)', cursor:'pointer', textDecoration:'underline', fontSize: 11, padding:0}}>
                        próxima semana
                      </button>
                      {' · '}
                      <button type="button" onClick={() => {
                        const d = window.fromISO(window.HOJE_ISO);
                        setNovo({...novo, data: window.toISO(new Date(d.getFullYear(), d.getMonth()+1, d.getDate()))});
                      }}
                        style={{border:0, background:'transparent', color:'var(--colo-blue-tag)', cursor:'pointer', textDecoration:'underline', fontSize: 11, padding:0}}>
                        mês que vem
                      </button>
                    </div>
                  </div>
                  <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap: 'var(--s-3)'}}>
                    <div>
                      <label className="eyebrow" style={{display:'block', marginBottom: 4, fontSize: 10}}>Início (h)</label>
                      <input className="input" type="number" min="0" max="23" value={novo.horaInicio}
                        onChange={e => setNovo({...novo, horaInicio: parseInt(e.target.value) || 0})}/>
                    </div>
                    <div>
                      <label className="eyebrow" style={{display:'block', marginBottom: 4, fontSize: 10}}>Duração (h)</label>
                      <input className="input" type="number" min="1" max="36" value={novo.duracao}
                        onChange={e => setNovo({...novo, duracao: parseInt(e.target.value) || 1})}/>
                    </div>
                  </div>
                </div>
              </div>

              <div>
                <label className="eyebrow" style={{display:'block', marginBottom: 6}}>Motivo (opcional)</label>
                <textarea className="input" value={colega.motivo} onChange={e => setColega({...colega, motivo: e.target.value})} rows={2}
                  placeholder="Ex.: ele precisava do sábado, fechei terça à tarde."
                  style={{resize:'vertical', fontFamily:'inherit'}}/>
              </div>

              <button className="btn" disabled={!colega.nome}
                onClick={() => { onTrocar(bloco.id, colega, novo); fechar(); }}
                style={{justifyContent:'center', opacity: colega.nome ? 1 : 0.5, marginTop: 4, background:'var(--ink)', color:'var(--bg)'}}>
                Confirmar troca
              </button>
            </div>
          </>
        )}
      </aside>
    </>
  );
}

function Row({ label, value }) {
  return (
    <div>
      <div className="eyebrow" style={{marginBottom: 4}}>{label}</div>
      <div style={{fontSize: 16, fontWeight: 500, color: 'var(--ink)'}}>{value}</div>
    </div>
  );
}

Object.assign(window, { Drawer });
