// ModalConsultaInfo — info rápida + botão Iniciar Consulta
// TelaProntuario   — tela cheia com abas Prontuário / Histórico

const { useState: prState } = React;
const MAX_CHARS = 5000;

/* ── Histórico mock ── */
const MOCK_HISTORICO = {
  'Ana Silva': [
    { id:'h1', data:'02/05/2026', hora:'09:00', status:'finalizado',
      conteudo:'Sessão focada em técnicas de regulação emocional. Paciente relatou melhora nos episódios de ansiedade. Exercícios de respiração aplicados com sucesso. Foram trabalhados exercícios de respiração diafragmática e técnicas de aterramento cognitivo.',
      anexos:['relatorio-ana-02mai.pdf'],
      terapeuta:'Dra. Ana Silva', unidade:'Unidade Centro', sala:'Sala 201' },
    { id:'h2', data:'09/05/2026', hora:'09:00', status:'finalizado',
      conteudo:'Continuidade do trabalho com TCC. Paciente apresentou boa adesão às tarefas entre sessões. Identificação de pensamentos automáticos negativos. Registro de pensamentos realizado em conjunto. Paciente demonstrou insight sobre padrões de ruminação.',
      anexos:[],
      terapeuta:'Dra. Ana Silva', unidade:'Unidade Centro', sala:'Sala 201' },
    { id:'h3', data:'16/05/2026', hora:'09:00', status:'finalizado',
      conteudo:'Revisão das tarefas de casa. Paciente trouxe situações da semana relacionadas à ansiedade no trabalho. Técnica de reestruturação cognitiva aplicada. Discussão sobre crenças centrais disfuncionais.',
      anexos:['avaliacao-16mai.docx'],
      terapeuta:'Dra. Ana Silva', unidade:'Unidade Centro', sala:'Sala 201' },
  ],
  'Jorge Ribeiro': [
    { id:'h4', data:'25/04/2026', hora:'10:00', status:'finalizado',
      conteudo:'Primeira sessão de avaliação. Queixas de ansiedade social e dificuldades nos relacionamentos interpessoais. Contrato terapêutico estabelecido. Aplicação de escala de ansiedade.',
      anexos:['contrato-jorge.pdf'],
      terapeuta:'Dr. Carlos Mendes', unidade:'Unidade Centro', sala:'Sala 202' },
  ],
  'Amanda Viana': [],
  'Carmem Lúcia': [
    { id:'h5', data:'15/05/2026', hora:'11:00', status:'finalizado',
      conteudo:'Sessão de acompanhamento. Trabalho com luto recente. Paciente demonstrou abertura para o processo terapêutico. Exploração de memórias afetivas e elaboração do processo de perda.',
      anexos:[],
      terapeuta:'Dra. Ana Silva', unidade:'Unidade Jardins', sala:'Sala 201' },
  ],
};

/* ─────────────────────────────────────────────
   Modal rápido: info + botão Iniciar Consulta
───────────────────────────────────────────── */
function ModalConsultaInfo({ appt, perfil='admin', onClose, onIniciar, onCancelar, onConfirmar, onReagendar }) {
  const c = APPT_COLORS[appt.status] || APPT_COLORS.aguardando;
  const dayInfo = WEEK_DAYS.find(d => d.key === appt.day) || {};
  const isAdmin      = perfil === 'admin';
  const isSecretaria = perfil === 'secretaria';
  const isTerapeuta  = perfil === 'terapeuta';
  const podeCancelar  = (isAdmin || isSecretaria) && ['confirmado','aguardando','reagendado'].includes(appt.status);
  const podeConfirmar = (isAdmin || isSecretaria) && ['aguardando','reagendado'].includes(appt.status);
  const podeReagendar = (isAdmin || isSecretaria) && ['confirmado','aguardando','falta','reagendado'].includes(appt.status);
  const podeIniciar   = isAdmin && appt.status === 'confirmado';

  const Row = ({ label, value }) => (
    <div style={{ display:'flex', justifyContent:'space-between', padding:'8px 0', borderBottom:'1px solid #f3f4f6' }}>
      <span style={{ fontSize:13, color:'#6b7280' }}>{label}</span>
      <span style={{ fontSize:13, fontWeight:500, color:'#111' }}>{value}</span>
    </div>
  );
  return (
    <Modal title="Informações da consulta" onClose={onClose} width={420}>
      <div style={{ marginBottom:16 }}>
        <Row label="Paciente"  value={appt.patient} />
        <Row label="Terapeuta" value={appt.terapeuta} />
        <Row label="Data"      value={`${dayInfo.label}, ${dayInfo.num}/06/2026`} />
        <Row label="Horário"   value={appt.time} />
        <Row label="Unidade"   value={appt.unidade} />
        <Row label="Sala"      value={appt.sala} />
        <div style={{ display:'flex', justifyContent:'space-between', padding:'10px 0', alignItems:'center' }}>
          <span style={{ fontSize:13, color:'#6b7280' }}>Status</span>
          <span style={{ fontSize:12, fontWeight:700, color:c.text, background:c.bg, border:`1px solid ${c.border}`, padding:'3px 10px', borderRadius:12 }}>{c.label}</span>
        </div>
      </div>

      {/* Terapeuta: só iniciar */}
      {isTerapeuta && (
        <button onClick={onIniciar}
          style={{ width:'100%', padding:'11px', background:C.primary, color:'white', border:'none', borderRadius:7, fontSize:14, fontWeight:700, cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'center', gap:8 }}>
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><polygon points="5 3 19 12 5 21 5 3"/></svg>
          Iniciar consulta
        </button>
      )}

      {/* Admin / Secretaria: botões de edição */}
      {(isAdmin || isSecretaria) && (
        <div style={{ display:'flex', gap:8, flexWrap:'wrap' }}>
          {podeCancelar && (
            <button onClick={onCancelar}
              style={{ flex:1, padding:'9px', background:'#fee2e2', color:'#991b1b', border:'1px solid #fca5a5', borderRadius:6, fontSize:13, fontWeight:600, cursor:'pointer' }}>
              Cancelar / Falta
            </button>
          )}
          {podeConfirmar && (
            <button onClick={onConfirmar}
              style={{ flex:1, padding:'9px', background:'#dcfce7', color:'#15803d', border:'1px solid #86efac', borderRadius:6, fontSize:13, fontWeight:600, cursor:'pointer' }}>
              ✓ Confirmar
            </button>
          )}
          {podeReagendar && (
            <button onClick={onReagendar}
              style={{ flex:1, padding:'9px', background:'#fef9c3', color:'#854d0e', border:'1px solid #fde047', borderRadius:6, fontSize:13, fontWeight:600, cursor:'pointer' }}>
              Reagendar
            </button>
          )}
          {podeIniciar && (
            <button onClick={onIniciar}
              style={{ width:'100%', marginTop:4, padding:'10px', background:C.primary, color:'white', border:'none', borderRadius:6, fontSize:13, fontWeight:700, cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'center', gap:8 }}>
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><polygon points="5 3 19 12 5 21 5 3"/></svg>
              Iniciar consulta
            </button>
          )}
        </div>
      )}
    </Modal>
  );
}

/* ─────────────────────────────────────────────
   Modal de detalhe de um prontuário histórico
───────────────────────────────────────────── */
function ModalHistoricoDetalhe({ item, paciente, onClose }) {
  return (
    <Modal title={`Prontuário — ${item.data} às ${item.hora}`} onClose={onClose} width={540}>
      <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
        {/* Info da sessão */}
        <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:10, padding:'12px 14px', background:'#f8fafc', borderRadius:8 }}>
          {[
            { label:'Paciente',  value: paciente },
            { label:'Terapeuta', value: item.terapeuta },
            { label:'Data',      value: item.data },
            { label:'Horário',   value: item.hora },
            { label:'Unidade',   value: item.unidade },
            { label:'Sala',      value: item.sala },
          ].map(f => (
            <div key={f.label}>
              <div style={{ fontSize:11, fontWeight:600, color:'#9ca3af', textTransform:'uppercase', letterSpacing:'.05em', marginBottom:2 }}>{f.label}</div>
              <div style={{ fontSize:13, color:'#111', fontWeight:500 }}>{f.value || '—'}</div>
            </div>
          ))}
        </div>

        {/* Status badge */}
        <div style={{ display:'flex', alignItems:'center', gap:8 }}>
          <span style={{ fontSize:13, color:'#6b7280' }}>Status:</span>
          <span style={{ fontSize:12, fontWeight:700, color:'#15803d', background:'#dcfce7', padding:'2px 10px', borderRadius:10 }}>Finalizado</span>
        </div>

        {/* Conteúdo */}
        <div>
          <div style={{ fontSize:12, fontWeight:700, color:'#374151', textTransform:'uppercase', letterSpacing:'.05em', marginBottom:8 }}>Conteúdo da sessão</div>
          <div style={{ padding:'14px', background:'#fafafa', border:'1px solid #e5e7eb', borderRadius:8, fontSize:13, color:'#374151', lineHeight:1.75, whiteSpace:'pre-wrap' }}>
            {item.conteudo}
          </div>
        </div>

        {/* Anexos */}
        <div>
          <div style={{ fontSize:12, fontWeight:700, color:'#374151', textTransform:'uppercase', letterSpacing:'.05em', marginBottom:8 }}>Anexos</div>
          {item.anexos && item.anexos.length > 0 ? (
            <div style={{ display:'flex', flexDirection:'column', gap:6 }}>
              {item.anexos.map((a, i) => (
                <div key={i} style={{ display:'flex', alignItems:'center', gap:10, padding:'10px 14px', background:'white', border:'1px solid #e5e7eb', borderRadius:7 }}>
                  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke={C.primary} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                    <path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8z"/><polyline points="14 2 14 8 20 8"/>
                  </svg>
                  <span style={{ flex:1, fontSize:13, color:'#374151' }}>{a}</span>
                  <span style={{ fontSize:11, color:'#9ca3af', background:'#f3f4f6', padding:'2px 8px', borderRadius:10 }}>
                    {a.endsWith('.pdf') ? 'PDF' : a.endsWith('.docx') ? 'DOCX' : 'DOC'}
                  </span>
                </div>
              ))}
            </div>
          ) : (
            <div style={{ padding:'12px 14px', background:'#f9fafb', border:'1px dashed #d1d5db', borderRadius:7, fontSize:13, color:'#9ca3af' }}>
              Nenhum anexo nesta sessão.
            </div>
          )}
        </div>

        <button onClick={onClose} style={{ padding:'9px', background:'white', border:'1px solid #d1d5db', borderRadius:6, fontSize:13, cursor:'pointer', color:'#374151' }}>Fechar</button>
      </div>
    </Modal>
  );
}

/* ─────────────────────────────────────────────
   Tela cheia: abas Prontuário | Histórico
───────────────────────────────────────────── */
function TelaProntuario({ appt, existente, prontuarios, onSave, onVoltar }) {
  const historico = MOCK_HISTORICO[appt.patient] || [];
  const dayInfo   = WEEK_DAYS.find(d => d.key === appt.day) || {};

  const [aba,          setAba]          = prState('prontuario');
  const [tipoInput,    setTipoInput]    = prState(existente?.tipoInput || 'manual');
  const [conteudo,     setConteudo]     = prState(existente?.conteudo  || '');
  const [status,       setStatus]       = prState(existente?.status    || 'pendente');
  const [anexoNome,    setAnexoNome]    = prState(existente?.anexoNome || '');
  const [erro,         setErro]         = prState('');
  const [histDetalhe,  setHistDetalhe]  = prState(null); // item do histórico em visualização

  const FORMATOS_VALIDOS = ['application/pdf','application/vnd.openxmlformats-officedocument.wordprocessingml.document','application/msword'];

  const handleAnexo = e => {
    const f = e.target.files[0]; if (!f) return;
    if (!FORMATOS_VALIDOS.includes(f.type)) { setErro('Formato inválido. Envie .pdf, .doc ou .docx.'); return; }
    setErro(''); setAnexoNome(f.name);
  };

  const handleSalvar = () => {
    if (tipoInput === 'manual' && !conteudo.trim()) { setErro('O conteúdo do prontuário é obrigatório.'); return; }
    if (tipoInput === 'upload' && !anexoNome)        { setErro('Faça o upload do arquivo do prontuário.'); return; }
    onSave({ apptId: appt.id, paciente: appt.patient, terapeuta: appt.terapeuta, data: dayInfo.label, hora: appt.time, conteudo, status, anexoNome, tipoInput });
  };

  const inp = { padding:'9px 12px', border:'1px solid #d1d5db', borderRadius:6, fontSize:13, background:'white', outline:'none', color:'#111', width:'100%', boxSizing:'border-box' };

  const TabBtn = ({ id, label, count }) => (
    <button onClick={() => { setAba(id); setHistDetalhe(null); }}
      style={{ padding:'10px 22px', border:'none', borderBottom: aba===id ? `2px solid ${C.primary}` : '2px solid transparent', background:'none', cursor:'pointer', fontSize:14, fontWeight: aba===id ? 700 : 400, color: aba===id ? C.primary : '#6b7280', display:'flex', alignItems:'center', gap:6, transition:'color .15s' }}>
      {label}
      {count !== undefined && (
        <span style={{ fontSize:11, fontWeight:700, background: aba===id ? C.primary : '#e5e7eb', color: aba===id ? 'white' : '#6b7280', borderRadius:10, padding:'1px 7px', transition:'all .15s' }}>{count}</span>
      )}
    </button>
  );

  /* ── Breadcrumb / back label */
  const backLabel = histDetalhe ? 'Histórico' : 'Voltar';
  const backAction = histDetalhe ? () => setHistDetalhe(null) : onVoltar;

  return (
    <div style={{ flex:1, display:'flex', flexDirection:'column', minHeight:0, background:C.pageBg, width:'100%' }}>
      {/* ── Header ── */}
      <div style={{ background:'white', borderBottom:'1px solid #e5e7eb', padding:'0 24px', display:'flex', alignItems:'center', gap:14, flexShrink:0 }}>
        <button onClick={backAction}
          style={{ display:'flex', alignItems:'center', gap:6, background:'none', border:'none', cursor:'pointer', color:'#6b7280', fontSize:13, fontWeight:500, padding:'14px 10px' }}
          onMouseEnter={e=>e.currentTarget.style.color='#111'} onMouseLeave={e=>e.currentTarget.style.color='#6b7280'}>
          <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M19 12H5M12 19l-7-7 7-7"/></svg>
          {backLabel}
        </button>
        <div style={{ width:1, height:20, background:'#e5e7eb' }}/>
        <div style={{ flex:1, display:'flex', alignItems:'center', gap:10 }}>
          <span style={{ fontSize:15, fontWeight:700, color:'#111' }}>
            {histDetalhe ? `Histórico — ${histDetalhe.data} · ${histDetalhe.hora}` : 'Prontuário'}
          </span>
          <span style={{ fontSize:13, color:'#9ca3af' }}>
            {histDetalhe ? histDetalhe.terapeuta : `${appt.patient} · ${dayInfo.label}, ${dayInfo.num}/06/2026 · ${appt.time}`}
          </span>
        </div>

        {/* Abas — ocultar quando em detalhe histórico */}
        {!histDetalhe && (
          <div style={{ display:'flex', alignSelf:'stretch' }}>
            <TabBtn id="prontuario" label="Prontuário" />
            <TabBtn id="historico"  label="Histórico"  count={historico.length} />
          </div>
        )}

        {aba === 'prontuario' && !histDetalhe && (
          <button onClick={handleSalvar}
            style={{ padding:'8px 20px', background: status==='finalizado' ? '#16a34a' : C.primary, color:'white', border:'none', borderRadius:6, fontSize:13, fontWeight:600, cursor:'pointer', flexShrink:0 }}>
            {status==='finalizado' ? '✓ Salvar e Finalizar' : 'Salvar rascunho'}
          </button>
        )}
      </div>

      {/* ── ABA PRONTUÁRIO ── */}
      {aba === 'prontuario' && !histDetalhe && (
        <div style={{ flex:1, overflowY:'auto', padding:'28px 40px', display:'flex', flexDirection:'column', gap:16 }}>
          {/* Cabeçalho da sessão */}
          <Card style={{ padding:'18px 24px' }}>
            <div style={{ display:'grid', gridTemplateColumns:'repeat(4,1fr)', gap:16 }}>
              {[
                { label:'Paciente',  value: appt.patient },
                { label:'Terapeuta', value: appt.terapeuta },
                { label:'Data',      value: `${dayInfo.label}, ${dayInfo.num}/06/2026` },
                { label:'Horário',   value: appt.time },
              ].map(f => (
                <div key={f.label}>
                  <div style={{ fontSize:11, fontWeight:700, color:'#9ca3af', textTransform:'uppercase', letterSpacing:'.06em', marginBottom:4 }}>{f.label}</div>
                  <div style={{ fontSize:14, fontWeight:600, color:'#111' }}>{f.value}</div>
                </div>
              ))}
            </div>
          </Card>

          <Card style={{ padding:'24px', flex:1 }}>
            {/* Toggle */}
            <div style={{ display:'flex', gap:8, marginBottom:18 }}>
              {[
                { id:'manual', label:'✏️ Preencher manualmente' },
                { id:'upload', label:'📎 Upload de arquivo' },
              ].map(op => (
                <button key={op.id} onClick={() => { setTipoInput(op.id); setErro(''); }}
                  style={{ flex:1, padding:'10px', border:`1.5px solid ${tipoInput===op.id ? C.primary : '#d1d5db'}`, borderRadius:6, background: tipoInput===op.id ? '#eff6ff' : 'white', color: tipoInput===op.id ? C.primary : '#374151', fontSize:14, fontWeight: tipoInput===op.id ? 600 : 400, cursor:'pointer', transition:'all .15s' }}>
                  {op.label}
                </button>
              ))}
            </div>

            {tipoInput === 'manual' && (
              <div>
                <div style={{ display:'flex', justifyContent:'space-between', marginBottom:8 }}>
                  <label style={{ fontSize:13, fontWeight:500, color:'#374151' }}>Conteúdo <span style={{ color:'#ef4444' }}>*</span></label>
                  <span style={{ fontSize:11, color: conteudo.length > MAX_CHARS*0.9 ? '#ef4444' : '#9ca3af' }}>{conteudo.length}/{MAX_CHARS}</span>
                </div>
                <textarea value={conteudo} onChange={e => { if (e.target.value.length <= MAX_CHARS) { setConteudo(e.target.value); setErro(''); } }}
                  placeholder="Descreva o conteúdo da sessão, observações clínicas, plano terapêutico, intercorrências…"
                  rows={16}
                  style={{ ...inp, resize:'vertical', lineHeight:1.8, fontFamily:'inherit', fontSize:14 }}/>
              </div>
            )}

            {tipoInput === 'upload' && (
              <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
                <label style={{ display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center', gap:10, padding:'40px', border:`2px dashed ${anexoNome ? '#22c55e' : '#d1d5db'}`, borderRadius:10, cursor:'pointer', background: anexoNome ? '#f0fdf4' : '#fafafa' }}>
                  <input type="file" accept=".pdf,.doc,.docx" onChange={handleAnexo} style={{ display:'none' }}/>
                  {anexoNome
                    ? (<><span style={{ fontSize:28 }}>✅</span><span style={{ fontSize:15, color:'#16a34a', fontWeight:600 }}>{anexoNome}</span><span style={{ fontSize:13, color:'#6b7280' }}>Clique para substituir</span></>)
                    : (<><Icon name="upload" size={32} color="#9ca3af"/><span style={{ fontSize:15, color:'#6b7280' }}>Clique para enviar o prontuário</span><span style={{ fontSize:13, color:'#9ca3af' }}>PDF, DOC ou DOCX</span></>)}
                </label>
                <textarea value={conteudo} onChange={e=>setConteudo(e.target.value)} rows={6}
                  placeholder="Observações complementares (opcional)…"
                  style={{ ...inp, resize:'vertical', fontFamily:'inherit', fontSize:14 }}/>
              </div>
            )}
          </Card>

          {/* Status */}
          <Card style={{ padding:'14px 24px', display:'flex', alignItems:'center', gap:12 }}>
            <span style={{ fontSize:13, fontWeight:500, color:'#374151' }}>Status:</span>
            {[
              { id:'pendente',   label:'Pendente',   bg:'#f3f4f6', border:'#d1d5db', col:'#6b7280' },
              { id:'finalizado', label:'Finalizado',  bg:'#dcfce7', border:'#86efac', col:'#15803d' },
            ].map(s => (
              <button key={s.id} onClick={() => setStatus(s.id)}
                style={{ padding:'7px 20px', border:`1.5px solid ${status===s.id ? s.border : '#e5e7eb'}`, borderRadius:20, background: status===s.id ? s.bg : 'white', color: status===s.id ? s.col : '#9ca3af', fontSize:13, fontWeight: status===s.id ? 700 : 400, cursor:'pointer', transition:'all .15s' }}>
                {s.label}
              </button>
            ))}
          </Card>

          {erro && <div style={{ padding:'10px 16px', background:'#fee2e2', border:'1px solid #fca5a5', borderRadius:6, fontSize:13, color:'#991b1b' }}>{erro}</div>}
        </div>
      )}

      {/* ── ABA HISTÓRICO — lista ── */}
      {aba === 'historico' && !histDetalhe && (
        <div style={{ flex:1, overflowY:'auto', padding:'28px 40px' }}>
          {historico.length === 0 ? (
            <div style={{ display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center', padding:'80px', color:'#9ca3af', gap:14 }}>
              <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round" strokeLinejoin="round"><path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/></svg>
              <span style={{ fontSize:16 }}>Nenhum prontuário anterior para {appt.patient}.</span>
            </div>
          ) : (
            <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
              {historico.map(h => (
                <div key={h.id} onClick={() => setHistDetalhe(h)}
                  style={{ background:'white', border:'1px solid #e5e7eb', borderRadius:12, padding:'20px 24px', cursor:'pointer', transition:'box-shadow .15s, border-color .15s' }}
                  onMouseEnter={e => { e.currentTarget.style.boxShadow='0 4px 20px rgba(0,0,0,0.08)'; e.currentTarget.style.borderColor='#93c5fd'; }}
                  onMouseLeave={e => { e.currentTarget.style.boxShadow='none'; e.currentTarget.style.borderColor='#e5e7eb'; }}>
                  <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:12 }}>
                    <div style={{ display:'flex', alignItems:'center', gap:12 }}>
                      <div style={{ width:40, height:40, borderRadius:10, background:'#eff6ff', display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0 }}>
                        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke={C.primary} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8z"/><polyline points="14 2 14 8 20 8"/></svg>
                      </div>
                      <div>
                        <div style={{ fontSize:15, fontWeight:700, color:'#111' }}>{h.data} · {h.hora}</div>
                        <div style={{ fontSize:13, color:'#6b7280', marginTop:2 }}>{h.terapeuta} · {h.unidade} · {h.sala}</div>
                      </div>
                    </div>
                    <div style={{ display:'flex', alignItems:'center', gap:10 }}>
                      {h.anexos && h.anexos.length > 0 && (
                        <span style={{ fontSize:12, color:'#6b7280', background:'#f3f4f6', padding:'3px 10px', borderRadius:10, display:'flex', alignItems:'center', gap:5 }}>
                          <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21.44 11.05l-9.19 9.19a6 6 0 01-8.49-8.49l9.19-9.19a4 4 0 015.66 5.66l-9.2 9.19a2 2 0 01-2.83-2.83l8.49-8.48"/></svg>
                          {h.anexos.length} anexo{h.anexos.length > 1 ? 's' : ''}
                        </span>
                      )}
                      <span style={{ fontSize:12, fontWeight:700, color:'#15803d', background:'#dcfce7', padding:'3px 12px', borderRadius:10 }}>Finalizado</span>
                      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#9ca3af" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M9 18l6-6-6-6"/></svg>
                    </div>
                  </div>
                  <p style={{ margin:0, fontSize:13, color:'#6b7280', lineHeight:1.7, overflow:'hidden', display:'-webkit-box', WebkitLineClamp:2, WebkitBoxOrient:'vertical' }}>
                    {h.conteudo}
                  </p>
                </div>
              ))}
            </div>
          )}
        </div>
      )}

      {/* ── DETALHE DE UM HISTÓRICO (tela cheia dentro das abas) ── */}
      {histDetalhe && (
        <div style={{ flex:1, overflowY:'auto', padding:'28px 40px', display:'flex', flexDirection:'column', gap:16 }}>
          {/* Cabeçalho da sessão histórica */}
          <Card style={{ padding:'18px 24px' }}>
            <div style={{ display:'grid', gridTemplateColumns:'repeat(4,1fr)', gap:16 }}>
              {[
                { label:'Paciente',  value: appt.patient },
                { label:'Terapeuta', value: histDetalhe.terapeuta },
                { label:'Data',      value: histDetalhe.data },
                { label:'Horário',   value: histDetalhe.hora },
                { label:'Unidade',   value: histDetalhe.unidade },
                { label:'Sala',      value: histDetalhe.sala },
                { label:'Status',    value: <span style={{ color:'#15803d', fontWeight:700 }}>Finalizado</span> },
              ].map(f => (
                <div key={f.label}>
                  <div style={{ fontSize:11, fontWeight:700, color:'#9ca3af', textTransform:'uppercase', letterSpacing:'.06em', marginBottom:4 }}>{f.label}</div>
                  <div style={{ fontSize:14, fontWeight:600, color:'#111' }}>{f.value}</div>
                </div>
              ))}
            </div>
          </Card>

          {/* Conteúdo */}
          <Card style={{ padding:'24px' }}>
            <div style={{ fontSize:12, fontWeight:700, color:'#9ca3af', textTransform:'uppercase', letterSpacing:'.06em', marginBottom:14 }}>Conteúdo da sessão</div>
            <div style={{ fontSize:14, color:'#374151', lineHeight:1.85, whiteSpace:'pre-wrap', padding:'18px', background:'#fafafa', borderRadius:8, border:'1px solid #f0f2f5' }}>
              {histDetalhe.conteudo}
            </div>
          </Card>

          {/* Anexos */}
          <Card style={{ padding:'20px 24px' }}>
            <div style={{ fontSize:12, fontWeight:700, color:'#9ca3af', textTransform:'uppercase', letterSpacing:'.06em', marginBottom:12 }}>Anexos</div>
            {histDetalhe.anexos && histDetalhe.anexos.length > 0 ? (
              <div style={{ display:'flex', flexDirection:'column', gap:8 }}>
                {histDetalhe.anexos.map((a, i) => (
                  <div key={i} style={{ display:'flex', alignItems:'center', gap:12, padding:'12px 16px', background:'white', border:'1px solid #e5e7eb', borderRadius:8 }}>
                    <div style={{ width:36, height:36, borderRadius:8, background:'#eff6ff', display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0 }}>
                      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke={C.primary} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                        <path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8z"/><polyline points="14 2 14 8 20 8"/>
                      </svg>
                    </div>
                    <span style={{ flex:1, fontSize:14, color:'#374151', fontWeight:500 }}>{a}</span>
                    <span style={{ fontSize:12, color:'#6b7280', background:'#f3f4f6', padding:'3px 10px', borderRadius:10 }}>
                      {a.endsWith('.pdf') ? 'PDF' : a.endsWith('.docx') ? 'DOCX' : 'DOC'}
                    </span>
                  </div>
                ))}
              </div>
            ) : (
              <div style={{ padding:'16px', background:'#f9fafb', border:'1px dashed #d1d5db', borderRadius:8, fontSize:14, color:'#9ca3af', textAlign:'center' }}>
                Nenhum anexo nesta sessão.
              </div>
            )}
          </Card>
        </div>
      )}
    </div>
  );
}


Object.assign(window, { ModalConsultaInfo, TelaProntuario });
