// Órbita — Editor Screen v2 (elevated)

// ── Rewrite suggestions (mock) ─────────────────────────────
const REWRITE_SUGGESTIONS = {
  'c-001': [
    { id: 'r1', headline: 'Saturno exige entrega: construa, não explore', summary: 'Um trânsito raro pela Casa 10 pede foco radical. O que não avançar até dezembro será abandonado.' },
    { id: 'r2', headline: 'Ano de maturidade profissional — colha o que plantou', summary: 'Projetos iniciados em 2024 chegam ao ponto de decisão: finalizar ou encerrar. Saturno não tolera meio-termo.' },
    { id: 'r3', headline: 'Foco em profundidade, não amplitude', summary: 'Com Saturno na cúspide da reputação, dispersão é o maior risco. Escolha uma frente e vá fundo.' },
  ],
  'c-002': [
    { id: 'r1', headline: 'Plutão faz curadoria dos seus vínculos', summary: 'Relações superficiais perdem força naturalmente. As essenciais se aprofundam de forma irreversível.' },
    { id: 'r2', headline: 'Transformação radical nas parcerias', summary: 'O que era conveniente vai se dissolver. O que é verdadeiro vai exigir mais — e entregar mais.' },
    { id: 'r3', headline: 'Ano de honestidade nas relações', summary: 'Plutão dissolve fachadas. Vínculos baseados em imagem ou conveniência chegam ao fim.' },
  ],
  'c-003': [
    { id: 'r1', headline: 'Reorganize as fontes de renda antes de novembro', summary: 'Urano traz imprevisibilidade financeira. Criar reserva e revisar investimentos é a tarefa central do ano.' },
    { id: 'r2', headline: 'Urano redesenha sua relação com dinheiro', summary: 'A forma como você ganha e guarda vai mudar. Resistir custa mais do que se adaptar.' },
    { id: 'r3', headline: 'Turbulência financeira pede estrutura prévia', summary: 'O segundo semestre traz instabilidade na Casa 8. Quem organizou cedo passa com menos impacto.' },
  ],
  'c-004': [
    { id: 'r1', headline: 'Marte × Saturno: 10 dias de pausa obrigatória', summary: 'Oposição exata entre 10-20 de agosto. Decisões tomadas nessa janela tendem a ser revistas em 30 dias.' },
    { id: 'r2', headline: 'Não decida em agosto — anote, não assine', summary: 'Tensão máxima entre ação e estrutura. Use o período para observar, não para agir.' },
    { id: 'r3', headline: 'Agosto 10-20: janela de revisão, não de avanço', summary: 'Marte oposto a Saturno gera impulso sem sustentação. Adie reuniões e contratos para setembro.' },
  ],
};

// ── Transcript source spans (each card maps to a phrase in the transcript) ──
const CARD_TRANSCRIPT_SPANS = {
  'c-001': 'Saturno passa pela sua casa dez',
  'c-002': 'Plutão em Aquário transitando pela sua casa sete',
  'c-003': 'Urano em Touro ainda tá ativo na sua casa oito',
  'c-004': 'janela de dez a vinte de agosto',
  'c-005': 'Vênus fica retrógrada de vinte de agosto a quinze de setembro',
  'c-006': 'Mercúrio direto',
  'c-007': 'Lua nova em Virgem',
  'c-008': 'Saturno em trânsito pela sua casa doze',
  'c-009': 'clareza mental',
};

// ── Keyboard shortcuts panel ───────────────────────────────
const ShortcutsPanel = ({ onClose }) => (
  <div style={{
    position: 'fixed', inset: 0, background: 'rgba(16,13,10,0.7)', backdropFilter: 'blur(6px)',
    display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 2000, padding: 20,
  }} onClick={onClose}>
    <div onClick={e => e.stopPropagation()} style={{
      width: '100%', maxWidth: 360, boxSizing: 'border-box', background: T.surface, border: `1px solid ${T.border}`,
      borderRadius: 18, padding: 28, position: 'relative',
    }}>
      <button onClick={onClose} style={{
        position: 'absolute', top: 14, right: 14, background: 'rgba(245,241,232,0.06)',
        border: 'none', borderRadius: '50%', width: 26, height: 26,
        color: T.fgMuted, cursor: 'pointer', fontSize: 14, display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>×</button>

      <h3 style={{ margin: '0 0 20px', fontFamily: '"Instrument Serif", serif', fontSize: 20, fontWeight: 400, color: T.fg }}>
        Atalhos de teclado
      </h3>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 0 }}>
        {[
          { key: 'A', desc: 'Aceitar card selecionado', color: T.success },
          { key: 'E', desc: 'Editar card selecionado', color: T.info },
          { key: 'D', desc: 'Descartar card selecionado', color: T.hot },
          { key: '↑ ↓', desc: 'Navegar entre cards', color: T.fgMuted },
          { key: '⌘ ↵', desc: 'Salvar edição em curso', color: T.accent },
          { key: 'Esc', desc: 'Cancelar edição / fechar', color: T.fgMuted },
          { key: '?', desc: 'Abrir / fechar este painel', color: T.fgMuted },
        ].map((s, i) => (
          <div key={i} style={{
            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            padding: '10px 0',
            borderBottom: i < 6 ? `1px solid ${T.border}` : 'none',
          }}>
            <span style={{ fontSize: 13, color: T.fgMuted }}>{s.desc}</span>
            <kbd style={{
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
              minWidth: 32, padding: '3px 8px', borderRadius: 6,
              background: 'rgba(245,241,232,0.06)', border: `1px solid rgba(245,241,232,0.14)`,
              color: s.color, fontSize: 12, fontFamily: 'monospace', fontWeight: 600,
              letterSpacing: '0.02em',
            }}>
              {s.key}
            </kbd>
          </div>
        ))}
      </div>
    </div>
  </div>
);

// ── Version history panel (mock) ───────────────────────────
const VersionHistoryPanel = ({ onClose }) => {
  const versions = [
    { id: 'v4', label: 'Versão atual', when: 'agora', who: 'você', desc: '18 cards aceitos, 5 pendentes' },
    { id: 'v3', label: 'Versão 3',     when: '2 h atrás', who: 'você', desc: 'Reescreveu 3 cards de Carreira' },
    { id: 'v2', label: 'Versão 2',     when: 'ontem às 14:20', who: 'você', desc: 'Aceitou meses 1–6' },
    { id: 'v1', label: 'Versão 1',     when: 'ontem às 09:05', who: 'IA', desc: 'Geração inicial a partir da transcrição' },
  ];
  return (
    <div style={{
      position: 'fixed', inset: 0, background: 'rgba(16,13,10,0.7)', backdropFilter: 'blur(6px)',
      display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 2000, padding: 20,
    }} onClick={onClose}>
      <div onClick={e => e.stopPropagation()} style={{
        width: '100%', maxWidth: 420, boxSizing: 'border-box', maxHeight: '80vh', overflowY: 'auto', background: T.surface, border: `1px solid ${T.border}`,
        borderRadius: 18, padding: 28, position: 'relative',
      }}>
        <button onClick={onClose} style={{
          position: 'absolute', top: 14, right: 14, background: 'rgba(245,241,232,0.06)',
          border: 'none', borderRadius: '50%', width: 26, height: 26,
          color: T.fgMuted, cursor: 'pointer', fontSize: 14,
        }}>×</button>
        <h3 style={{ margin: '0 0 20px', fontFamily: '"Instrument Serif", serif', fontSize: 20, fontWeight: 400, color: T.fg }}>
          Histórico de versões
        </h3>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
          {versions.map((v, i) => (
            <div key={v.id} style={{
              padding: '12px 14px', borderRadius: 12, marginBottom: 2,
              background: i === 0 ? 'rgba(244,162,97,0.08)' : 'transparent',
              border: `1px solid ${i === 0 ? 'rgba(244,162,97,0.22)' : 'transparent'}`,
            }}>
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 4 }}>
                <span style={{ fontSize: 13, fontWeight: 500, color: i === 0 ? T.accent : T.fg }}>{v.label}</span>
                <span style={{ fontSize: 11, color: T.fgDim, fontFamily: 'DM Mono, monospace' }}>{v.when}</span>
              </div>
              <div style={{ fontSize: 12, color: T.fgMuted, marginBottom: i === 0 ? 0 : 6 }}>{v.desc} · {v.who}</div>
              {i > 0 && (
                <button style={{
                  background: 'none', border: `1px solid ${T.border}`, borderRadius: 999, padding: '4px 12px',
                  color: T.fgMuted, fontSize: 11, cursor: 'pointer', fontFamily: 'Inter, sans-serif',
                }}>Restaurar esta versão</button>
              )}
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

// ── Rewrite Popover ────────────────────────────────────────
const RewritePopover = ({ cardId, onApply, onClose }) => {
  const suggestions = REWRITE_SUGGESTIONS[cardId] || [
    { id: 'r1', headline: 'Versão alternativa A', summary: 'Uma forma diferente de expressar a mesma ideia astrológica com mais clareza.' },
    { id: 'r2', headline: 'Versão alternativa B', summary: 'Tom mais direto e prático, focado na ação que a consulente pode tomar.' },
    { id: 'r3', headline: 'Versão alternativa C', summary: 'Linguagem mais poética e simbólica, próxima da tradição astrológica.' },
  ];

  return (
    <div style={{
      position: 'absolute', top: '100%', left: 0, right: 0, marginTop: 8,
      background: T.surface, border: `1px solid rgba(244,162,97,0.25)`,
      borderRadius: 14, padding: 14, zIndex: 500,
      boxShadow: '0 12px 40px rgba(0,0,0,0.5)',
    }}>
      {/* Arrow */}
      <div style={{
        position: 'absolute', top: -5, left: 20, width: 10, height: 10,
        background: T.surface, border: `1px solid rgba(244,162,97,0.25)`,
        transform: 'rotate(45deg)', borderBottom: 'none', borderRight: 'none',
      }} />

      <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 10 }}>
        <span style={{ fontSize: 12 }}>✨</span>
        <span style={{ fontSize: 11, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.08em', color: T.accent }}>
          Sugestões de reescrita
        </span>
        <div style={{ flex: 1 }} />
        <button onClick={onClose} style={{ background: 'none', border: 'none', color: T.fgDim, cursor: 'pointer', fontSize: 14, padding: '0 2px' }}>×</button>
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        {suggestions.map((sug, i) => (
          <button key={sug.id} onClick={() => onApply(sug)} style={{
            display: 'block', width: '100%', textAlign: 'left', padding: '10px 12px',
            background: 'rgba(245,241,232,0.04)', border: `1px solid ${T.border}`,
            borderRadius: 10, cursor: 'pointer', fontFamily: 'Inter, sans-serif',
            transition: 'all 0.15s',
          }}
          onMouseEnter={e => { e.currentTarget.style.background = 'rgba(244,162,97,0.08)'; e.currentTarget.style.borderColor = 'rgba(244,162,97,0.25)'; }}
          onMouseLeave={e => { e.currentTarget.style.background = 'rgba(245,241,232,0.04)'; e.currentTarget.style.borderColor = T.border; }}
          >
            <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 4 }}>
              <span style={{ fontSize: 10, color: T.accent, fontWeight: 700, opacity: 0.6 }}>{i + 1}</span>
              <span style={{ fontSize: 13, fontWeight: 500, color: T.fg }}>{sug.headline}</span>
            </div>
            <span style={{ fontSize: 11, color: T.fgMuted, lineHeight: 1.5, display: 'block' }}>{sug.summary}</span>
          </button>
        ))}
      </div>
    </div>
  );
};

// ── Status filter pills ────────────────────────────────────
const STATUS_FILTERS = [
  { id: 'all',       label: 'Todos'      },
  { id: 'suggested', label: 'Pendentes'  },
  { id: 'edited',    label: 'Editados'   },
  { id: 'accepted',  label: 'Aceitos'    },
  { id: 'discarded', label: 'Descartados' },
];

const FilterPills = ({ active, onChange, counts }) => (
  <div style={{ display: 'flex', gap: 6, padding: '10px 18px', borderBottom: `1px solid ${T.border}`, overflowX: 'auto', scrollbarWidth: 'none', flexShrink: 0 }}>
    {STATUS_FILTERS.map(f => {
      const isActive = active === f.id;
      const count = f.id === 'all' ? Object.values(counts).reduce((a, b) => a + b, 0) : (counts[f.id] || 0);
      return (
        <button key={f.id} onClick={() => onChange(f.id)} style={{
          display: 'inline-flex', alignItems: 'center', gap: 5,
          padding: '5px 13px', borderRadius: 999, fontSize: 12, fontWeight: 500,
          fontFamily: 'Inter, sans-serif', cursor: 'pointer', border: 'none',
          background: isActive ? 'rgba(244,162,97,0.18)' : 'rgba(245,241,232,0.06)',
          color: isActive ? T.accent : T.fg,
          opacity: isActive ? 1 : 0.78,
          transition: 'all 0.15s', whiteSpace: 'nowrap', flexShrink: 0,
        }}
        onMouseEnter={e => { if (!isActive) e.currentTarget.style.opacity = '1'; }}
        onMouseLeave={e => { if (!isActive) e.currentTarget.style.opacity = '0.78'; }}
        >
          {f.label}
          {count > 0 && (
            <span style={{
              fontSize: 10, padding: '0 5px', borderRadius: 999,
              background: isActive ? 'rgba(244,162,97,0.22)' : 'rgba(245,241,232,0.1)',
              color: isActive ? T.accent : T.fgMuted, fontFamily: 'DM Mono, monospace',
            }}>
              {count}
            </span>
          )}
        </button>
      );
    })}
  </div>
);

// ── Session Card v2 ────────────────────────────────────────
const SessionCard = ({
  card, status, isExpanded, isEditing, isFocused,
  onToggle, onAccept, onDiscard, onEdit, onStopEdit, onHighlight,
  onHoverIn, onHoverOut, isHighlighted,
}) => {
  const [headlineVal, setHeadlineVal] = React.useState(card.headline);
  const [summaryVal, setSummaryVal] = React.useState(card.summary);
  const [showRewrite, setShowRewrite] = React.useState(false);
  const isDiscarded = status === 'discarded';
  const isAccepted = status === 'accepted' || status === 'edited';

  const handleApplyRewrite = (sug) => {
    setHeadlineVal(sug.headline);
    setSummaryVal(sug.summary);
    setShowRewrite(false);
    onStopEdit && onStopEdit(sug.headline, sug.summary);
  };

  const borderColor = isHighlighted
    ? `rgba(244,162,97,0.55)`
    : isAccepted ? 'rgba(140,175,136,0.22)'
    : isDiscarded ? 'rgba(231,111,81,0.15)'
    : isFocused ? 'rgba(245,241,232,0.2)'
    : T.border;

  return (
    <div
      onMouseEnter={onHoverIn}
      onMouseLeave={onHoverOut}
      style={{
        background: isHighlighted ? 'rgba(244,162,97,0.04)' : T.card,
        backdropFilter: 'blur(12px)',
        border: `1px solid ${borderColor}`,
        borderRadius: 14, overflow: 'visible',
        opacity: isDiscarded ? 0.45 : 1,
        transition: 'all 0.18s',
        position: 'relative',
        zIndex: showRewrite ? 600 : 'auto',
        boxShadow: isFocused ? '0 0 0 2px rgba(244,162,97,0.12)' : 'none',
      }}
    >
      <div style={{ padding: '14px 16px' }}>
        {/* Top meta row */}
        <div style={{ display: 'flex', gap: 6, alignItems: 'center', marginBottom: 8, flexWrap: 'wrap' }}>
          <Badge status={status} small />
          {card.area && <AreaTag area={card.area} />}
          {card.intensity && <IntensityDot intensity={card.intensity} />}
          {isFocused && (
            <span style={{ marginLeft: 'auto', fontSize: 10, color: T.fgDim, fontFamily: 'monospace' }}>
              A · E · D
            </span>
          )}
        </div>

        {/* EDIT MODE — before/after */}
        {isEditing ? (
          <div>
            {/* Before */}
            <div style={{
              padding: '8px 10px', borderRadius: 8, marginBottom: 10,
              background: 'rgba(231,111,81,0.05)', border: `1px solid rgba(231,111,81,0.15)`,
            }}>
              <div style={{ fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.08em', color: 'rgba(231,111,81,0.6)', marginBottom: 5 }}>Original</div>
              <div style={{ fontSize: 13, fontWeight: 500, color: T.fgDim, textDecoration: 'line-through', lineHeight: 1.4, marginBottom: 3 }}>
                {card.headline}
              </div>
              <div style={{ fontSize: 11, color: 'rgba(245,241,232,0.25)', textDecoration: 'line-through', lineHeight: 1.5 }}>
                {card.summary}
              </div>
            </div>

            {/* Separator */}
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
              <div style={{ flex: 1, height: 1, background: 'rgba(245,241,232,0.08)' }} />
              <span style={{ fontSize: 10, color: T.fgDim, textTransform: 'uppercase', letterSpacing: '0.08em' }}>Nova versão</span>
              <div style={{ flex: 1, height: 1, background: 'rgba(245,241,232,0.08)' }} />
            </div>

            {/* After — editable */}
            <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
              <input
                autoFocus
                value={headlineVal}
                onChange={e => setHeadlineVal(e.target.value)}
                style={{
                  width: '100%', background: 'rgba(244,162,97,0.06)',
                  border: `1px solid rgba(244,162,97,0.3)`,
                  borderRadius: 8, padding: '7px 10px', color: T.fg,
                  fontSize: 14, fontWeight: 500, fontFamily: 'Inter, sans-serif',
                  boxSizing: 'border-box', outline: 'none',
                }}
              />
              <textarea
                value={summaryVal}
                onChange={e => setSummaryVal(e.target.value)}
                rows={2}
                style={{
                  width: '100%', background: 'rgba(244,162,97,0.06)',
                  border: `1px solid rgba(244,162,97,0.3)`,
                  borderRadius: 8, padding: '7px 10px', color: T.fgMuted,
                  fontSize: 12, fontFamily: 'Inter, sans-serif',
                  resize: 'none', boxSizing: 'border-box', outline: 'none', lineHeight: 1.6,
                }}
              />
            </div>
          </div>
        ) : (
          /* DISPLAY MODE */
          <>
            <div style={{ fontSize: 14, fontWeight: 500, color: T.fg, marginBottom: 4, lineHeight: 1.4 }}>{headlineVal}</div>
            <div style={{ fontSize: 12, color: T.fgMuted, lineHeight: 1.65 }}>{summaryVal}</div>
          </>
        )}

        {/* Detail */}
        {isExpanded && card.detail && !isEditing && (
          <div style={{
            marginTop: 10, padding: '10px 12px', borderRadius: 8,
            background: 'rgba(245,241,232,0.04)', fontSize: 12, color: T.fgMuted, lineHeight: 1.7,
            borderLeft: `2px solid rgba(244,162,97,0.2)`,
          }}>
            {card.detail}
          </div>
        )}

        {/* Action bar */}
        <div style={{ display: 'flex', gap: 6, marginTop: 12, alignItems: 'center', flexWrap: 'wrap' }}>
          {isEditing ? (
            <>
              <button
                onClick={() => onStopEdit && onStopEdit(headlineVal, summaryVal)}
                style={{
                  display: 'flex', alignItems: 'center', gap: 5, padding: '5px 14px',
                  background: '#F5F1E8',
                  border: 'none', borderRadius: 999, color: '#100D0A',
                  fontSize: 11, fontWeight: 600, cursor: 'pointer', fontFamily: 'Inter, sans-serif',
                }}
              >
                ✓ Salvar  <kbd style={{ background: 'rgba(0,0,0,0.15)', borderRadius: 4, padding: '1px 4px', fontSize: 9 }}>⌘↵</kbd>
              </button>
              <button onClick={() => onEdit()} style={{
                padding: '5px 12px', background: 'transparent',
                border: `1px solid rgba(245,241,232,0.12)`, borderRadius: 999,
                color: T.fgDim, fontSize: 11, cursor: 'pointer', fontFamily: 'Inter, sans-serif',
              }}>
                Cancelar <kbd style={{ background: 'rgba(245,241,232,0.06)', borderRadius: 4, padding: '1px 4px', fontSize: 9, marginLeft: 3 }}>Esc</kbd>
              </button>
            </>
          ) : (
            <>
              {!isAccepted && (
                <button onClick={onAccept} style={{
                  display: 'flex', alignItems: 'center', gap: 4, padding: '5px 12px',
                  background: 'rgba(140,175,136,0.12)', border: `1px solid rgba(140,175,136,0.25)`,
                  borderRadius: 999, color: T.success, fontSize: 11, fontWeight: 500,
                  cursor: 'pointer', fontFamily: 'Inter, sans-serif',
                }}>✓ Aceitar</button>
              )}
              {isAccepted && (
                <span style={{ fontSize: 11, color: T.success, display: 'flex', alignItems: 'center', gap: 4 }}>
                  <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><polyline points="20 6 9 17 4 12"/></svg>
                  Aceito
                </span>
              )}
              {!isDiscarded && (
                <button onClick={onDiscard} style={{
                  padding: '5px 12px', background: 'transparent',
                  border: `1px solid rgba(245,241,232,0.1)`, borderRadius: 999,
                  color: T.fgDim, fontSize: 11, cursor: 'pointer', fontFamily: 'Inter, sans-serif',
                }}>Descartar</button>
              )}
              <button onClick={onEdit} style={{
                padding: '5px 12px', background: 'transparent',
                border: `1px solid rgba(245,241,232,0.1)`, borderRadius: 999,
                color: T.fgDim, fontSize: 11, cursor: 'pointer', fontFamily: 'Inter, sans-serif',
              }}>✎ Editar</button>

              {/* Rewrite button */}
              <div style={{ position: 'relative' }}>
                <button onClick={() => setShowRewrite(r => !r)} style={{
                  display: 'flex', alignItems: 'center', gap: 4, padding: '5px 12px',
                  background: showRewrite ? 'rgba(244,162,97,0.12)' : 'transparent',
                  border: `1px solid ${showRewrite ? 'rgba(244,162,97,0.3)' : 'rgba(245,241,232,0.1)'}`,
                  borderRadius: 999, color: showRewrite ? T.accent : T.fgDim,
                  fontSize: 11, cursor: 'pointer', fontFamily: 'Inter, sans-serif',
                  whiteSpace: 'nowrap', transition: 'all 0.15s',
                }}>✨ Reescrever</button>
                {showRewrite && (
                  <RewritePopover
                    cardId={card.id}
                    onApply={handleApplyRewrite}
                    onClose={() => setShowRewrite(false)}
                  />
                )}
              </div>
            </>
          )}

          {!isEditing && (
            <>
              <div style={{ flex: 1 }} />
              <button onClick={onHighlight} title="Destacar trecho na transcrição" style={{
                background: 'none', border: 'none', color: T.fgDim, fontSize: 11,
                cursor: 'pointer', padding: '4px 6px', display: 'flex', alignItems: 'center', gap: 3,
                fontFamily: 'Inter, sans-serif',
              }}>
                <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                  <path d="M9 11l3 3L22 4"/><path d="M21 12v7a2 2 0 01-2 2H5a2 2 0 01-2-2V5a2 2 0 012-2h11"/>
                </svg>
                Trecho
              </button>
              {card.detail && (
                <button onClick={onToggle} style={{
                  background: 'none', border: 'none', color: T.fgDim, fontSize: 11,
                  cursor: 'pointer', padding: '4px 6px', fontFamily: 'Inter, sans-serif',
                }}>
                  {isExpanded ? '↑' : '↓'} Detalhe
                </button>
              )}
            </>
          )}
        </div>
      </div>
    </div>
  );
};

// ── Month rewrite suggestions (mock) ──────────────────────
const MONTH_REWRITE_SUGGESTIONS = [
  { id: 'r1', headline: 'Tom mais direto', summary: 'Reformula o foco e o risco em linguagem prática, sem jargão astrológico.' },
  { id: 'r2', headline: 'Tom mais poético', summary: 'Reescreve com referências simbólicas da tradição, mais lírico que técnico.' },
  { id: 'r3', headline: 'Foco em ação', summary: 'Converte foco e risco em duas ações concretas pra consulente fazer esta semana.' },
];

// ── Month Card v2 — com sugestões + edição ────────────────
const MonthCard = ({ mc, status, isExpanded, onToggle, onAccept, onDiscard, onHighlight, onEdit }) => {
  const [showRewrite, setShowRewrite] = React.useState(false);
  const [foco, setFoco] = React.useState(mc.headline);
  const [risco, setRisco] = React.useState(mc.summary);
  const isAccepted = status === 'accepted' || status === 'edited';
  const isDiscarded = status === 'discarded';

  const handleApply = (sug) => {
    setFoco(sug.headline);
    setRisco(sug.summary);
    setShowRewrite(false);
    onEdit && onEdit(sug.headline, sug.summary);
  };

  return (
    <div style={{
      background: T.card, backdropFilter: 'blur(12px)',
      border: `1px solid ${isAccepted ? 'rgba(140,175,136,0.22)' : T.border}`,
      borderRadius: 14, overflow: 'visible',
      opacity: isDiscarded ? 0.45 : 1, transition: 'all 0.2s',
      position: 'relative', zIndex: showRewrite ? 600 : 'auto',
    }}>
      <div style={{ padding: '14px 16px' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
          <span style={{ fontSize: 12, color: T.accent, fontWeight: 600, minWidth: 22, fontFamily: 'DM Mono, monospace' }}>{mc.i < 10 ? `0${mc.i}` : mc.i}</span>
          <span style={{ fontSize: 14, fontWeight: 500, color: T.fg }}>{mc.nome}</span>
          <Badge status={status} small />
          <div style={{ flex: 1 }} />
          <button onClick={onToggle} style={{ background: 'none', border: 'none', color: T.fgMuted, cursor: 'pointer', fontSize: 12, padding: '2px 6px' }}>
            {isExpanded ? '↑' : '↓'}
          </button>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
          {[{ label: 'Foco', value: foco, color: T.info }, { label: 'Risco', value: risco, color: T.hot }].map(item => (
            <div key={item.label} style={{ padding: '8px 10px', borderRadius: 8, background: 'rgba(245,241,232,0.03)', border: `1px solid ${T.border}` }}>
              <div style={{ fontSize: 9, textTransform: 'uppercase', letterSpacing: '0.08em', color: item.color, marginBottom: 4, fontWeight: 600 }}>{item.label}</div>
              <div style={{ fontSize: 11, color: T.fgMuted, lineHeight: 1.55 }}>{item.value}</div>
            </div>
          ))}
        </div>
        {isExpanded && mc.oportunidade && (
          <div style={{ marginTop: 8, padding: '8px 10px', borderRadius: 8, background: 'rgba(140,175,136,0.06)', border: `1px solid rgba(140,175,136,0.18)` }}>
            <div style={{ fontSize: 9, textTransform: 'uppercase', letterSpacing: '0.08em', color: T.success, marginBottom: 4, fontWeight: 600 }}>Oportunidade</div>
            <div style={{ fontSize: 11, color: T.fgMuted, lineHeight: 1.55 }}>{mc.oportunidade}</div>
          </div>
        )}
        <div style={{ display: 'flex', gap: 6, marginTop: 12, alignItems: 'center', flexWrap: 'wrap' }}>
          {!isAccepted && (
            <button onClick={onAccept} style={{ display: 'flex', alignItems: 'center', gap: 4, padding: '5px 12px', background: 'rgba(140,175,136,0.12)', border: `1px solid rgba(140,175,136,0.25)`, borderRadius: 999, color: T.success, fontSize: 11, fontWeight: 500, cursor: 'pointer', fontFamily: 'Inter, sans-serif' }}>✓ Aceitar</button>
          )}
          {isAccepted && (
            <span style={{ fontSize: 11, color: T.success, display: 'flex', alignItems: 'center', gap: 4 }}>
              <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><polyline points="20 6 9 17 4 12"/></svg>
              Aceito
            </span>
          )}
          {!isDiscarded && (
            <button onClick={onDiscard} style={{ padding: '5px 12px', background: 'transparent', border: `1px solid rgba(245,241,232,0.12)`, borderRadius: 999, color: T.fgMuted, fontSize: 11, cursor: 'pointer', fontFamily: 'Inter, sans-serif' }}>Descartar</button>
          )}

          {/* Reescrever — o que faltava na aba Meses */}
          <div style={{ position: 'relative' }}>
            <button onClick={() => setShowRewrite(r => !r)} style={{
              display: 'flex', alignItems: 'center', gap: 4, padding: '5px 12px',
              background: showRewrite ? 'rgba(244,162,97,0.12)' : 'transparent',
              border: `1px solid ${showRewrite ? 'rgba(244,162,97,0.3)' : 'rgba(245,241,232,0.12)'}`,
              borderRadius: 999, color: showRewrite ? T.accent : T.fgMuted,
              fontSize: 11, cursor: 'pointer', fontFamily: 'Inter, sans-serif',
              whiteSpace: 'nowrap', transition: 'all 0.15s',
            }}>✨ Reescrever</button>
            {showRewrite && (
              <div style={{
                position: 'absolute', top: '100%', left: 0, marginTop: 8, minWidth: 320,
                background: T.surface, border: `1px solid rgba(244,162,97,0.25)`,
                borderRadius: 14, padding: 14, zIndex: 500,
                boxShadow: '0 12px 40px rgba(0,0,0,0.5)',
              }}>
                <div style={{ position: 'absolute', top: -5, left: 20, width: 10, height: 10, background: T.surface, border: `1px solid rgba(244,162,97,0.25)`, transform: 'rotate(45deg)', borderBottom: 'none', borderRight: 'none' }} />
                <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 10 }}>
                  <span style={{ fontSize: 12 }}>✨</span>
                  <span style={{ fontSize: 11, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.08em', color: T.accent }}>Sugestões para {mc.nome}</span>
                  <div style={{ flex: 1 }} />
                  <button onClick={() => setShowRewrite(false)} style={{ background: 'none', border: 'none', color: T.fgDim, cursor: 'pointer', fontSize: 14, padding: '0 2px' }}>×</button>
                </div>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                  {MONTH_REWRITE_SUGGESTIONS.map((sug, i) => (
                    <button key={sug.id} onClick={() => handleApply(sug)} style={{
                      display: 'block', width: '100%', textAlign: 'left', padding: '10px 12px',
                      background: 'rgba(245,241,232,0.04)', border: `1px solid ${T.border}`,
                      borderRadius: 10, cursor: 'pointer', fontFamily: 'Inter, sans-serif', transition: 'all 0.15s',
                    }}
                    onMouseEnter={e => { e.currentTarget.style.background = 'rgba(244,162,97,0.08)'; e.currentTarget.style.borderColor = 'rgba(244,162,97,0.25)'; }}
                    onMouseLeave={e => { e.currentTarget.style.background = 'rgba(245,241,232,0.04)'; e.currentTarget.style.borderColor = T.border; }}
                    >
                      <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 4 }}>
                        <span style={{ fontSize: 10, color: T.accent, fontWeight: 700, opacity: 0.7 }}>{i + 1}</span>
                        <span style={{ fontSize: 13, fontWeight: 500, color: T.fg }}>{sug.headline}</span>
                      </div>
                      <span style={{ fontSize: 11, color: T.fgMuted, lineHeight: 1.5, display: 'block' }}>{sug.summary}</span>
                    </button>
                  ))}
                </div>
              </div>
            )}
          </div>

          <div style={{ flex: 1 }} />
          <button onClick={onHighlight} title="Destacar trecho na transcrição" style={{ background: 'none', border: 'none', color: T.fgMuted, fontSize: 11, cursor: 'pointer', fontFamily: 'Inter, sans-serif', padding: '4px 6px', display: 'flex', alignItems: 'center', gap: 3 }}>
            <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M9 11l3 3L22 4"/><path d="M21 12v7a2 2 0 01-2 2H5a2 2 0 01-2-2V5a2 2 0 012-2h11"/></svg>
            Trecho
          </button>
        </div>
      </div>
    </div>
  );
};

// ── Publish Modal ──────────────────────────────────────────
// `session` traz o public_slug se a leitura já tinha sido publicada antes
// (idempotente — reclicar mantém o mesmo link). Sem slug ainda, o link real só
// existe depois que `onPublish` resolve — por isso o botão fica "Publicando…"
// e só then mostra o link (copiar de verdade, sem navegar sozinho: quem decide
// sair pro portal é a astróloga, com o link já copiado).
const PublishModal = ({ onClose, onPublish, onGoToPortal, consulente, session, acceptedCount, totalCount, periodLabel, forceError = false }) => {
  const [copied, setCopied] = React.useState(false);
  const [attempted, setAttempted] = React.useState(false);
  const [publishing, setPublishing] = React.useState(false);
  const [publishedSlug, setPublishedSlug] = React.useState(session?.public_slug || null);
  const [publishFailed, setPublishFailed] = React.useState(false);
  const origin = typeof window !== 'undefined' ? window.location.origin : '';
  const link = publishedSlug ? `${origin}/portal/${publishedSlug}` : null;

  const handleConfirm = async () => {
    if (forceError) { setAttempted(true); return; }
    setPublishFailed(false);
    setPublishing(true);
    try {
      const record = await onPublish();
      setPublishedSlug(record?.public_slug || null);
    } catch {
      setPublishFailed(true);
    } finally {
      setPublishing(false);
    }
  };

  const handleCopy = () => {
    if (!link) return;
    navigator.clipboard.writeText(link)
      .then(() => { setCopied(true); setTimeout(() => setCopied(false), 2000); })
      .catch(() => {});
  };

  if ((forceError && attempted) || publishFailed) {
    return (
      <div style={{
        position: 'fixed', inset: 0, background: 'rgba(16,13,10,0.85)', backdropFilter: 'blur(8px)',
        display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 1000, padding: 20,
      }} onClick={onClose}>
        <div onClick={e => e.stopPropagation()} style={{
          width: '100%', maxWidth: 440, boxSizing: 'border-box', background: T.surface, border: `1px solid ${T.hot}40`,
          borderRadius: 20, padding: 32, position: 'relative', textAlign: 'center',
        }}>
          <button onClick={onClose} style={{ position: 'absolute', top: 16, right: 16, background: 'rgba(245,241,232,0.06)', border: 'none', borderRadius: '50%', width: 28, height: 28, color: T.fgMuted, cursor: 'pointer', fontSize: 14 }}>×</button>
          <div style={{ fontSize: 30, color: T.hot, marginBottom: 14 }}>✕</div>
          <h2 style={{ margin: '0 0 8px', fontFamily: '"Instrument Serif", serif', fontSize: 22, fontWeight: 400, color: T.fg }}>Não foi possível publicar</h2>
          <p style={{ margin: '0 0 22px', fontSize: 13, color: T.fgMuted, lineHeight: 1.6 }}>Tivemos uma instabilidade ao gerar o portal. Nenhuma alteração foi perdida — tente novamente em alguns segundos.</p>
          <div style={{ display: 'flex', gap: 10 }}>
            <BtnGhost onClick={onClose} style={{ flex: 1 }}>Fechar</BtnGhost>
            <BtnPrimary onClick={() => { setAttempted(false); setPublishFailed(false); }} style={{ flex: 1 }}>Tentar novamente</BtnPrimary>
          </div>
        </div>
      </div>
    );
  }
  return (
    <div style={{
      position: 'fixed', inset: 0, background: 'rgba(16,13,10,0.85)', backdropFilter: 'blur(8px)',
      display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 1000, padding: 20,
    }} onClick={onClose}>
      <div onClick={e => e.stopPropagation()} style={{
        width: '100%', maxWidth: 480, boxSizing: 'border-box', background: T.surface, border: `1px solid ${T.border}`,
        borderRadius: 20, padding: 36, position: 'relative',
      }}>
        <button onClick={onClose} style={{ position: 'absolute', top: 16, right: 16, background: 'rgba(245,241,232,0.06)', border: 'none', borderRadius: '50%', width: 28, height: 28, color: T.fgMuted, cursor: 'pointer', fontSize: 14 }}>×</button>
        <div style={{ textAlign: 'center', marginBottom: 28 }}>
          <div style={{ fontSize: 40, marginBottom: 12 }}>🚀</div>
          <h2 style={{ margin: '0 0 8px', fontFamily: '"Instrument Serif", serif', fontSize: 24, fontWeight: 400 }}>Publicar sessão</h2>
          <p style={{ margin: 0, fontSize: 13, color: T.fgMuted }}>A consulente receberá acesso ao portal personalizado.</p>
        </div>
        <div style={{ background: 'rgba(245,241,232,0.04)', borderRadius: 12, padding: 16, marginBottom: 20 }}>
          {[
            ['Consulente', consulente?.name || '—', T.fg],
            ['Cards aceitos', `${acceptedCount ?? 0} de ${totalCount ?? 0}`, T.success],
            ...(periodLabel ? [['Período', periodLabel, T.fg]] : []),
          ].map(([l, v, c]) => (
            <div key={l} style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, color: T.fgMuted, marginBottom: 6 }}>
              <span>{l}</span><span style={{ color: c }}>{v}</span>
            </div>
          ))}
        </div>
        {link ? (
          <div style={{ display: 'flex', gap: 8, marginBottom: 24 }}>
            <div style={{ flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', background: 'rgba(245,241,232,0.04)', border: `1px solid ${T.border}`, borderRadius: 10, padding: '10px 14px', fontSize: 13, color: T.fgMuted, fontFamily: 'monospace' }}>{link}</div>
            <button onClick={handleCopy} style={{ padding: '0 16px', borderRadius: 10, border: `1px solid ${copied ? 'rgba(140,175,136,0.3)' : T.border}`, background: copied ? 'rgba(140,175,136,0.1)' : 'rgba(245,241,232,0.06)', color: copied ? T.success : T.fg, fontSize: 12, cursor: 'pointer', whiteSpace: 'nowrap', fontFamily: 'Inter, sans-serif' }}>
              {copied ? '✓ Copiado' : 'Copiar link'}
            </button>
          </div>
        ) : (
          <p style={{ margin: '0 0 24px', fontSize: 12, color: T.fgMuted, textAlign: 'center' }}>
            {publishing ? 'Gerando o link do portal…' : 'O link real aparece aqui assim que você publicar.'}
          </p>
        )}
        {link ? (
          <BtnPrimary onClick={onGoToPortal} style={{ width: '100%' }}>Ir para o portal</BtnPrimary>
        ) : (
          <BtnPrimary onClick={handleConfirm} disabled={publishing} style={{ width: '100%', opacity: publishing ? 0.7 : 1 }}>
            {publishing ? 'Publicando…' : 'Confirmar e publicar'}
          </BtnPrimary>
        )}
      </div>
    </div>
  );
};

// ── LAYER TABS ─────────────────────────────────────────────
const LAYER_TABS = [
  { id: 'visao_ano',   label: 'Visão',   icon: '◎' },
  { id: 'foco_mensal', label: 'Meses',   icon: '◑' },
  { id: 'alerta',      label: 'Alertas', icon: '⚠' },
  { id: 'acao',        label: 'Ações',   icon: '→' },
  { id: 'rotina',      label: 'Rotina',  icon: '↻' },
];

// ── EDITOR SCREEN v2 ───────────────────────────────────────
const EditorScreen = ({ session, onBack, onPreview, onPublish, onGoToPortal, publishError = false }) => {
  // `session` vem do motor real (upload → /api/extract) quando existe; sem ele
  // (atalho de protótipo pulando direto pro Editor), cai no mock de revisão.
  const mock = window.ORBITA_DATA;
  const leitura = (session && session.leitura) || mock.sessionDetail;
  const transcript = (session && session.transcript) || mock.transcript;
  const consulente = (session && session.consulente) || mock.consulentes.find(c => c.id === 'con-001');
  const isMockReview = !(session && session.leitura);
  const leituraId = isMockReview ? null : (session.id ?? null);

  // Cards reais do motor não têm `id` (ver lib/motor/schema.ts) — sintetiza um
  // estável por posição pra chave de estado local. O mock já tem id e é preservado.
  const cards = React.useMemo(
    () => (leitura.cards || []).map((c, i) => ({ id: c.id ?? `c-${i}`, ...c })),
    [leitura],
  );

  const [activeTab, setActiveTab]         = React.useState('visao_ano');
  const [statusFilter, setStatusFilter]   = React.useState('all');
  const [cardStates, setCardStates]       = React.useState(() => {
    const s = {};
    cards.forEach(c => { s[c.id] = c.status; });
    return s;
  });
  const [cardTexts, setCardTexts]         = React.useState(() => {
    const t = {};
    cards.forEach(c => { t[c.id] = { headline: c.headline, summary: c.summary }; });
    return t;
  });
  const [expandedCards, setExpandedCards] = React.useState({});
  const [editingCard, setEditingCard]     = React.useState(null);
  const [focusedCard, setFocusedCard]     = React.useState(null);
  const [hoveredCard, setHoveredCard]     = React.useState(null);  // card id hovered
  const [highlightedSpan, setHighlightedSpan] = React.useState(null);
  const [showPublish, setShowPublish]     = React.useState(false);
  const [showShortcuts, setShowShortcuts] = React.useState(false);
  const [showHistory, setShowHistory]     = React.useState(false);
  // saveState: 'nosync' (atalho de protótipo, sem sessão real — nada pra salvar),
  // 'unsaved' (extração real mas sem id — banco não configurado ou falhou ao salvar),
  // 'saved' | 'saving' | 'error' (autosave real via PATCH /api/leituras/[id]).
  const [saveState, setSaveState] = React.useState(
    leituraId ? 'saved' : isMockReview ? 'nosync' : 'unsaved',
  );
  const [savedSecsAgo, setSavedSecsAgo]   = React.useState(0);

  React.useEffect(() => {
    const t = setInterval(() => setSavedSecsAgo(s => s + 1), 1000);
    return () => clearInterval(t);
  }, []);

  // Autosave real, debounced — ignora o primeiro disparo (estado inicial vindo
  // direto do motor, nada foi editado ainda) pra não fazer PATCH à toa ao abrir.
  const skipNextSave = React.useRef(true);
  React.useEffect(() => {
    if (!leituraId) return;
    if (skipNextSave.current) { skipNextSave.current = false; return; }
    setSaveState('saving');
    const t = setTimeout(() => {
      const patchedCards = cards.map(c => ({
        layer: c.layer, area: c.area, intensity: c.intensity, detail: c.detail,
        headline: (cardTexts[c.id] && cardTexts[c.id].headline) ?? c.headline,
        summary: (cardTexts[c.id] && cardTexts[c.id].summary) ?? c.summary,
        status: cardStates[c.id] || 'suggested',
      }));
      fetch(`/api/leituras/${leituraId}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ leitura: { ...leitura, cards: patchedCards }, consulente }),
      })
        .then(res => {
          if (!res.ok) throw new Error('save failed');
          setSaveState('saved');
          setSavedSecsAgo(0);
        })
        .catch(() => setSaveState('error'));
    }, 900);
    return () => clearTimeout(t);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [cardStates, cardTexts, leituraId]);

  const transcriptRef = React.useRef(null);

  // Build month cards
  const monthCards = leitura.meses.map(m => ({
    id: `m-${m.i}`, layer: 'foco_mensal', month: m.i, nome: m.nome,
    headline: m.foco, summary: m.risco, oportunidade: m.oportunidade,
  }));

  const setStatus = (id, status) => setCardStates(p => ({ ...p, [id]: status }));

  // Status counts for current tab
  const currentLayerCards = activeTab === 'foco_mensal'
    ? monthCards
    : cards.filter(c => c.layer === activeTab);

  const statusCounts = React.useMemo(() => {
    const counts = { suggested: 0, edited: 0, accepted: 0, discarded: 0 };
    currentLayerCards.forEach(c => {
      const s = cardStates[c.id] || 'suggested';
      if (counts[s] !== undefined) counts[s]++;
    });
    return counts;
  }, [cardStates, activeTab, currentLayerCards]);

  // Filtered cards
  const filteredCards = React.useMemo(() => {
    if (statusFilter === 'all') return currentLayerCards;
    return currentLayerCards.filter(c => (cardStates[c.id] || 'suggested') === statusFilter);
  }, [currentLayerCards, statusFilter, cardStates]);

  // Focused card index within filtered list
  const focusedIdx = filteredCards.findIndex(c => c.id === focusedCard);

  // Global counts
  const acceptedCount = Object.values(cardStates).filter(s => s === 'accepted' || s === 'edited').length;
  const totalCount = cards.length + leitura.meses.length;

  // Período real do ciclo (pro modal de publicar) — sem year_start (mock, ou
  // sessão real sem essa data), esconde a linha em vez de inventar uma.
  const periodLabel = React.useMemo(() => {
    const yearStart = session?.year_start;
    if (!yearStart) return null;
    const start = new Date(yearStart);
    if (Number.isNaN(start.getTime())) return null;
    const end = new Date(start); end.setUTCFullYear(end.getUTCFullYear() + 1); end.setUTCDate(end.getUTCDate() - 1);
    const fmt = (d) => d.toLocaleDateString('pt-BR', { month: 'short', year: 'numeric', timeZone: 'UTC' });
    return `${fmt(start)} – ${fmt(end)}`;
  }, [session]);

  // Transcript highlight
  const highlightTranscript = (keywords) => {
    setHighlightedSpan(keywords);
  };

  // Build transcript HTML with source spans
  const transcriptHtml = React.useMemo(() => {
    // Parse into paragraphs by timestamp
    const blocks = transcript.split('\n\n').filter(Boolean);

    const allSpans = Object.entries(CARD_TRANSCRIPT_SPANS);

    let html = blocks.map(block => {
      // Replace timestamp
      let b = block.replace(/\[(\d{2}:\d{2}:\d{2})\]\s*/g, (_, ts) =>
        `<span class="ts">${ts}</span> `
      );

      // Mark sourced spans
      allSpans.forEach(([cardId, phrase]) => {
        const words = phrase.split(' ').slice(0, 5).join(' ');
        const escaped = words.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
        const re = new RegExp(`(${escaped}[^.!?]*)`, 'i');
        b = b.replace(re, (match) =>
          `<span class="src-span" data-card="${cardId}" style="
            background: rgba(244,162,97,0.1);
            border-bottom: 1.5px dotted rgba(244,162,97,0.5);
            border-radius: 3px;
            padding: 1px 2px;
            cursor: pointer;
          ">${match}</span>`
        );
      });

      // Highlight keywords
      if (highlightedSpan) {
        const words = highlightedSpan.split(' ').filter(w => w.length > 4);
        words.forEach(w => {
          const re = new RegExp(`(${w})`, 'gi');
          b = b.replace(re, '<mark style="background:rgba(244,162,97,0.28);color:#F5F1E8;border-radius:3px;padding:1px 3px">$1</mark>');
        });
      }

      return `<p style="margin:0 0 18px;line-height:1.8">${b}</p>`;
    }).join('');

    return html;
  }, [highlightedSpan]);

  // Keyboard shortcuts
  React.useEffect(() => {
    const onKey = (e) => {
      if (e.key === '?') { setShowShortcuts(s => !s); return; }
      if (!focusedCard || activeTab === 'foco_mensal') return;
      if (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA') return;

      if (e.key === 'a' || e.key === 'A') { setStatus(focusedCard, 'accepted'); }
      if (e.key === 'd' || e.key === 'D') { setStatus(focusedCard, 'discarded'); }
      if (e.key === 'e' || e.key === 'E') { setEditingCard(c => c === focusedCard ? null : focusedCard); }
      if (e.key === 'Escape') { setEditingCard(null); setShowShortcuts(false); }
      if ((e.metaKey || e.ctrlKey) && e.key === 'Enter') {
        if (editingCard) setEditingCard(null);
      }
      if (e.key === 'ArrowDown') {
        e.preventDefault();
        const next = filteredCards[Math.min(focusedIdx + 1, filteredCards.length - 1)];
        if (next) setFocusedCard(next.id);
      }
      if (e.key === 'ArrowUp') {
        e.preventDefault();
        const prev = filteredCards[Math.max(focusedIdx - 1, 0)];
        if (prev) setFocusedCard(prev.id);
      }
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [focusedCard, editingCard, filteredCards, focusedIdx, activeTab]);

  // Hover on transcript span → highlight card
  React.useEffect(() => {
    const el = transcriptRef.current;
    if (!el) return;
    const onHover = (e) => {
      const span = e.target.closest('.src-span');
      if (span) {
        const cardId = span.dataset.card;
        setHoveredCard(cardId);
        setFocusedCard(cardId);
      }
    };
    const onLeave = (e) => {
      if (!e.target.closest('.src-span')) setHoveredCard(null);
    };
    el.addEventListener('mouseover', onHover);
    el.addEventListener('mouseout', onLeave);
    return () => { el.removeEventListener('mouseover', onHover); el.removeEventListener('mouseout', onLeave); };
  }, []);

  return (
    <div style={{ height: '100vh', background: T.bg, fontFamily: 'Inter, sans-serif', color: T.fg, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
      <GrainOverlay />

      {/* Header — fixed dark bar regardless of app theme, so all colors below
          are hardcoded (not theme-reactive T.*) to stay legible in light mode too */}
      <header style={{
        flexShrink: 0, zIndex: 100,
        background: 'rgba(16,13,10,0.92)', backdropFilter: 'blur(16px)',
        borderBottom: '1px solid rgba(245,241,232,0.11)',
        padding: '0 20px', height: 62,
        display: 'flex', alignItems: 'center', gap: 14,
      }}>
        <button onClick={onBack} style={{ background: 'none', border: 'none', color: 'rgba(245,241,232,0.7)', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 5, fontSize: 13, padding: 0 }}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M15 18l-6-6 6-6"/></svg>
          Painel
        </button>

        {/* Consulente — primary, with avatar */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, paddingLeft: 6, borderLeft: '1px solid rgba(245,241,232,0.11)' }}>
          <div style={{
            width: 30, height: 30, borderRadius: '50%',
            background: 'rgba(245,241,232,0.14)', border: '1.5px solid rgba(245,241,232,0.4)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            color: '#F5F1E8', fontSize: 11, fontWeight: 600, flexShrink: 0,
          }}>
            {(consulente?.name || 'Consulente').split(' ').map(w => w[0]).slice(0,2).join('')}
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', lineHeight: 1.2, minWidth: 0, maxWidth: 260 }}>
            <span style={{ fontSize: 14, color: '#F5F1E8', fontWeight: 600, whiteSpace: 'nowrap' }}>
              {consulente?.name || 'Consulente sem nome'}
            </span>
            <span style={{ fontSize: 11, color: 'rgba(245,241,232,0.7)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
              {leitura.tema}
            </span>
          </div>
        </div>
        <span style={{
          display: 'inline-flex', alignItems: 'center', gap: 5,
          padding: '3px 10px', borderRadius: 999, fontSize: 11, fontWeight: 500,
          letterSpacing: '0.04em', textTransform: 'uppercase',
          color: '#7A9EC9', background: 'rgba(122,158,201,0.16)',
        }}>
          <span style={{ width: 5, height: 5, borderRadius: '50%', background: '#7A9EC9', flexShrink: 0 }} />
          Pronto
        </span>
        <div style={{ flex: 1 }} />
        {/* Progress */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <div style={{ width: 80, height: 3, borderRadius: 999, background: 'rgba(245,241,232,0.14)', overflow: 'hidden' }}>
            <div style={{ height: '100%', background: 'linear-gradient(90deg, #8CAF88, #F5F1E8)', borderRadius: 999, width: `${(acceptedCount / totalCount) * 100}%`, transition: 'width 0.3s' }} />
          </div>
          <span style={{ fontSize: 12, color: 'rgba(245,241,232,0.7)' }}>
            <span style={{ color: '#8CAF88', fontWeight: 500 }}>{acceptedCount}</span>/{totalCount}
          </span>
        </div>
        <button onClick={onPreview} style={{
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8,
          padding: '7px 16px', background: 'transparent', color: '#F5F1E8',
          fontFamily: 'Inter, sans-serif', fontWeight: 500, fontSize: 13, borderRadius: 999,
          border: '1px solid rgba(245,241,232,0.18)', cursor: 'pointer', transition: 'background 0.15s',
        }}
        onMouseEnter={e => e.currentTarget.style.background = 'rgba(245,241,232,0.06)'}
        onMouseLeave={e => e.currentTarget.style.background = 'transparent'}
        >Pré-visualizar</button>
        <button onClick={() => setShowPublish(true)} style={{
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8,
          padding: '8px 18px', background: '#F5F1E8',
          color: '#100D0A', fontFamily: 'Inter, sans-serif', fontWeight: 600, fontSize: 13,
          borderRadius: 999, border: 'none', cursor: 'pointer', transition: 'opacity 0.15s',
        }}
        onMouseEnter={e => e.currentTarget.style.opacity = '0.88'}
        onMouseLeave={e => e.currentTarget.style.opacity = '1'}
        >Publicar</button>
        {/* Shortcuts button */}
        <span style={{ fontSize: 11, color: 'rgba(245,241,232,0.55)', display: 'flex', alignItems: 'center', gap: 5, whiteSpace: 'nowrap' }} title={session?.save_error || undefined}>
          <span style={{
            width: 5, height: 5, borderRadius: '50%',
            background: saveState === 'error' || saveState === 'unsaved' ? '#E76F51'
              : saveState === 'saving' ? '#F4A261'
              : saveState === 'nosync' ? 'rgba(245,241,232,0.3)'
              : '#8CAF88',
          }} />
          {saveState === 'saving' ? 'Salvando…'
            : saveState === 'error' ? 'Erro ao salvar — tentando de novo na próxima edição'
            : saveState === 'unsaved' ? (session?.save_error ? `Não salvo: ${session.save_error}` : 'Não foi salvo no banco')
            : saveState === 'nosync' ? 'Sem persistência (modo revisão)'
            : (savedSecsAgo < 3 ? 'Salvo agora' : `Salvo há ${savedSecsAgo}s`)}
        </span>
        <button onClick={() => setShowHistory(true)} title="Histórico de versões" style={{
          background: 'none', border: '1px solid rgba(245,241,232,0.14)', borderRadius: 999, color: 'rgba(245,241,232,0.7)',
          fontSize: 12, cursor: 'pointer', padding: '6px 12px', fontFamily: 'Inter, sans-serif',
        }}>Histórico</button>
        <button onClick={() => setShowShortcuts(true)} style={{
          width: 28, height: 28, borderRadius: '50%', background: 'rgba(245,241,232,0.06)',
          border: '1px solid rgba(245,241,232,0.11)', color: 'rgba(245,241,232,0.7)', fontSize: 12,
          cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontFamily: 'serif', fontWeight: 600,
        }}>?</button>
      </header>

      {/* Two-panel */}
      <div style={{ flex: 1, display: 'flex', overflow: 'hidden' }}>

        {/* LEFT — Cards (é o output que importa — a transcrição é referência, não o principal) */}
        <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
          {/* Layer tabs */}
          <div style={{
            padding: '0 16px', borderBottom: `1px solid ${T.border}`,
            display: 'flex', gap: 2, overflowX: 'auto', scrollbarWidth: 'none', flexShrink: 0,
          }}>
            {LAYER_TABS.map(tab => {
              const isActive = tab.id === activeTab;
              const layerCards = tab.id === 'foco_mensal' ? monthCards : cards.filter(c => c.layer === tab.id);
              const acceptedInLayer = layerCards.filter(c => cardStates[c.id] === 'accepted' || cardStates[c.id] === 'edited').length;
              return (
                <button key={tab.id} onClick={() => { setActiveTab(tab.id); setStatusFilter('all'); setFocusedCard(null); }} style={{
                  display: 'flex', alignItems: 'center', gap: 6, padding: '15px 14px 13px',
                  background: 'none', border: 'none', cursor: 'pointer',
                  borderBottom: `2px solid ${isActive ? T.accent : 'transparent'}`,
                  color: isActive ? T.accent : T.fg,
                  opacity: isActive ? 1 : 0.7,
                  fontSize: 13, fontFamily: 'Inter, sans-serif', fontWeight: isActive ? 600 : 500,
                  transition: 'color 0.15s, opacity 0.15s', whiteSpace: 'nowrap', flexShrink: 0,
                }}
                onMouseEnter={e => { if (!isActive) e.currentTarget.style.opacity = '1'; }}
                onMouseLeave={e => { if (!isActive) e.currentTarget.style.opacity = '0.7'; }}
                >
                  <span style={{ fontSize: 11 }}>{tab.icon}</span>
                  {tab.label}
                  <span style={{ fontSize: 10, padding: '1px 6px', borderRadius: 999, background: isActive ? 'rgba(244,162,97,0.16)' : 'rgba(245,241,232,0.07)', color: isActive ? T.accent : T.fgMuted, fontFamily: 'DM Mono, monospace', fontWeight: 500 }}>
                    {acceptedInLayer}/{layerCards.length}
                  </span>
                </button>
              );
            })}
          </div>

          {/* Status filter */}
          <FilterPills active={statusFilter} onChange={setStatusFilter} counts={statusCounts} />

          {/* Cards list */}
          <div
            style={{
              flex: 1, overflowY: 'auto', padding: '14px 16px',
              display: 'flex', flexDirection: 'column', gap: 9,
              scrollbarWidth: 'thin', scrollbarColor: `${T.border} transparent`,
            }}
            onClick={() => { if (document.activeElement?.tagName !== 'INPUT' && document.activeElement?.tagName !== 'TEXTAREA') setFocusedCard(null); }}
          >
            {filteredCards.length === 0 && (
              <div style={{ textAlign: 'center', padding: '40px 20px', color: T.fgDim, fontSize: 13 }}>
                Nenhum card com este filtro
              </div>
            )}

            {activeTab === 'foco_mensal' ? (
              filteredCards.map(mc => {
                const status = cardStates[mc.id] || 'suggested';
                const isExpanded = expandedCards[mc.id];
                return (
                  <MonthCard
                    key={mc.id} mc={mc} status={status} isExpanded={isExpanded}
                    onToggle={() => setExpandedCards(p => ({ ...p, [mc.id]: !p[mc.id] }))}
                    onAccept={() => setStatus(mc.id, 'accepted')}
                    onDiscard={() => setStatus(mc.id, 'discarded')}
                    onEdit={() => setStatus(mc.id, 'edited')}
                    onHighlight={() => highlightTranscript(mc.headline)}
                  />
                );
              })
            ) : (
              filteredCards.map(card => {
                const status = cardStates[card.id] || 'suggested';
                const isExpanded = expandedCards[card.id];
                const isEditing = editingCard === card.id;
                const isFocused = focusedCard === card.id;
                const isHighlighted = hoveredCard === card.id;
                return (
                  <div
                    key={card.id}
                    onClick={e => { e.stopPropagation(); setFocusedCard(card.id); }}
                  >
                    <SessionCard
                      card={{ ...card, ...(cardTexts[card.id] || {}) }}
                      status={status}
                      isExpanded={isExpanded}
                      isEditing={isEditing}
                      isFocused={isFocused}
                      isHighlighted={isHighlighted}
                      onToggle={() => setExpandedCards(p => ({ ...p, [card.id]: !p[card.id] }))}
                      onAccept={() => setStatus(card.id, 'accepted')}
                      onDiscard={() => setStatus(card.id, 'discarded')}
                      onEdit={() => setEditingCard(c => c === card.id ? null : card.id)}
                      onStopEdit={(h, s) => {
                        setCardTexts(p => ({ ...p, [card.id]: { headline: h || card.headline, summary: s || card.summary } }));
                        setEditingCard(null);
                        setStatus(card.id, 'edited');
                      }}
                      onHighlight={() => highlightTranscript(
                        (CARD_TRANSCRIPT_SPANS[card.id] || card.headline) + ' ' + card.summary
                      )}
                      onHoverIn={() => {
                        setHoveredCard(card.id);
                        // Also highlight the transcript span
                        const phrase = CARD_TRANSCRIPT_SPANS[card.id];
                        if (phrase) setHighlightedSpan(phrase);
                      }}
                      onHoverOut={() => {
                        setHoveredCard(null);
                        setHighlightedSpan(null);
                      }}
                    />
                  </div>
                );
              })
            )}
          </div>
        </div>

        {/* RIGHT — Transcript (referência de apoio, não o foco principal da tela) */}
        <div style={{
          width: '38%', flexShrink: 0, borderLeft: `1px solid ${T.border}`,
          display: 'flex', flexDirection: 'column',
        }}>
          <div style={{
            padding: '12px 20px 10px', borderBottom: `1px solid ${T.border}`,
            display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexShrink: 0,
          }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <span style={{ fontSize: 11, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.1em', color: T.fgMuted }}>Transcrição</span>
              <span style={{ fontSize: 10, padding: '2px 7px', borderRadius: 999, background: 'rgba(244,162,97,0.1)', color: T.accent }}>
                {Object.keys(CARD_TRANSCRIPT_SPANS).length} trechos vinculados
              </span>
            </div>
            {highlightedSpan && (
              <button onClick={() => setHighlightedSpan(null)} style={{ background: 'none', border: 'none', color: T.accent, fontSize: 11, cursor: 'pointer', padding: 0 }}>
                Limpar destaque ×
              </button>
            )}
          </div>

          {/* Legend */}
          <div style={{ padding: '8px 20px', borderBottom: `1px solid ${T.border}`, display: 'flex', alignItems: 'center', gap: 12, flexShrink: 0 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 5 }}>
              <span style={{ display: 'inline-block', width: 24, height: 2, background: 'rgba(244,162,97,0.5)', borderTop: '1.5px dotted rgba(244,162,97,0.5)' }} />
              <span style={{ fontSize: 10, color: T.fgDim }}>Trecho vinculado a card</span>
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 5 }}>
              <span style={{ display: 'inline-block', width: 14, height: 9, background: 'rgba(244,162,97,0.28)', borderRadius: 2 }} />
              <span style={{ fontSize: 10, color: T.fgDim }}>Card em foco</span>
            </div>
          </div>

          <div
            ref={transcriptRef}
            style={{
              flex: 1, overflowY: 'auto', padding: '22px 24px',
              fontSize: 13, color: T.fgMuted,
              scrollbarWidth: 'thin', scrollbarColor: `${T.border} transparent`,
            }}
            dangerouslySetInnerHTML={{ __html: transcriptHtml }}
          />

          <style>{`
            .ts { color: rgba(245,241,232,0.28); font-size: 11px; font-family: monospace; letter-spacing: 0.05em; }
            .src-span:hover { background: rgba(244,162,97,0.22) !important; }
          `}</style>
        </div>
      </div>

      {showPublish && (
        <PublishModal
          onClose={() => setShowPublish(false)}
          onPublish={onPublish}
          onGoToPortal={onGoToPortal}
          consulente={consulente}
          session={session}
          acceptedCount={acceptedCount}
          totalCount={totalCount}
          periodLabel={periodLabel}
          forceError={publishError}
        />
      )}
      {showShortcuts && <ShortcutsPanel onClose={() => setShowShortcuts(false)} />}
      {showHistory && <VersionHistoryPanel onClose={() => setShowHistory(false)} />}
    </div>
  );
};

Object.assign(window, { EditorScreen, PublishModal });
