/* Bespoke pages per tool — each landing has its own UI. */
const { useState: usePS, useMemo: usePM, useEffect: usePE } = React;

// --- Shared UI bits ---------------------------------------
function Field({ label, children, helper }) {
  return (
    <label style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
      <span className="mono" style={{ fontSize: 9.5, letterSpacing: '0.22em', color: 'rgba(34,197,94,0.85)' }}>
        / {label}
      </span>
      {children}
      {helper && <span style={{ fontSize: 11, color: 'rgba(255,255,255,0.4)', marginTop: 2 }}>{helper}</span>}
    </label>
  );
}

const legacyInputStyle = {
  width: '100%',
  background: 'rgba(255,255,255,0.03)',
  border: 'none',
  borderRadius: 8,
  color: '#fff',
  fontSize: 13.5,
  padding: '10px 12px',
  outline: 'none',
};

function Card({ title, sub, children, right, padding = 18 }) {
  return (
    <div className="card card-topline" style={{ padding }}>
      {(title || right) && (
        <div style={{ display: 'flex', alignItems: 'flex-start', gap: 10, marginBottom: 14 }}>
          <div style={{ flex: 1, minWidth: 0 }}>
            {title && <div style={{ fontSize: 14, fontWeight: 500, marginBottom: sub ? 4 : 0 }}>{title}</div>}
            {sub && <div style={{ fontSize: 12, color: 'rgba(255,255,255,0.55)' }}>{sub}</div>}
          </div>
          {right}
        </div>
      )}
      {children}
    </div>
  );
}

function PageHead({ eyebrow, title, sub, right }) {
  return (
    <div className="page-head">
      <div style={{ flex: 1, minWidth: 0 }}>
        <div className="page-eyebrow">/ {eyebrow}</div>
        <h1 className="page-title">{title}<span style={{ color: 'var(--green)' }}>.</span></h1>
        {sub && <p className="page-sub">{sub}</p>}
      </div>
      {right}
    </div>
  );
}

// === ATENDENTE · LOCALIZAR CONVERSA =======================
function PageConvOrigem({ tool }) {
  const [q, setQ] = usePS('');
  const [filter, setFilter] = usePS('todas');
  const results = [
    { who: 'Camila Ribeiro', cpf: '048.221.***-22', date: '03/05 14:21', via: 'WhatsApp', tag: 'venda', conv: '#A48-2210', agent: 'Pedro M.' },
    { who: 'Camila Ribeiro', cpf: '048.221.***-22', date: '28/04 09:08', via: 'Voz',      tag: 'suporte', conv: '#V12-0408', agent: 'Larissa S.' },
    { who: 'Camila Ribeiro', cpf: '048.221.***-22', date: '14/03 18:02', via: 'WhatsApp', tag: 'cadastro', conv: '#A41-1402', agent: 'Pedro M.' },
  ];
  return (
    <div className="page">
      <PageHead eyebrow={tool.tag} title={tool.title} sub={tool.desc} />
      <div className="search-jumbo">
        <Icon name="search" size={20} />
        <input value={q} onChange={e => setQ(e.target.value)}
               placeholder="Buscar por CPF, e-mail, telefone, número da conversa…" />
        <span className="kbd">↵</span>
      </div>
      <div style={{ display: 'flex', gap: 8 }}>
        {[
          { id: 'todas', label: 'Todas' },
          { id: 'venda', label: 'Vendas' },
          { id: 'suporte', label: 'Suporte' },
          { id: 'cadastro', label: 'Cadastro' },
          { id: 'voz', label: 'Voz' },
        ].map(f => (
          <button key={f.id} onClick={() => setFilter(f.id)}
                  className={`chip ${filter === f.id ? 'is-info' : ''}`}
                  style={{ cursor: 'pointer', borderColor: filter === f.id ? 'rgba(34,197,94,0.5)' : undefined,
                           color: filter === f.id ? 'var(--green)' : undefined }}>
            {f.label}
          </button>
        ))}
      </div>
      <Card title="Resultados" sub="3 conversas encontradas para CPF 048.221.***-22">
        <table className="itable">
          <thead>
            <tr><th>Conversa</th><th>Cliente</th><th>Data</th><th>Canal</th><th>Tipo</th><th>Atendente</th><th></th></tr>
          </thead>
          <tbody>
            {results.map(r => (
              <tr key={r.conv}>
                <td style={{ fontFamily: 'Geist Mono, monospace', color: 'var(--green)' }}>{r.conv}</td>
                <td>{r.who}<div style={{ fontSize: 11, color: 'rgba(255,255,255,0.4)' }}>{r.cpf}</div></td>
                <td style={{ fontFamily: 'Geist Mono, monospace', color: 'rgba(255,255,255,0.7)' }}>{r.date}</td>
                <td>{r.via}</td>
                <td><span className="chip">{r.tag.toUpperCase()}</span></td>
                <td>{r.agent}</td>
                <td><button className="btn-cta" style={{ padding: '6px 14px', fontSize: 11.5 }}>Abrir</button></td>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>
    </div>
  );
}

// === ATENDENTE · BACKLOG ==================================
function PageBacklog({ tool }) {
  const cols = [
    { title: 'Aguardando', tag: 'WAIT', accent: '#f59e0b', items: [
      { id: 'C-2210', who: 'Camila R.', sla: '+02:14', via: 'WhatsApp' },
      { id: 'C-2211', who: 'Marcos T.', sla: '+00:48', via: 'WhatsApp' },
      { id: 'C-2213', who: 'Vinicius A.', sla: '+00:12', via: 'Email' },
    ]},
    { title: 'Em atendimento', tag: 'WORK', accent: '#22c55e', items: [
      { id: 'C-2199', who: 'Beatriz G.', sla: 'em foco', via: 'WhatsApp' },
      { id: 'C-2202', who: 'Otávio L.', sla: 'em foco', via: 'Voz' },
    ]},
    { title: 'Pendente cliente', tag: 'PEND', accent: '#3b82f6', items: [
      { id: 'C-2188', who: 'Renata S.', sla: '24h', via: 'WhatsApp' },
    ]},
    { title: 'Resolvidas hoje', tag: 'DONE', accent: 'rgba(255,255,255,0.4)', items: [
      { id: 'C-2180', who: 'Henrique B.', sla: '−', via: 'WhatsApp' },
      { id: 'C-2181', who: 'Lucas P.',    sla: '−', via: 'Voz' },
      { id: 'C-2183', who: 'Paula R.',    sla: '−', via: 'Email' },
    ]},
  ];
  return (
    <div className="page">
      <PageHead eyebrow={tool.tag} title={tool.title} sub={tool.desc}
        right={<button className="btn-cta"><Icon name="rotate" size={14} /> Recarregar</button>} />
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12 }}>
        {cols.map(c => (
          <div key={c.title} className="card" style={{ padding: 14, minHeight: 360, display: 'flex', flexDirection: 'column', gap: 10 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <span style={{ width: 6, height: 6, borderRadius: 99, background: c.accent }} />
              <span style={{ fontSize: 13, fontWeight: 500 }}>{c.title}</span>
              <span style={{ flex: 1 }} />
              <span className="mono" style={{ fontSize: 9.5, letterSpacing: '0.22em', color: 'rgba(255,255,255,0.4)' }}>{c.items.length}</span>
            </div>
            {c.items.map(i => (
              <div key={i.id} style={{
                padding: 10, borderRadius: 8,
                background: 'rgba(255,255,255,0.03)',
                border: 'none',
              }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                  <span style={{ fontFamily: 'Geist Mono, monospace', fontSize: 10.5, color: 'var(--green)' }}>{i.id}</span>
                  <span style={{ flex: 1 }} />
                  <span className="mono" style={{ fontSize: 9, letterSpacing: '0.22em', color: 'rgba(255,255,255,0.4)' }}>{i.via.toUpperCase()}</span>
                </div>
                <div style={{ marginTop: 4, fontSize: 13 }}>{i.who}</div>
                <div style={{ marginTop: 4, fontFamily: 'Geist Mono, monospace', fontSize: 10.5, color: 'rgba(255,255,255,0.5)' }}>SLA {i.sla}</div>
              </div>
            ))}
          </div>
        ))}
      </div>
    </div>
  );
}

// === GESTOR · CADASTROS · RESET SENHA =====================
function PageReset({ tool }) {
  const [email, setEmail] = usePS('');
  return (
    <div className="page">
      <PageHead eyebrow={tool.tag} title={tool.title} sub={tool.desc} />
      <div className="page-cols">
        <Card title="Disparar reset" sub="O colaborador receberá um link único de 30 minutos no e-mail corporativo.">
          <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
            <Field label="E-MAIL CORPORATIVO" helper="Apenas domínios @igreen.com são aceitos.">
              <input style={legacyInputStyle} value={email} onChange={e => setEmail(e.target.value)} placeholder="ana.beatriz@igreen.com" />
            </Field>
            <Field label="MOTIVO">
              <select style={legacyInputStyle} defaultValue="esquecida">
                <option value="esquecida">Senha esquecida</option>
                <option value="bloqueio">Conta bloqueada</option>
                <option value="trocaobr">Troca obrigatória</option>
              </select>
            </Field>
            <label style={{ display: 'flex', gap: 8, alignItems: 'center', fontSize: 12.5, color: 'rgba(255,255,255,0.7)' }}>
              <input type="checkbox" defaultChecked /> Forçar troca no primeiro acesso
            </label>
            <button className="btn-cta" style={{ alignSelf: 'flex-start' }}>
              <Icon name="key" size={14} /> Disparar reset
            </button>
          </div>
        </Card>
        <Card title="O que acontece" sub="Sequência segura, com auditoria.">
          <ol style={{ margin: 0, padding: 0, listStyle: 'none', display: 'flex', flexDirection: 'column', gap: 10 }}>
            {[
              'Verificamos que o e-mail pertence a um colaborador ativo',
              'Geramos um token criptográfico válido por 30 minutos',
              'Enviamos um link único pelo provedor SES corporativo',
              'Sessões anteriores são invalidadas no próximo login',
              'Evento `auth.password.reset` é registrado em audit.log',
            ].map((s, i) => (
              <li key={i} style={{ display: 'flex', gap: 10 }}>
                <span style={{
                  width: 22, height: 22, flexShrink: 0,
                  borderRadius: 99, background: 'rgba(34,197,94,0.10)',
                  border: 'none',
                  color: 'var(--green)', fontFamily: 'Geist Mono, monospace', fontSize: 10.5,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                }}>{i + 1}</span>
                <span style={{ fontSize: 12.5, color: 'rgba(255,255,255,0.75)', lineHeight: 1.5 }}>{s}</span>
              </li>
            ))}
          </ol>
        </Card>
      </div>
    </div>
  );
}

// === GESTOR · CADASTROS · CRIAR ===========================
function PageCriar({ tool }) {
  return (
    <div className="page">
      <PageHead eyebrow={tool.tag} title={tool.title} sub={tool.desc} />
      <div className="page-cols">
        <Card title="Dados do colaborador">
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
            <Field label="NOME"><input style={legacyInputStyle} placeholder="Henrique de Sá" /></Field>
            <Field label="CPF"><input style={legacyInputStyle} placeholder="000.000.000-00" /></Field>
            <Field label="E-MAIL CORPORATIVO" helper="Recebe o convite de primeiro acesso.">
              <input style={legacyInputStyle} placeholder="henrique.sa@igreen.com" /></Field>
            <Field label="TIME">
              <select style={legacyInputStyle} defaultValue="sac">
                <option value="sac">SAC</option><option value="vendas">Vendas</option>
                <option value="cs">Customer Success</option><option value="fin">Financeiro</option>
              </select>
            </Field>
            <Field label="ROLE">
              <select style={legacyInputStyle} defaultValue="atendente">
                <option value="atendente">Atendente</option><option value="supervisor">Supervisor</option>
                <option value="gestor">Gestor</option><option value="admin">Admin</option>
              </select>
            </Field>
            <Field label="NÍVEL">
              <select style={legacyInputStyle} defaultValue="n1">
                <option value="n1">N1</option><option value="n2">N2</option>
              </select>
            </Field>
          </div>
        </Card>
        <Card title="Permissões aplicadas" sub="Calculadas automaticamente a partir de role + nível.">
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {[
              ['Acessar próprio backlog', true],
              ['Ver conversas do time', true],
              ['Reatribuir conversas no time', false],
              ['Resetar senha de outros', false],
              ['Acessar relatórios financeiros', false],
              ['Configurar integrações', false],
            ].map(([k, v]) => (
              <div key={k} style={{
                display: 'flex', alignItems: 'center', gap: 10,
                padding: '7px 10px', borderRadius: 7,
                background: 'rgba(255,255,255,0.03)',
              }}>
                <span style={{
                  width: 16, height: 16, borderRadius: 4,
                  background: v ? 'rgba(34,197,94,0.15)' : 'rgba(255,255,255,0.04)',
                  border: '1px solid ' + (v ? 'rgba(34,197,94,0.4)' : 'transparent'),
                  color: v ? 'var(--green)' : 'rgba(255,255,255,0.3)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  fontSize: 10,
                }}>{v ? '✓' : '·'}</span>
                <span style={{ fontSize: 13, color: 'rgba(255,255,255,0.85)' }}>{k}</span>
              </div>
            ))}
            <button className="btn-cta" style={{ marginTop: 10, alignSelf: 'flex-start' }}>
              <Icon name="userPlus" size={14} /> Provisionar acesso
            </button>
          </div>
        </Card>
      </div>
    </div>
  );
}

// === GESTOR · CADASTROS · ROLE ============================
function PageRole({ tool }) {
  const [from, setFrom] = usePS('atendente');
  const [to, setTo] = usePS('supervisor');
  const matrix = [
    ['Backlog próprio', true, true, true, true],
    ['Backlog do time', false, true, true, true],
    ['Reatribuir conversa', false, true, true, true],
    ['Reset de senha', false, false, true, true],
    ['Criar cadastro', false, false, true, true],
    ['Editar role/nível', false, false, false, true],
    ['Configurar integrações', false, false, false, true],
  ];
  return (
    <div className="page">
      <PageHead eyebrow={tool.tag} title={tool.title} sub={tool.desc} />
      <Card>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr auto 1fr auto', gap: 14, alignItems: 'end' }}>
          <Field label="COLABORADOR"><input style={legacyInputStyle} placeholder="Buscar por nome ou e-mail" defaultValue="Ana Beatriz · ana.beatriz@igreen.com" /></Field>
          <div style={{ paddingBottom: 10, color: 'rgba(255,255,255,0.4)' }}>›</div>
          <Field label="DE → PARA">
            <div style={{ display: 'flex', gap: 8 }}>
              <select style={legacyInputStyle} value={from} onChange={e => setFrom(e.target.value)}>
                <option value="atendente">Atendente</option>
                <option value="supervisor">Supervisor</option>
                <option value="gestor">Gestor</option>
              </select>
              <select style={legacyInputStyle} value={to} onChange={e => setTo(e.target.value)}>
                <option value="atendente">Atendente</option>
                <option value="supervisor">Supervisor</option>
                <option value="gestor">Gestor</option>
                <option value="admin">Admin</option>
              </select>
            </div>
          </Field>
          <button className="btn-cta"><Icon name="shield" size={14} /> Aplicar</button>
        </div>
      </Card>
      <Card title="Matriz de permissões" sub="✓ liberado · — bloqueado">
        <table className="itable">
          <thead>
            <tr><th>Permissão</th><th>Atendente</th><th>Supervisor</th><th>Gestor</th><th>Admin</th></tr>
          </thead>
          <tbody>
            {matrix.map(([k, ...vs]) => (
              <tr key={k}>
                <td>{k}</td>
                {vs.map((v, i) => (
                  <td key={i} style={{
                    color: v ? 'var(--green)' : 'rgba(255,255,255,0.25)',
                    fontFamily: 'Geist Mono, monospace',
                    background: ['atendente', 'supervisor', 'gestor', 'admin'][i] === to ? 'rgba(34,197,94,0.05)' : 'transparent',
                  }}>{v ? '✓' : '—'}</td>
                ))}
              </tr>
            ))}
          </tbody>
        </table>
      </Card>
    </div>
  );
}

// === GESTOR · CADASTROS · NÍVEL ===========================
function PageNivel({ tool }) {
  return (
    <div className="page">
      <PageHead eyebrow={tool.tag} title={tool.title} sub={tool.desc} />
      <div className="page-cols">
        <Card title="Promover colaborador" sub="N1 → N2 desbloqueia atendimentos de maior complexidade.">
          <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
            <Field label="COLABORADOR"><input style={legacyInputStyle} placeholder="Buscar…" defaultValue="Pedro Mendes" /></Field>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 24px 1fr', gap: 10, alignItems: 'center' }}>
              <div style={{
                padding: 14, border: 'none', borderRadius: 10, textAlign: 'center',
              }}>
                <div className="mono" style={{ fontSize: 9.5, letterSpacing: '0.22em', color: 'rgba(255,255,255,0.4)' }}>NÍVEL ATUAL</div>
                <div style={{ fontSize: 26, fontWeight: 300, marginTop: 4 }}>N1</div>
              </div>
              <div style={{ textAlign: 'center', color: 'var(--green)', fontSize: 18 }}>→</div>
              <div style={{
                padding: 14, border: 'none',
                background: 'rgba(34,197,94,0.06)',
                borderRadius: 10, textAlign: 'center',
              }}>
                <div className="mono" style={{ fontSize: 9.5, letterSpacing: '0.22em', color: 'var(--green)' }}>NOVO NÍVEL</div>
                <div style={{ fontSize: 26, fontWeight: 300, marginTop: 4, color: 'var(--green)' }}>N2</div>
              </div>
            </div>
            <Field label="JUSTIFICATIVA">
              <textarea style={{ ...legacyInputStyle, minHeight: 80, resize: 'vertical' }}
                        defaultValue="3 meses consecutivos com CSAT acima de 92% e TMA dentro da meta." />
            </Field>
            <button className="btn-cta" style={{ alignSelf: 'flex-start' }}>
              <Icon name="zap" size={14} /> Aplicar promoção
            </button>
          </div>
        </Card>
        <Card title="O que muda em N2">
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8, fontSize: 13 }}>
            {[
              ['Atendimentos críticos', '+ liberado'],
              ['Aprovação de descontos', 'até 15%'],
              ['Reatribuir conversas', '+ liberado'],
              ['Faixa salarial', 'tier B → tier C'],
              ['Treinamentos requeridos', 'TR-N2 (concluído ✓)'],
            ].map(([k, v]) => (
              <div key={k} style={{ display: 'flex', justifyContent: 'space-between',
                padding: '8px 10px', borderRadius: 6, background: 'rgba(255,255,255,0.025)' }}>
                <span style={{ color: 'rgba(255,255,255,0.7)' }}>{k}</span>
                <span style={{ color: 'var(--green)', fontFamily: 'Geist Mono, monospace', fontSize: 12 }}>{v}</span>
              </div>
            ))}
          </div>
        </Card>
      </div>
    </div>
  );
}

// === GESTOR · FAMÍLIAS · TRANSFER LIST ====================
function TransferList({ leftTitle, rightTitle, left, right }) {
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1fr 32px 1fr', gap: 12, alignItems: 'stretch' }}>
      {[{ title: leftTitle, items: left }, null, { title: rightTitle, items: right }].map((c, k) => {
        if (c === null) return (
          <div key="mid" style={{ display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'center', gap: 6 }}>
            <button style={{ width: 32, height: 28, borderRadius: 6, background: 'rgba(255,255,255,0.04)', border: 'none', color: 'rgba(255,255,255,0.5)' }}>›</button>
            <button style={{ width: 32, height: 28, borderRadius: 6, background: 'rgba(255,255,255,0.04)', border: 'none', color: 'rgba(255,255,255,0.5)' }}>‹</button>
          </div>
        );
        return (
          <div key={c.title} style={{ background: 'rgba(255,255,255,0.025)', border: 'none', borderRadius: 10, overflow: 'hidden' }}>
            <div style={{ padding: '10px 12px', borderBottom: '1px solid rgba(255,255,255,0.03)', display: 'flex', alignItems: 'center', gap: 8 }}>
              <span className="mono" style={{ fontSize: 10, letterSpacing: '0.22em', color: 'rgba(255,255,255,0.5)' }}>{c.title}</span>
              <span style={{ flex: 1 }} />
              <span className="mono" style={{ fontSize: 9.5, color: 'rgba(255,255,255,0.4)' }}>{c.items.length}</span>
            </div>
            <div style={{ padding: 6, display: 'flex', flexDirection: 'column', gap: 2, maxHeight: 320, overflow: 'auto' }}>
              {c.items.map(i => (
                <button key={i} style={{
                  textAlign: 'left', padding: '8px 10px', borderRadius: 6,
                  background: 'transparent', border: '1px solid transparent',
                  color: 'rgba(255,255,255,0.85)', fontSize: 12.5, cursor: 'pointer',
                }}
                onMouseEnter={e => e.currentTarget.style.background = 'rgba(34,197,94,0.08)'}
                onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
                  {i}
                </button>
              ))}
            </div>
          </div>
        );
      })}
    </div>
  );
}

function PageFamCol({ tool }) {
  return (
    <div className="page">
      <PageHead eyebrow={tool.tag} title={tool.title} sub={tool.desc} />
      <Card title="Pedro Mendes · Atendente N2 · SAC"
            sub="Selecione famílias do lado esquerdo e mova para a direita para vincular.">
        <TransferList
          leftTitle="DISPONÍVEIS · 24"
          rightTitle="ATRIBUÍDAS · 6"
          left={[
            'Família CRESOL', 'Família COOPENERGI', 'Família COCAMAR',
            'Família COOPAVEL', 'Família CASTROLANDA', 'Família COOPERSOL',
            'Família COOPATOS', 'Família CAMNPAL', 'Família UNIMED LITORAL',
            'Família FRIMESA', 'Família COCARI',
          ]}
          right={[
            'Família COOPERMOTA', 'Família AURORA', 'Família COTRIPAL',
            'Família LAR', 'Família INTEGRADA', 'Família COAMO',
          ]}
        />
      </Card>
    </div>
  );
}

function PageFamTime({ tool }) {
  const grid = [
    { time: 'SAC · Time A', fam: ['COAMO', 'AURORA', 'LAR'], total: 18 },
    { time: 'SAC · Time B', fam: ['COTRIPAL', 'INTEGRADA'], total: 12 },
    { time: 'SAC · Voz',    fam: ['COOPERMOTA', 'CRESOL'], total: 9 },
    { time: 'CS · Enterprise', fam: ['UNIMED LITORAL', 'FRIMESA'], total: 4 },
    { time: 'Vendas · SP',  fam: ['COCAMAR', 'COCARI'], total: 7 },
  ];
  return (
    <div className="page">
      <PageHead eyebrow={tool.tag} title={tool.title} sub={tool.desc}
        right={<button className="btn-cta"><Icon name="link" size={14} /> Novo vínculo</button>} />
      <Card title="Times × Famílias" sub="5 vínculos ativos. Clique em uma linha para editar.">
        <table className="itable">
          <thead><tr><th>Time</th><th>Famílias atribuídas</th><th>Atendentes</th><th></th></tr></thead>
          <tbody>
            {grid.map(g => (
              <tr key={g.time}>
                <td style={{ fontWeight: 500 }}>{g.time}</td>
                <td>
                  <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                    {g.fam.map(f => <span key={f} className="chip">{f}</span>)}
                  </div>
                </td>
                <td style={{ fontFamily: 'Geist Mono, monospace', color: 'var(--green)' }}>{g.total}</td>
                <td><span className="mono" style={{ fontSize: 10, letterSpacing: '0.22em', color: 'rgba(255,255,255,0.4)' }}>EDITAR ↗</span></td>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>
    </div>
  );
}

function PageFamForn({ tool }) {
  const supps = [
    { name: 'CPFL Energia',   region: 'SP · Interior', fams: 8, status: 'ok' },
    { name: 'Enel Distribuição São Paulo', region: 'SP · Capital', fams: 5, status: 'ok' },
    { name: 'Energisa',       region: 'MS · Sul',      fams: 4, status: 'attn' },
    { name: 'Equatorial',     region: 'MA · PA · PI',  fams: 6, status: 'ok' },
    { name: 'Light',          region: 'RJ · Capital',  fams: 3, status: 'attn' },
    { name: 'Cemig',          region: 'MG',            fams: 7, status: 'ok' },
  ];
  return (
    <div className="page">
      <PageHead eyebrow={tool.tag} title={tool.title} sub={tool.desc} />
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(260px,1fr))', gap: 12 }}>
        {supps.map(s => (
          <div key={s.name} className="card card-topline" style={{ padding: 16 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 10 }}>
              <div style={{ width: 32, height: 32, borderRadius: 8,
                background: 'rgba(59,130,246,0.10)', border: 'none',
                color: 'var(--info)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                <Icon name="plug" size={15} />
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 13.5, fontWeight: 500 }}>{s.name}</div>
                <div className="mono" style={{ fontSize: 9.5, letterSpacing: '0.22em', color: 'rgba(255,255,255,0.4)' }}>{s.region.toUpperCase()}</div>
              </div>
              <span className={`chip ${s.status === 'attn' ? 'is-warn' : ''}`}>{s.status === 'ok' ? 'OK' : 'ATENÇÃO'}</span>
            </div>
            <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginTop: 4 }}>
              <span style={{ fontSize: 22, fontWeight: 300 }}>{s.fams}</span>
              <span style={{ fontSize: 12, color: 'rgba(255,255,255,0.5)' }}>famílias atribuídas</span>
            </div>
            <button className="mono" style={{
              marginTop: 12, fontSize: 9.5, letterSpacing: '0.22em',
              padding: '6px 0', background: 'transparent', border: 'none',
              color: 'var(--green)', cursor: 'pointer', textAlign: 'left',
            }}>GERENCIAR VÍNCULOS ↗</button>
          </div>
        ))}
      </div>
    </div>
  );
}

// === GESTOR · OPERAÇÃO ====================================
function PageAlertas({ tool }) {
  const rules = [
    { name: 'TMA acima de 8 minutos', who: 'SAC · Time A', chan: 'Slack #ops', state: 'on' },
    { name: 'Fila estagnada > 50',    who: 'Todos os times', chan: 'E-mail · supervisor', state: 'on' },
    { name: 'Atendente ocioso > 12min', who: 'SAC',         chan: 'Push · supervisor', state: 'on' },
    { name: 'CSAT diário < 80%',      who: 'Todos os times', chan: 'Slack #qualidade', state: 'on' },
    { name: 'Sessão sem resposta 2h', who: 'CS · Enterprise', chan: 'Slack #ops', state: 'paused' },
    { name: 'Volume voz +30%/hora',   who: 'SAC · Voz',     chan: 'Slack #ops', state: 'on' },
  ];
  return (
    <div className="page">
      <PageHead eyebrow={tool.tag} title={tool.title} sub={tool.desc}
        right={<button className="btn-cta"><Icon name="bell" size={14} /> Nova regra</button>} />
      <Card title="Regras ativas" sub="6 alertas configurados.">
        {rules.map((r, k) => (
          <div key={r.name} style={{
            display: 'grid', gridTemplateColumns: 'auto 1fr 200px 200px auto', gap: 14, alignItems: 'center',
            padding: '12px 4px', borderTop: k ? '1px dashed rgba(255,255,255,0.06)' : 'none',
          }}>
            <span style={{
              width: 32, height: 32, display: 'flex', alignItems: 'center', justifyContent: 'center',
              borderRadius: 8, background: 'rgba(245,158,11,0.10)', border: 'none',
              color: 'var(--warning)',
            }}><Icon name="bell" size={14} /></span>
            <div>
              <div style={{ fontSize: 13.5 }}>{r.name}</div>
              <div className="mono" style={{ fontSize: 9.5, letterSpacing: '0.22em', color: 'rgba(255,255,255,0.4)', marginTop: 2 }}>{r.who.toUpperCase()}</div>
            </div>
            <div style={{ fontSize: 12, color: 'rgba(255,255,255,0.6)' }}>{r.chan}</div>
            <span className={`chip ${r.state === 'paused' ? 'is-warn' : ''}`}>{r.state === 'on' ? 'ATIVA' : 'PAUSADA'}</span>
            <span className="mono" style={{ fontSize: 10, letterSpacing: '0.22em', color: 'rgba(255,255,255,0.4)' }}>EDITAR ↗</span>
          </div>
        ))}
      </Card>
    </div>
  );
}

function PageRelat({ tool }) {
  const rows = [
    { who: 'Pedro Mendes',    team: 'SAC · A', res: 412, tma: '4:21', csat: '94%' },
    { who: 'Larissa Souza',   team: 'SAC · A', res: 378, tma: '4:48', csat: '91%' },
    { who: 'Marina Coelho',   team: 'SAC · A', res: 366, tma: '4:55', csat: '93%' },
    { who: 'Otávio Lins',     team: 'SAC · B', res: 340, tma: '5:12', csat: '88%' },
    { who: 'Beatriz Galvão',  team: 'SAC · B', res: 318, tma: '5:24', csat: '90%' },
  ];
  return (
    <div className="page">
      <PageHead eyebrow={tool.tag} title={tool.title} sub={tool.desc}
        right={<div style={{ display: 'flex', gap: 8 }}>
          <button className="btn-cta" style={{ background: 'rgba(255,255,255,0.05)', color: '#fff', border: 'none', boxShadow: 'none' }}>
            <Icon name="download" size={14} /> CSV
          </button>
          <button className="btn-cta"><Icon name="download" size={14} /> Exportar PDF</button>
        </div>} />
      <Card>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12 }}>
          <Field label="PERÍODO">
            <select style={legacyInputStyle} defaultValue="mes"><option value="dia">Hoje</option><option value="semana">Últimos 7 dias</option><option value="mes">Este mês</option><option value="trimestre">Trimestre</option></select>
          </Field>
          <Field label="EQUIPE">
            <select style={legacyInputStyle} defaultValue="todos"><option value="todos">Todas</option><option value="a">SAC · A</option><option value="b">SAC · B</option><option value="cs">CS</option></select>
          </Field>
          <Field label="MÉTRICA">
            <select style={legacyInputStyle} defaultValue="resol"><option value="resol">Resoluções</option><option value="tma">TMA</option><option value="csat">CSAT</option></select>
          </Field>
          <Field label="AGRUPAR POR">
            <select style={legacyInputStyle} defaultValue="pessoa"><option value="pessoa">Colaborador</option><option value="time">Equipe</option><option value="canal">Canal</option></select>
          </Field>
        </div>
      </Card>
      <Card title="Resoluções por colaborador · Maio/26" sub="1.814 resoluções no período. CSAT médio 91,2%.">
        <table className="itable">
          <thead><tr><th>Colaborador</th><th>Equipe</th><th style={{ textAlign: 'right' }}>Resoluções</th><th>TMA</th><th>CSAT</th></tr></thead>
          <tbody>
            {rows.map(r => (
              <tr key={r.who}>
                <td>{r.who}</td>
                <td><span className="chip">{r.team.toUpperCase()}</span></td>
                <td style={{ textAlign: 'right', fontFamily: 'Geist Mono, monospace', color: 'var(--green)' }}>{r.res}</td>
                <td style={{ fontFamily: 'Geist Mono, monospace' }}>{r.tma}</td>
                <td style={{ fontFamily: 'Geist Mono, monospace' }}>{r.csat}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>
    </div>
  );
}

function PageLinkSAC({ tool }) {
  return (
    <div className="page">
      <PageHead eyebrow={tool.tag} title={tool.title} sub={tool.desc} />
      <Card>
        <div style={{ textAlign: 'center', padding: '40px 20px' }}>
          <div style={{
            width: 72, height: 72, margin: '0 auto 20px',
            borderRadius: 16, background: 'rgba(59,130,246,0.10)', border: 'none',
            color: 'var(--info)', display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}><Icon name="link" size={28} /></div>
          <h2 style={{ fontSize: 20, fontWeight: 400, margin: 0 }}>Painel SAC · ao vivo</h2>
          <p style={{ fontSize: 13, color: 'rgba(255,255,255,0.55)', maxWidth: 460, margin: '8px auto 18px', lineHeight: 1.55 }}>
            O dashboard de suporte ao cliente é mantido em ferramenta externa.
            Você sai da Central e abre o painel em uma nova aba.
          </p>
          <button className="btn-cta">Abrir painel SAC ↗</button>
          <div className="mono" style={{ fontSize: 9.5, letterSpacing: '0.22em', color: 'rgba(255,255,255,0.4)', marginTop: 18 }}>
            sac.igreen.com/painel · SSO ATIVADO
          </div>
        </div>
      </Card>
    </div>
  );
}

// === LIDERANÇA · DASHBOARDS ===============================
function MiniSparkline({ points, color, height = 38, fill = true }) {
  const w = 240, h = height;
  const max = Math.max(...points), min = Math.min(...points);
  const span = max - min || 1;
  const xs = points.map((_, i) => (i / (points.length - 1)) * w);
  const ys = points.map(p => h - ((p - min) / span) * (h - 6) - 3);
  const line = xs.map((x, i) => `${i ? 'L' : 'M'}${x.toFixed(1)},${ys[i].toFixed(1)}`).join(' ');
  const area = `${line} L${w},${h} L0,${h} Z`;
  return (
    <svg viewBox={`0 0 ${w} ${h}`} preserveAspectRatio="none" style={{ width: '100%', height }}>
      {fill && <path d={area} fill={color} fillOpacity="0.12" />}
      <path d={line} fill="none" stroke={color} strokeWidth="1.5" />
    </svg>
  );
}

function BigStat({ label, value, sub, color = '#22c55e', spark }) {
  return (
    <div className="card card-topline" style={{ padding: 18 }}>
      <div className="mono" style={{ fontSize: 9.5, letterSpacing: '0.32em', color: 'rgba(255,255,255,0.5)' }}>/ {label}</div>
      <div style={{ fontSize: 32, fontWeight: 300, marginTop: 6, color }}>{value}</div>
      {sub && <div style={{ fontSize: 12, color: 'rgba(255,255,255,0.55)', marginTop: 4 }}>{sub}</div>}
      {spark && <div style={{ marginTop: 12 }}><MiniSparkline points={spark} color={color} /></div>}
    </div>
  );
}

function PageFin({ tool }) {
  return (
    <div className="page">
      <PageHead eyebrow={tool.tag} title={tool.title} sub={tool.desc} />
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14 }}>
        <BigStat label="MRR" value="R$ 4,82M" sub="+ 8,4% MoM" color="#22c55e" spark={[3.8,3.9,4.0,4.1,4.2,4.3,4.4,4.5,4.6,4.7,4.78,4.82]} />
        <BigStat label="CHURN FIN." value="2,1%" sub="meta 2,5%" color="#22c55e" spark={[3.2,3.0,2.8,2.9,2.6,2.5,2.3,2.4,2.2,2.1,2.1,2.1]} />
        <BigStat label="INADIMPLÊNCIA" value="R$ 312k" sub="− R$ 41k vs abr" color="#f59e0b" spark={[420,410,400,395,380,370,365,355,340,330,320,312]} />
        <BigStat label="CAC" value="R$ 188" sub="payback 9 meses" color="#3b82f6" spark={[230,225,220,215,210,205,200,198,195,193,190,188]} />
      </div>
      <Card title="Receita por família · 12 meses">
        <MiniSparkline height={120} points={[2.1,2.3,2.4,2.6,2.8,3.0,3.3,3.5,3.8,4.1,4.5,4.82]} color="#22c55e" />
      </Card>
    </div>
  );
}

function PageIA({ tool }) {
  return (
    <div className="page">
      <PageHead eyebrow={tool.tag} title={tool.title} sub={tool.desc} />
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14 }}>
        <BigStat label="DEFLEXÃO IA" value="64%" sub="conversas resolvidas sem humano" color="#22c55e" spark={[40,42,45,48,50,52,55,57,58,60,62,64]} />
        <BigStat label="QUALIDADE" value="4,7 / 5" sub="avaliação pós-conversa" color="#22c55e" spark={[4.2,4.3,4.3,4.4,4.5,4.5,4.6,4.6,4.6,4.7,4.7,4.7]} />
        <BigStat label="LATÊNCIA P95" value="1,2s" sub="meta < 2s" color="#3b82f6" spark={[2.1,2.0,1.8,1.7,1.5,1.5,1.4,1.4,1.3,1.3,1.2,1.2]} />
        <BigStat label="CUSTO / SESSÃO" value="R$ 0,18" sub="− 22% vs jan" color="#22c55e" spark={[0.32,0.30,0.28,0.27,0.25,0.24,0.23,0.22,0.21,0.20,0.19,0.18]} />
      </div>
      <Card title="Distribuição de intenções resolvidas">
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {[
            ['Segunda-via de fatura', 38],
            ['Status do cadastro',    22],
            ['Esclarecimentos comerciais', 18],
            ['Trocar dados de contato', 12],
            ['Outros',                10],
          ].map(([k, v]) => (
            <div key={k} style={{ display: 'grid', gridTemplateColumns: '220px 1fr 50px', gap: 12, alignItems: 'center' }}>
              <span style={{ fontSize: 12.5 }}>{k}</span>
              <div style={{ height: 8, background: 'rgba(255,255,255,0.05)', borderRadius: 99, overflow: 'hidden' }}>
                <div style={{ width: `${v}%`, height: '100%',
                  background: 'linear-gradient(90deg, #22c55e, #16a34a)' }} />
              </div>
              <span style={{ fontFamily: 'Geist Mono, monospace', fontSize: 11, color: 'rgba(255,255,255,0.7)', textAlign: 'right' }}>{v}%</span>
            </div>
          ))}
        </div>
      </Card>
    </div>
  );
}

function PageProd({ tool }) {
  const teams = [
    { team: 'SAC · A',     score: 94, tma: '4:32', vol: 1820 },
    { team: 'SAC · B',     score: 89, tma: '5:08', vol: 1640 },
    { team: 'SAC · Voz',   score: 91, tma: '6:12', vol: 920 },
    { team: 'CS Enterprise', score: 96, tma: '8:48', vol: 320 },
    { team: 'Vendas · SP', score: 87, tma: '3:55', vol: 540 },
  ];
  return (
    <div className="page">
      <PageHead eyebrow={tool.tag} title={tool.title} sub={tool.desc} />
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 14 }}>
        <BigStat label="ÍNDICE GERAL" value="91" sub="produtividade composta" color="#22c55e" spark={[82,84,85,86,87,88,89,89,90,90,91,91]} />
        <BigStat label="TMA MÉDIO" value="5:14" sub="− 0:42 vs abr" color="#22c55e" spark={[6.2,6.1,5.9,5.8,5.6,5.5,5.4,5.3,5.3,5.2,5.2,5.14]} />
        <BigStat label="VOLUME · MAIO" value="5.240" sub="conversas resolvidas" color="#3b82f6" spark={[3800,4000,4200,4400,4500,4700,4800,4900,5000,5100,5200,5240]} />
      </div>
      <Card title="Comparativo por equipe">
        <table className="itable">
          <thead><tr><th>Equipe</th><th>Índice</th><th>TMA</th><th>Volume</th><th>Tendência</th></tr></thead>
          <tbody>
            {teams.map(t => (
              <tr key={t.team}>
                <td style={{ fontWeight: 500 }}>{t.team}</td>
                <td>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                    <div style={{ width: 120, height: 6, background: 'rgba(255,255,255,0.06)', borderRadius: 99, overflow: 'hidden' }}>
                      <div style={{ width: `${t.score}%`, height: '100%', background: t.score >= 90 ? '#22c55e' : t.score >= 85 ? '#3b82f6' : '#f59e0b' }} />
                    </div>
                    <span style={{ fontFamily: 'Geist Mono, monospace', fontSize: 12, color: 'rgba(255,255,255,0.85)' }}>{t.score}</span>
                  </div>
                </td>
                <td style={{ fontFamily: 'Geist Mono, monospace' }}>{t.tma}</td>
                <td style={{ fontFamily: 'Geist Mono, monospace', color: 'var(--green)' }}>{t.vol.toLocaleString('pt-BR')}</td>
                <td style={{ width: 140 }}>
                  <MiniSparkline height={26} fill={false}
                    points={Array.from({ length: 12 }, (_, i) => t.score - 5 + Math.sin(i + t.score) * 3 + i * 0.4)}
                    color="#22c55e" />
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>
    </div>
  );
}

// === REPORTS · Feed + Em desenvolvimento =================
const MOCK_NEWS = [
  { date: '13/05 · 09:14', tag: 'release', tagTone: 'safe',
    title: 'Resumo automático de conversas agora em produção',
    body: 'Toda conversa encerrada gera um resumo de 3 linhas, com tags, alimentando relatórios e auditoria. Olhe a página da conversa para conferir.',
    by: 'Time Suporte Tech & IA' },
  { date: '12/05 · 17:42', tag: 'fix', tagTone: 'info',
    title: 'Bot voltou a classificar fatura corretamente',
    body: 'Ajustamos o prompt do classificador. Bug que mandava "fatura" para a fila de cancelamento foi resolvido após o pico de 10/05.',
    by: 'Renan Tavares' },
  { date: '11/05 · 14:00', tag: 'aviso', tagTone: 'warn',
    title: 'Janela de manutenção · sexta 16/05 das 22h às 00h',
    body: 'Banco será migrado para nova versão. Atendimentos serão pausados e enfileirados. Não há perda de mensagens.',
    by: 'Infra' },
  { date: '09/05 · 11:20', tag: 'release', tagTone: 'safe',
    title: 'Dashboard de produtividade ganhou comparativo por equipe',
    body: 'A nova visão Liderança mostra índice, TMA e volume lado-a-lado com mini-tendências de 12 semanas.',
    by: 'Time Produto' },
  { date: '07/05 · 16:55', tag: 'estudo', tagTone: 'info',
    title: 'Detector de frustração: resultados do primeiro AB-test',
    body: 'Conversas com sinal de irritação foram priorizadas em 41% dos casos. CSAT subiu 6pp nesse subset. Decidimos seguir para piloto amplo.',
    by: 'Vitor Andrade' },
  { date: '03/05 · 10:08', tag: 'fix', tagTone: 'info',
    title: 'Assinatura "iGreen Solar" vs "iGreen Energia"',
    body: 'O bot misturava assinaturas em respostas longas. Corrigido e validado em 5 famílias.',
    by: 'Renan Tavares' },
];

function NewsTag({ tag, tone }) {
  const cls = tone === 'safe' ? '' : tone === 'warn' ? 'is-warn' : 'is-info';
  return <span className={`chip ${cls}`} style={{ fontSize: 9, padding: '0 7px', height: 20 }}>{tag.toUpperCase()}</span>;
}

function PageReports() {
  return (
    <div className="page">
      <PageHead eyebrow="REPORTS · DESENVOLVIMENTO" title="Acompanhe o que mudou"
        sub="Releases, correções, avisos e estudos da Central. Atualizado pelo time de Tech & IA e Produto."
        right={<span className="chip"><span className="dot-pulse" /> 3 EM ANDAMENTO</span>} />

      <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 18, alignItems: 'flex-start' }}>
        {/* News feed */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          <div className="mono" style={{ fontSize: 10, letterSpacing: '0.32em', color: 'rgba(255,255,255,0.5)' }}>
            / FEED · ÚLTIMOS 30 DIAS
          </div>
          {MOCK_NEWS.map((n, k) => (
            <article key={k} className="card card-topline" style={{ padding: 18 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 8 }}>
                <span className="mono" style={{ fontSize: 10, letterSpacing: '0.22em', color: 'rgba(34,197,94,0.85)' }}>
                  {n.date}
                </span>
                <span style={{ flex: 1 }} />
                <NewsTag tag={n.tag} tone={n.tagTone} />
              </div>
              <h3 style={{ margin: '0 0 6px', fontSize: 16, fontWeight: 500, letterSpacing: '-0.005em' }}>
                {n.title}
              </h3>
              <p style={{ margin: 0, fontSize: 13, color: 'rgba(255,255,255,0.7)', lineHeight: 1.55 }}>
                {n.body}
              </p>
              <div className="mono" style={{ fontSize: 9.5, letterSpacing: '0.22em', color: 'rgba(255,255,255,0.4)', marginTop: 12 }}>
                — {n.by.toUpperCase()}
              </div>
            </article>
          ))}
          <button style={{
            padding: '10px 16px', borderRadius: 8,
            background: 'rgba(255,255,255,0.03)',
            border: 'none',
            color: 'rgba(255,255,255,0.65)', cursor: 'pointer',
            fontSize: 12.5,
          }}>Carregar mais</button>
        </div>

        {/* Em desenvolvimento (sticky aside) */}
        <aside style={{ display: 'flex', flexDirection: 'column', gap: 12, position: 'sticky', top: 16 }}>
          <div style={{
            padding: '12px 14px', borderRadius: 10,
            background: 'rgba(34,197,94,0.06)',
            border: 'none',
            display: 'flex', alignItems: 'center', gap: 10,
          }}>
            <span className="dot-pulse" style={{ width: 7, height: 7 }} />
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 12.5, fontWeight: 500 }}>Sprint 26 · 06–17 mai</div>
              <div style={{ fontSize: 11, color: 'rgba(255,255,255,0.55)', marginTop: 1 }}>
                3 frentes em andamento
              </div>
            </div>
          </div>

          <div className="mono" style={{ fontSize: 10, letterSpacing: '0.32em', color: 'rgba(255,255,255,0.5)' }}>
            / EM DESENVOLVIMENTO
          </div>

          {MOCK_DEV.map(epic => (
            <div key={epic.id} className="card" style={{ padding: 14 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <span style={{ fontFamily: 'Geist Mono, monospace', fontSize: 10, color: 'var(--green)', letterSpacing: '0.18em' }}>
                  {epic.id}
                </span>
                <span style={{ flex: 1 }} />
                <StatusBadge status={epic.status} />
              </div>
              <div style={{ marginTop: 6, fontSize: 13.5, fontWeight: 500, lineHeight: 1.35 }}>
                {epic.title}
              </div>
              <p style={{ margin: '4px 0 10px', fontSize: 11.5, color: 'rgba(255,255,255,0.55)', lineHeight: 1.5 }}>
                {epic.summary}
              </p>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <div style={{ flex: 1, height: 6, background: 'rgba(255,255,255,0.05)', borderRadius: 99, overflow: 'hidden' }}>
                  <div style={{ width: `${epic.progress}%`, height: '100%',
                    background: 'linear-gradient(90deg, #22c55e, #16a34a)',
                    boxShadow: '0 0 10px rgba(34,197,94,0.45)' }} />
                </div>
                <span style={{ fontFamily: 'Geist Mono, monospace', fontSize: 11, color: 'var(--green)', minWidth: 32, textAlign: 'right' }}>{epic.progress}%</span>
              </div>
              <div className="mono" style={{ fontSize: 9, letterSpacing: '0.22em', color: 'rgba(255,255,255,0.4)', marginTop: 8, display: 'flex', justifyContent: 'space-between' }}>
                <span>ETA {epic.eta}</span>
                <span>{epic.lead.split('·')[0].trim().toUpperCase()}</span>
              </div>
            </div>
          ))}
        </aside>
      </div>
    </div>
  );
}

window.PageReports = PageReports;

// === SUPORTE TECH & IA · TICKETS ====================================
const MOCK_TICKETS = [
  { id: 'IA-218', title: 'Bot está classificando reclamação de fatura como pedido de cancelamento',
    type: 'Bug', prio: 'crit', status: 'progress', created: '12/05',
    requester: 'Marina Coelho', team: 'SAC · A', assignee: 'Time Tech & IA',
    replies: 4, lastReply: 'há 2h',
    last: 'Reproduzimos com 6 amostras do dia 10/05. Ajuste no prompt + retrain agendado para hoje 18h.',
    by: 'Renan Tavares · Tech & IA' },
  { id: 'IA-215', title: 'Sugerir resposta automática quando cliente envia print da fatura',
    type: 'Feature', prio: 'high', status: 'triage', created: '11/05',
    requester: 'Pedro Mendes', team: 'SAC · A', assignee: '—',
    replies: 1, lastReply: 'há 1d',
    last: 'Recebido — vamos avaliar viabilidade na sprint 26.',
    by: 'Ana Lin · PM IA' },
  { id: 'IA-211', title: 'Threshold de confiança do classificador de intenção parece baixo demais',
    type: 'Investigação', prio: 'med', status: 'progress', created: '09/05',
    requester: 'Marina Coelho', team: 'SAC · A', assignee: 'Time Tech & IA',
    replies: 6, lastReply: 'há 5h',
    last: 'Analisando matriz de confusão de 7 dias. Hipótese: threshold cai com volume alto na fila.',
    by: 'Vitor Andrade · Tech & IA' },
  { id: 'IA-209', title: 'Dashboard IA não atualiza após meia-noite',
    type: 'Bug', prio: 'med', status: 'review', created: '08/05',
    requester: 'Larissa Souza', team: 'CS', assignee: 'Time Tech & IA',
    replies: 3, lastReply: 'há 12h',
    last: 'Fix aplicado em homolog. Subindo para produção amanhã 09h.',
    by: 'Renan Tavares · Tech & IA' },
  { id: 'IA-205', title: 'Permitir treinar variações do bot por família atendida',
    type: 'Feature', prio: 'high', status: 'progress', created: '06/05',
    requester: 'Otávio Lins', team: 'Vendas', assignee: 'Time Tech & IA',
    replies: 8, lastReply: 'há 30min',
    last: 'PoC pronta para Família COAMO. Vamos abrir piloto na próxima semana.',
    by: 'Ana Lin · PM IA' },
  { id: 'IA-198', title: 'Bot misturando assinatura "iGreen Energia" com "iGreen Solar"',
    type: 'Bug', prio: 'low', status: 'done', created: '03/05',
    requester: 'Beatriz Galvão', team: 'SAC · B', assignee: 'Time Tech & IA',
    replies: 5, lastReply: 'há 3d',
    last: 'Resolvido. Disponibilizado em produção 06/05 às 14:20.',
    by: 'Renan Tavares · Tech & IA' },
  { id: 'IA-191', title: 'Sugestão: integrar bot com base de conhecimento de cooperativas',
    type: 'Feature', prio: 'med', status: 'backlog', created: '01/05',
    requester: 'Pedro Mendes', team: 'SAC · A', assignee: '—',
    replies: 0, lastReply: '—',
    last: 'Aguardando triagem na próxima sprint.',
    by: '—' },
];

const MOCK_DEV = [
  { id: 'EPIC-7', title: 'Roteamento inteligente por família atendida',
    progress: 62, eta: '23/05', lead: 'Ana Lin · PM',
    status: 'progress',
    summary: 'Bot reconhece automaticamente a família do consumidor e direciona para fila/skill correta.',
    tasks: [
      { t: 'Modelo de classificação por família', d: 'done' },
      { t: 'Integração com roteador atual',       d: 'progress' },
      { t: 'Painel de monitoring por família',    d: 'progress' },
      { t: 'Piloto Família COAMO',                d: 'backlog' },
    ]},
  { id: 'EPIC-6', title: 'Detector de frustração em mensagens',
    progress: 41, eta: '30/05', lead: 'Vitor Andrade · Tech & IA',
    status: 'progress',
    summary: 'Identifica sinais de irritação e prioriza/encaminha a conversa antes de virar reclamação formal.',
    tasks: [
      { t: 'Dataset rotulado · 2k amostras',     d: 'done' },
      { t: 'Modelo fine-tuned',                  d: 'progress' },
      { t: 'Integração com fila prioritária',    d: 'backlog' },
      { t: 'AB-test com SAC · A',                d: 'backlog' },
    ]},
  { id: 'EPIC-5', title: 'Resumo automático ao encerrar conversa',
    progress: 88, eta: '15/05', lead: 'Renan Tavares · Tech & IA',
    status: 'review',
    summary: 'Cada conversa encerrada ganha um resumo de 3 linhas + tags para alimentar relatórios e auditoria.',
    tasks: [
      { t: 'Prompt + few-shot examples',          d: 'done' },
      { t: 'Pipeline de geração assíncrona',      d: 'done' },
      { t: 'Validação humana · amostra 500',      d: 'done' },
      { t: 'Deploy em produção',                  d: 'review' },
    ]},
];

function StatusBadge({ status }) {
  const map = {
    backlog:  ['Backlog',         'ts-backlog'],
    triage:   ['Triagem',         'ts-triage'],
    progress: ['Em desenvolvimento', 'ts-progress'],
    review:   ['Em revisão',      'ts-review'],
    done:     ['Concluído',       'ts-done'],
    blocked:  ['Bloqueado',       'ts-blocked'],
  };
  const [label, cls] = map[status];
  return <span className={`ticket-status ${cls}`}><span className="d" />{label}</span>;
}

function PrioLabel({ p }) {
  const map = { low: ['Baixa', 'prio-low'], med: ['Média', 'prio-med'], high: ['Alta', 'prio-high'], crit: ['Crítica', 'prio-crit'] };
  const [l, c] = map[p];
  return <span className={`mono ${c}`} style={{ fontSize: 10, letterSpacing: '0.22em' }}>● {l.toUpperCase()}</span>;
}

function PageTickets({ tool }) {
  const [tab, setTab] = usePS('resumo');
  const [summary, setSummary] = usePS(null);
  const [reloadKey, setReloadKey] = usePS(0);
  const refresh = () => setReloadKey(k => k + 1);

  usePE(() => {
    window.CCApi.support.summary().then(setSummary).catch(() => {});
  }, [reloadKey]);

  const inProgress = (summary?.totals ?? []).find(s => s.status === 'progress')?.count ?? 0;
  const minePending = summary?.mine_pending ?? 0;

  return (
    <div className="page">
      <PageHead eyebrow="ENGENHARIA DE IA · DEMANDAS" title="Demandas"
        sub="Resumo do que o time está construindo, abrir nova demanda e acompanhar respostas dos seus tickets."
        right={
          <div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
            <span className="chip"><span className="dot-pulse" /> {inProgress} EM ANDAMENTO</span>
          </div>
        } />

      <div className="tabs">
        <button className={`tab ${tab === 'resumo' ? 'is-active' : ''}`} onClick={() => setTab('resumo')}>
          <Icon name="activity" size={13} /> Resumo
        </button>
        <button className={`tab ${tab === 'criar' ? 'is-active' : ''}`} onClick={() => setTab('criar')}>
          <Icon name="userPlus" size={13} /> Nova demanda
        </button>
        <button className={`tab ${tab === 'acomp' ? 'is-active' : ''}`} onClick={() => setTab('acomp')}>
          <Icon name="inbox" size={13} /> Minhas respostas
          {minePending > 0 && <span className="tab-count">{minePending}</span>}
        </button>
      </div>

      {tab === 'resumo' && <TicketResumo summary={summary} onRefresh={refresh} />}
      {tab === 'criar' && <TicketCriar onCreated={() => { refresh(); setTab('acomp'); }} />}
      {tab === 'acomp' && <TicketAcomp reloadKey={reloadKey} onChange={refresh} />}
    </div>
  );
}

function TicketResumo({ summary, onRefresh }) {
  const totalsByStatus = (summary?.totals ?? []).reduce((acc, t) => { acc[t.status] = t.count; return acc; }, {});
  const total = Object.values(totalsByStatus).reduce((s, v) => s + v, 0);
  const inDev = MOCK_DEV.filter(e => e.status === 'progress' || e.status === 'review');
  const meusAbertos = summary?.mine_pending ?? 0;
  const cardStyle = {
    padding: '14px 16px', borderRadius: 12,
    background: 'linear-gradient(145deg, rgba(30,41,59,0.55), rgba(15,23,42,0.55))',
    border: 'none',
  };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 10 }}>
        <div style={cardStyle}>
          <div className="mono" style={{ fontSize: 9.5, letterSpacing: '0.22em', color: 'rgba(255,255,255,0.5)' }}>SEUS TICKETS ABERTOS</div>
          <div style={{ fontSize: 26, fontWeight: 600, letterSpacing: '-0.02em', marginTop: 4, color: meusAbertos > 0 ? 'var(--green)' : 'var(--text)' }}>{meusAbertos}</div>
          <div style={{ fontSize: 11, color: 'rgba(255,255,255,0.55)', marginTop: 2 }}>
            {meusAbertos === 0 ? 'sem demandas pendentes' : meusAbertos === 1 ? 'demanda em andamento' : 'demandas em andamento'}
          </div>
        </div>
        <div style={cardStyle}>
          <div className="mono" style={{ fontSize: 9.5, letterSpacing: '0.22em', color: 'rgba(255,255,255,0.5)' }}>EM DESENVOLVIMENTO</div>
          <div style={{ fontSize: 26, fontWeight: 600, letterSpacing: '-0.02em', marginTop: 4 }}>{(totalsByStatus.progress || 0)}</div>
          <div style={{ fontSize: 11, color: 'rgba(255,255,255,0.55)', marginTop: 2 }}>tickets ativos no time</div>
        </div>
        <div style={cardStyle}>
          <div className="mono" style={{ fontSize: 9.5, letterSpacing: '0.22em', color: 'rgba(255,255,255,0.5)' }}>EM REVISÃO</div>
          <div style={{ fontSize: 26, fontWeight: 600, letterSpacing: '-0.02em', marginTop: 4 }}>{(totalsByStatus.review || 0)}</div>
          <div style={{ fontSize: 11, color: 'rgba(255,255,255,0.55)', marginTop: 2 }}>aguardando validação</div>
        </div>
        <div style={cardStyle}>
          <div className="mono" style={{ fontSize: 9.5, letterSpacing: '0.22em', color: 'rgba(255,255,255,0.5)' }}>TOTAL</div>
          <div style={{ fontSize: 26, fontWeight: 600, letterSpacing: '-0.02em', marginTop: 4 }}>{total}</div>
          <div style={{ fontSize: 11, color: 'rgba(255,255,255,0.55)', marginTop: 2 }}>
            {Object.entries(totalsByStatus).map(([k, v]) => `${k} ${v}`).join(' · ') || 'sem demandas ainda'}
          </div>
        </div>
      </div>

      <div className="card card-topline" style={{ padding: 18 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 14 }}>
          <span className="mono" style={{ color: 'var(--green)', fontSize: 11 }}>01</span>
          <h2 style={{ margin: 0, fontSize: 14, fontWeight: 500 }}>O que o time está construindo</h2>
          <div className="rule" style={{ flex: 1, height: 1, background: 'rgba(255,255,255,0.06)' }} />
          <span className="mono" style={{ fontSize: 9.5, letterSpacing: '0.22em', color: 'rgba(255,255,255,0.4)' }}>
            {inDev.length} EPICS ATIVOS
          </span>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))', gap: 12 }}>
          {inDev.map(epic => (
            <div key={epic.id} style={{
              padding: 14, borderRadius: 10,
              background: 'rgba(255,255,255,0.02)',
              border: 'none',
            }}>
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8 }}>
                <span className="mono" style={{ fontSize: 9.5, color: 'var(--green)', letterSpacing: '0.22em' }}>{epic.id}</span>
                <StatusBadge status={epic.status} />
              </div>
              <div style={{ fontSize: 13, fontWeight: 500, marginTop: 6, lineHeight: 1.35 }}>{epic.title}</div>
              <div style={{ fontSize: 11.5, color: 'rgba(255,255,255,0.55)', marginTop: 4, lineHeight: 1.5 }}>{epic.summary}</div>
              <div style={{ marginTop: 10, display: 'flex', alignItems: 'center', gap: 8 }}>
                <div style={{
                  flex: 1, height: 4, borderRadius: 999,
                  background: 'rgba(255,255,255,0.06)', overflow: 'hidden',
                }}>
                  <div style={{
                    width: `${epic.progress}%`, height: '100%',
                    background: 'linear-gradient(90deg, var(--green), rgba(52,211,153,0.6))',
                  }} />
                </div>
                <span className="mono" style={{ fontSize: 10, color: 'rgba(255,255,255,0.55)', letterSpacing: '0.18em' }}>{epic.progress}%</span>
              </div>
              <div className="mono" style={{ fontSize: 9.5, letterSpacing: '0.22em', color: 'rgba(255,255,255,0.42)', marginTop: 8 }}>
                ETA {epic.eta} · {epic.lead}
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function TicketCriar({ onCreated }) {
  const [type, setType] = usePS('');
  const [prio, setPrio] = usePS('low');
  const [title, setTitle] = usePS('');
  const [description, setDescription] = usePS('');
  const [convRef, setConvRef] = usePS('');
  const [attachments, setAttachments] = usePS([]);
  const [submitting, setSubmitting] = usePS(false);
  const [error, setError] = usePS(null);
  const fileRef = React.useRef(null);
  const me = window.__identity?.displayName || window.__identity?.email || 'Colaborador';

  function handleFiles(e) {
    const files = Array.from(e.target.files || []);
    for (const f of files) {
      const reader = new FileReader();
      reader.onload = () => setAttachments(prev => [...prev, { name: f.name, size: f.size, dataUrl: reader.result }]);
      reader.readAsDataURL(f);
    }
    e.target.value = '';
  }

  function removeAttachment(idx) {
    setAttachments(prev => prev.filter((_, i) => i !== idx));
  }

  async function submit() {
    setError(null);
    if (!type) { setError('Selecione o tipo do ticket.'); return; }
    if (title.trim().length < 3) { setError('Título precisa ter pelo menos 3 caracteres.'); return; }
    if (description.trim().length < 10) { setError('Descrição precisa ter pelo menos 10 caracteres.'); return; }
    setSubmitting(true);
    try {
      // Mapeia o id da UI (feat/invest/other/bug) pro tipo do backend.
      const apiType = ({ bug: 'bug', feat: 'feature', ia: 'melhoria_ia', invest: 'investigacao', other: 'outro' })[type] || 'bug';
      await window.CCApi.support.createTicket({
        title: title.trim(),
        description: description.trim(),
        type: apiType,
        priority: prio,
        conversation_ref: convRef.trim() || undefined,
      });
      setTitle(''); setDescription(''); setConvRef('');
      onCreated?.();
    } catch (e) {
      setError(e.detail?.message || e.detail?.error || e.message);
    } finally {
      setSubmitting(false);
    }
  }

  return (
    <div className="page-cols">
      <Card title="Novo ticket" sub="Quanto mais contexto, mais rápido o time consegue agir.">
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          <div>
            <div className="mono" style={{ fontSize: 9.5, letterSpacing: '0.22em', color: !type ? 'var(--danger)' : 'rgba(255,255,255,0.5)', marginBottom: 6 }}>
              {!type ? 'SELECIONE O TIPO *' : 'TIPO'}
            </div>
            <div style={{
              display: 'flex', gap: 0, borderRadius: 8, overflow: 'hidden',
              border: '1px solid ' + (!type ? 'rgba(239,68,68,0.30)' : 'transparent'),
            }}>
              {[
                { id: 'bug',    label: 'Bug',          icon: 'ban'    },
                { id: 'feat',   label: 'Sugestão',     icon: 'zap'    },
                { id: 'ia',     label: 'Melhoria IA',  icon: 'cpu'    },
                { id: 'invest', label: 'Investigação', icon: 'search' },
                { id: 'other',  label: 'Outro',        icon: 'fileText' },
              ].map((o, i) => (
                <button key={o.id} type="button" onClick={() => setType(o.id)}
                  style={{
                    flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 5,
                    padding: '8px 6px',
                    background: type === o.id ? 'rgba(34,197,94,0.12)' : 'rgba(255,255,255,0.02)',
                    borderRight: i < 4 ? '1px solid rgba(255,255,255,0.06)' : 'none',
                    border: 'none', borderRight: i < 4 ? '1px solid rgba(255,255,255,0.06)' : 'none',
                    color: type === o.id ? 'var(--green)' : 'rgba(255,255,255,0.6)',
                    cursor: 'pointer', fontSize: 11, fontWeight: type === o.id ? 600 : 400,
                    transition: 'background 100ms, color 100ms',
                  }}>
                  <Icon name={o.icon} size={11} /> {o.label}
                </button>
              ))}
            </div>
          </div>
          <Field label="PRIORIDADE">
              <div style={{ display: 'flex', gap: 6 }}>
                {[
                  { id: 'low',  label: 'Baixa',  c: 'var(--info)' },
                  { id: 'med',  label: 'Média',   c: 'var(--warning)' },
                  { id: 'high', label: 'Alta',    c: 'var(--danger)' },
                ].map(p => (
                  <button key={p.id} type="button" onClick={async () => {
                    if (p.id === 'high') {
                      const ok = await window.CCConfirm({
                        title: 'Prioridade alta',
                        message: 'Tem certeza sobre a classificação de prioridade alta?\n\nExemplos de prioridade alta: sistema fora do ar, IA passando informação errada, erros em funcionalidades vitais de algum sistema.',
                        confirmLabel: 'Sim, é alta',
                        cancelLabel: 'Cancelar',
                        tone: 'danger',
                      });
                      if (!ok) return;
                    }
                    setPrio(p.id);
                  }}
                    style={{
                      flex: 1, padding: '6px 4px', borderRadius: 6,
                      background: prio === p.id ? 'rgba(255,255,255,0.05)' : 'transparent',
                      border: '1px solid ' + (prio === p.id ? p.c : 'transparent'),
                      color: prio === p.id ? p.c : 'rgba(255,255,255,0.5)',
                      fontSize: 11, cursor: 'pointer',
                    }}>● {p.label}</button>
                ))}
              </div>
            </Field>
          <Field label="TÍTULO">
            <input style={legacyInputStyle} value={title} onChange={e => setTitle(e.target.value)}
                   placeholder="Bot está respondendo errado quando o cliente envia áudio" />
          </Field>
          <Field label="DESCRIÇÃO">
            <textarea style={{ ...legacyInputStyle, minHeight: 80, resize: 'vertical' }}
                      value={description} onChange={e => setDescription(e.target.value)}
                      placeholder="O que aconteceu? O que era esperado? Quando começou?" />
          </Field>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr auto', gap: 10, alignItems: 'end' }}>
            <Field label="ID DA CONVERSA (OPCIONAL)">
              <input style={legacyInputStyle} value={convRef} onChange={e => setConvRef(e.target.value)}
                     placeholder="#A48-2210" />
            </Field>
            <div>
              <input ref={fileRef} type="file" accept="image/*" multiple style={{ display: 'none' }} onChange={handleFiles} />
              <button type="button" onClick={() => fileRef.current?.click()} style={{
                padding: '8px 12px', borderRadius: 6, cursor: 'pointer',
                background: 'rgba(255,255,255,0.03)', border: 'none',
                color: 'rgba(255,255,255,0.55)', fontSize: 11, display: 'flex', alignItems: 'center', gap: 6,
                whiteSpace: 'nowrap',
              }}>
                <Icon name="upload" size={12} /> {attachments.length > 0 ? `${attachments.length} anexo${attachments.length > 1 ? 's' : ''}` : 'Anexar imagem'}
              </button>
            </div>
          </div>
          {attachments.length > 0 && (
            <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
              {attachments.map((a, i) => (
                <div key={i} style={{
                  position: 'relative', width: 48, height: 48, borderRadius: 5, overflow: 'hidden',
                  border: 'none',
                }}>
                  <img src={a.dataUrl} alt={a.name} style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
                  <button type="button" onClick={() => removeAttachment(i)} style={{
                    position: 'absolute', top: 1, right: 1, width: 14, height: 14, borderRadius: 99,
                    background: 'rgba(0,0,0,0.7)', border: 'none', color: '#fff', fontSize: 9,
                    cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
                  }}>×</button>
                </div>
              ))}
            </div>
          )}
          {error && <div className="chip is-warn" style={{ alignSelf: 'flex-start' }}>{error}</div>}
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <span className="mono" style={{ fontSize: 9.5, letterSpacing: '0.22em', color: 'rgba(255,255,255,0.4)' }}>
              REGISTRADO COMO {String(me).toUpperCase()}
            </span>
            <div style={{ display: 'flex', gap: 8 }}>
              <button className="btn-cta" type="button" onClick={submit} disabled={submitting}>
                {submitting ? 'Abrindo…' : 'Abrir ticket ↵'}
              </button>
            </div>
          </div>
        </div>
      </Card>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
        <Card title="Como funciona" sub="Seg–Sex · 9h às 18h (Brasília)">
          <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
            {[
              ['1', 'Você abre o ticket',                 'Descreva o problema com prints e IDs de conversa. Quanto mais contexto, mais rápido resolvemos.'],
              ['2', 'Triagem pelo time',                  'Validamos a prioridade e estimamos o prazo.'],
              ['3', 'Desenvolvimento',                    'Resolvemos e você acompanha o status aqui.'],
              ['4', 'Validação com você',                 'Confirmamos a resolução antes de fechar o ticket.'],
            ].map(([n, h, t]) => (
              <div key={n} style={{ display: 'flex', gap: 12 }}>
                <span style={{
                  width: 22, height: 22, flexShrink: 0, borderRadius: 99,
                  background: 'rgba(34,197,94,0.10)', border: 'none',
                  color: 'var(--green)', fontFamily: 'Geist Mono, monospace', fontSize: 10.5,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                }}>{n}</span>
                <div>
                  <div style={{ fontSize: 12.5, fontWeight: 500 }}>{h}</div>
                  <div style={{ fontSize: 11.5, color: 'rgba(255,255,255,0.55)', lineHeight: 1.5 }}>{t}</div>
                </div>
              </div>
            ))}
          </div>
        </Card>
        <Card title="SLA por prioridade">
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {[
              ['●', 'Alta',  'Resolvido no mesmo dia, o quanto antes.',           'var(--danger)'],
              ['●', 'Média', 'Alocado nos próximos dias livres da fila.',         'var(--warning)'],
              ['●', 'Baixa', 'Entra na fila sem prazo fixo.', 'rgba(255,255,255,0.4)'],
            ].map(([dot, label, desc, c]) => (
              <div key={label} style={{ display: 'flex', alignItems: 'flex-start', gap: 10 }}>
                <span style={{ color: c, fontSize: 14, lineHeight: 1, marginTop: 2 }}>{dot}</span>
                <div>
                  <div style={{ fontSize: 12.5, fontWeight: 500 }}>{label}</div>
                  <div style={{ fontSize: 11.5, color: 'rgba(255,255,255,0.55)', lineHeight: 1.5 }}>{desc}</div>
                </div>
              </div>
            ))}
          </div>
          <div style={{ marginTop: 8, fontSize: 11, color: 'rgba(255,255,255,0.4)', lineHeight: 1.5 }}>
            A prioridade informada por você passa pela nossa triagem.
          </div>
        </Card>
      </div>
    </div>
  );
}

function TicketAcomp({ reloadKey, onChange }) {
  const isTech = !!window.__identity?.isSuperAdmin;
  const [scope, setScope] = usePS(isTech ? 'all' : 'mine');
  const [items, setItems] = usePS([]);
  const [openId, setOpenId] = usePS(null);
  const [detail, setDetail] = usePS(null);
  const [commentText, setCommentText] = usePS('');
  const [busy, setBusy] = usePS(false);
  const [error, setError] = usePS(null);

  async function loadList() {
    try {
      const r = await window.CCApi.support.listTickets({ scope });
      setItems(r.items ?? []);
      if (!openId && (r.items ?? []).length > 0) setOpenId(r.items[0].id);
    } catch (e) { setError(e.detail?.message || e.message); }
  }
  async function loadDetail(id) {
    if (!id) { setDetail(null); return; }
    try {
      const r = await window.CCApi.support.getTicket(id);
      setDetail(r);
    } catch (e) { setError(e.detail?.message || e.message); }
  }

  usePE(() => { loadList(); }, [scope, reloadKey]);
  usePE(() => { loadDetail(openId); }, [openId, reloadKey]);

  async function postComment() {
    if (!openId || commentText.trim().length < 2) return;
    setBusy(true); setError(null);
    try {
      await window.CCApi.support.addComment(openId, commentText.trim());
      setCommentText('');
      await loadDetail(openId);
      await loadList();
      onChange?.();
    } catch (e) { setError(e.detail?.message || e.message); }
    finally { setBusy(false); }
  }

  async function updateField(patch) {
    if (!openId) return;
    setBusy(true); setError(null);
    try {
      await window.CCApi.support.updateTicket(openId, patch);
      await loadDetail(openId);
      await loadList();
      onChange?.();
    } catch (e) { setError(e.detail?.message || e.message); }
    finally { setBusy(false); }
  }

  const open = detail?.ticket;
  const comments = detail?.comments ?? [];

  return (
    <div>
      <div style={{ display: 'flex', gap: 8, marginBottom: 14, flexWrap: 'wrap', alignItems: 'center' }}>
        {[
          ['mine',  `Minhas · ${scope === 'mine' ? items.length : ''}`.trim()],
          ...(isTech ? [['all', `Todas · ${scope === 'all' ? items.length : ''}`.trim()]] : []),
        ].map(([id, l]) => (
          <button key={id} onClick={() => { setScope(id); setOpenId(null); }}
            className={`chip ${scope === id ? 'is-info' : ''}`}
            style={{ cursor: 'pointer',
              borderColor: scope === id ? 'rgba(34,197,94,0.5)' : undefined,
              color: scope === id ? 'var(--green)' : undefined }}>
            {l}
          </button>
        ))}
        {error && <span className="chip is-warn">{error}</span>}
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1.1fr 1fr', gap: 14 }}>
        <Card padding={0}>
          {items.length === 0
            ? <div style={{ padding: 22, color: 'rgba(255,255,255,0.5)', fontSize: 13 }}>Nenhum ticket por enquanto. Abra uma nova demanda na aba ao lado.</div>
            : items.map((t, k) => (
            <button key={t.id} onClick={() => setOpenId(t.id)}
              style={{
                width: '100%', textAlign: 'left', cursor: 'pointer',
                padding: '14px 16px', display: 'flex', flexDirection: 'column', gap: 8,
                background: openId === t.id ? 'rgba(34,197,94,0.06)' : 'transparent',
                border: 'none', borderTop: k ? '1px solid rgba(255,255,255,0.05)' : 'none',
                color: 'inherit',
              }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <span style={{ fontFamily: 'Geist Mono, monospace', fontSize: 10.5,
                  color: openId === t.id ? 'var(--green)' : 'rgba(255,255,255,0.5)',
                  letterSpacing: '0.18em' }}>{t.code}</span>
                <span style={{ flex: 1 }} />
                <StatusBadge status={t.status} />
              </div>
              <div style={{ fontSize: 13.5, color: 'rgba(255,255,255,0.9)', fontWeight: 500, lineHeight: 1.4 }}>
                {t.title}
              </div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 12, fontSize: 11.5, color: 'rgba(255,255,255,0.5)' }}>
                <span className="mono" style={{ letterSpacing: '0.22em', fontSize: 9.5 }}>{(t.type || '').toUpperCase()}</span>
                <PrioLabel p={t.priority || 'med'} />
                <span style={{ flex: 1 }} />
                <span>{t.comment_count || 0} resposta{(t.comment_count||0) === 1 ? '' : 's'}</span>
              </div>
            </button>
          ))}
        </Card>

        <div className="card card-topline" style={{ padding: 18, alignSelf: 'flex-start' }}>
          {!open ? (
            <div style={{ padding: 22, color: 'rgba(255,255,255,0.5)' }}>Selecione um ticket à esquerda.</div>
          ) : (
            <>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' }}>
                <span style={{ fontFamily: 'Geist Mono, monospace', fontSize: 11, color: 'var(--green)', letterSpacing: '0.18em' }}>{open.code}</span>
                <StatusBadge status={open.status} />
                <span style={{ flex: 1 }} />
                <span className="mono" style={{ fontSize: 9.5, letterSpacing: '0.22em', color: 'rgba(255,255,255,0.4)' }}>
                  ABERTO {(open.created_at || '').slice(0, 10)}
                </span>
              </div>
              <h2 style={{ margin: '10px 0 4px', fontSize: 17, fontWeight: 500, lineHeight: 1.35 }}>{open.title}</h2>
              <div style={{ display: 'flex', gap: 14, fontSize: 11.5, color: 'rgba(255,255,255,0.55)', alignItems: 'center', marginTop: 6, flexWrap: 'wrap' }}>
                <span className="mono" style={{ letterSpacing: '0.22em', fontSize: 9.5 }}>{(open.type || '').toUpperCase()}</span>
                <PrioLabel p={open.priority || 'med'} />
                <span>· por {open.requester_name || open.requester_email || '—'}</span>
                {open.conversation_ref && <span>· conv {open.conversation_ref}</span>}
              </div>

              {/* Controles do tech */}
              {isTech && (
                <div style={{
                  marginTop: 12, padding: 10, borderRadius: 8,
                  background: 'rgba(168,85,247,0.06)', border: 'none',
                  display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap',
                }}>
                  <span className="mono" style={{ fontSize: 9.5, letterSpacing: '0.22em', color: '#d8b4fe' }}>TECH CONTROLS</span>
                  <select value={open.status} onChange={e => updateField({ status: e.target.value })} style={selectMini}>
                    {['triage', 'backlog', 'progress', 'review', 'done', 'blocked'].map(s => <option key={s} value={s}>{s}</option>)}
                  </select>
                  <select value={open.priority} onChange={e => updateField({ priority: e.target.value })} style={selectMini}>
                    {['low', 'med', 'high', 'crit'].map(p => <option key={p} value={p}>{p}</option>)}
                  </select>
                  <input placeholder="Assignee (nome do dev)" value={open.assignee_label || ''}
                         onBlur={e => updateField({ assignee_label: e.target.value })}
                         onChange={e => setDetail(d => ({ ...d, ticket: { ...d.ticket, assignee_label: e.target.value } }))}
                         style={{ ...selectMini, minWidth: 160 }} />
                </div>
              )}

              {/* Descrição original */}
              <div style={{ marginTop: 12, padding: 12, borderRadius: 8,
                background: 'rgba(255,255,255,0.02)', border: 'none' }}>
                <div className="mono" style={{ fontSize: 9.5, letterSpacing: '0.22em', color: 'rgba(255,255,255,0.45)', marginBottom: 6 }}>DESCRIÇÃO ORIGINAL</div>
                <div style={{ fontSize: 12.5, color: 'rgba(255,255,255,0.78)', lineHeight: 1.55, whiteSpace: 'pre-wrap' }}>{open.description}</div>
              </div>

              {/* Thread de comentários */}
              <div style={{ marginTop: 14, display: 'flex', flexDirection: 'column', gap: 10 }}>
                {comments.length === 0 && (
                  <div style={{ fontSize: 12, color: 'rgba(255,255,255,0.4)', fontStyle: 'italic' }}>
                    Sem respostas ainda.
                  </div>
                )}
                {comments.map(c => {
                  const isCommentTech = c.author_role === 'tech';
                  return (
                    <div key={c.id} style={{
                      padding: 12, borderRadius: 8,
                      background: isCommentTech ? 'rgba(34,197,94,0.05)' : 'rgba(255,255,255,0.03)',
                      border: '1px solid ' + (isCommentTech ? 'rgba(34,197,94,0.18)' : 'transparent'),
                    }}>
                      <div className="mono" style={{ fontSize: 9.5, letterSpacing: '0.22em', color: isCommentTech ? 'var(--green)' : 'rgba(255,255,255,0.55)', marginBottom: 6 }}>
                        {isCommentTech ? '★ TIME TECH/IA' : '· VOCÊ'} · {(c.created_at || '').slice(0, 16).replace('T', ' ')}
                      </div>
                      <div style={{ fontSize: 12.5, color: 'rgba(255,255,255,0.85)', lineHeight: 1.55, whiteSpace: 'pre-wrap' }}>{c.body}</div>
                      <div className="mono" style={{ fontSize: 9.5, letterSpacing: '0.22em', color: 'rgba(255,255,255,0.4)', marginTop: 6 }}>
                        — {c.author_name || c.author_email || 'sem nome'}
                      </div>
                    </div>
                  );
                })}
              </div>

              {/* Composer — só tech/dev pode responder e resolver */}
              <div style={{ marginTop: 14 }}>
                <span className="mono" style={{ fontSize: 9.5, letterSpacing: '0.22em', color: 'rgba(255,255,255,0.4)' }}>
                  {comments.length} RESPOSTA{comments.length === 1 ? '' : 'S'} NO TICKET
                </span>
                {isTech && (
                  <>
                    <textarea value={commentText} onChange={e => setCommentText(e.target.value)}
                              style={{ ...legacyInputStyle, minHeight: 80, resize: 'vertical', marginTop: 8 }}
                              placeholder="Escreva uma resposta… (mínimo 2 caracteres)" />
                    <div style={{ display: 'flex', justifyContent: 'flex-end', alignItems: 'center', marginTop: 10, gap: 8 }}>
                      {open.status !== 'done' && (
                        <button className="chip" style={{ cursor: 'pointer' }}
                                onClick={() => updateField({ status: 'done' })}
                                disabled={busy}>
                          Marcar como resolvido
                        </button>
                      )}
                      <button className="btn-cta" onClick={postComment} disabled={busy || commentText.trim().length < 2}>
                        {busy ? '…' : 'Responder'}
                      </button>
                    </div>
                  </>
                )}
                {!isTech && comments.length === 0 && open.status !== 'done' && (
                  <div style={{ marginTop: 8, fontSize: 12, color: 'rgba(255,255,255,0.4)', fontStyle: 'italic' }}>
                    Aguardando análise do time.
                  </div>
                )}
              </div>
            </>
          )}
        </div>
      </div>
    </div>
  );
}

const selectMini = {
  padding: '5px 8px', borderRadius: 6,
  background: 'rgba(255,255,255,0.04)', border: 'none',
  color: 'var(--text)', fontSize: 11.5, fontFamily: 'inherit',
};

function TicketDev() {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
      <div style={{
        padding: '14px 18px', borderRadius: 10,
        background: 'rgba(34,197,94,0.06)',
        border: 'none',
        display: 'flex', alignItems: 'center', gap: 14,
      }}>
        <span className="dot-pulse" style={{ width: 8, height: 8 }} />
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 13, fontWeight: 500 }}>Sprint 26 · 06–17 mai</div>
          <div style={{ fontSize: 11.5, color: 'rgba(255,255,255,0.55)', marginTop: 2 }}>
            3 épicos em andamento · próximo planejamento 19/05
          </div>
        </div>
        <span className="chip is-info">DEMO 17/05 · 16H</span>
      </div>

      {MOCK_DEV.map(epic => (
        <div key={epic.id} className="card card-topline" style={{ padding: 20 }}>
          <div style={{ display: 'flex', alignItems: 'flex-start', gap: 14 }}>
            <div style={{
              width: 44, height: 44, borderRadius: 10,
              background: 'rgba(34,197,94,0.10)', border: 'none',
              color: 'var(--green)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}>
              <Icon name="zap" size={18} />
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <span style={{ fontFamily: 'Geist Mono, monospace', fontSize: 10.5, color: 'var(--green)', letterSpacing: '0.18em' }}>{epic.id}</span>
                <StatusBadge status={epic.status} />
              </div>
              <h2 style={{ margin: '6px 0 4px', fontSize: 17, fontWeight: 500 }}>{epic.title}</h2>
              <p style={{ margin: 0, fontSize: 12.5, color: 'rgba(255,255,255,0.6)', lineHeight: 1.55 }}>{epic.summary}</p>
            </div>
            <div style={{ textAlign: 'right' }}>
              <div className="mono" style={{ fontSize: 9.5, letterSpacing: '0.22em', color: 'rgba(255,255,255,0.4)' }}>ETA</div>
              <div style={{ fontSize: 16, fontFamily: 'Geist Mono, monospace', color: 'var(--green)', marginTop: 4 }}>{epic.eta}</div>
            </div>
          </div>

          <div style={{ marginTop: 16, display: 'flex', alignItems: 'center', gap: 12 }}>
            <div style={{ flex: 1, height: 8, background: 'rgba(255,255,255,0.05)', borderRadius: 99, overflow: 'hidden' }}>
              <div style={{ width: `${epic.progress}%`, height: '100%',
                background: 'linear-gradient(90deg, #22c55e, #16a34a)',
                boxShadow: '0 0 12px rgba(34,197,94,0.45)' }} />
            </div>
            <span style={{ fontFamily: 'Geist Mono, monospace', fontSize: 12, color: 'var(--green)', minWidth: 40, textAlign: 'right' }}>{epic.progress}%</span>
            <span className="mono" style={{ fontSize: 9.5, letterSpacing: '0.22em', color: 'rgba(255,255,255,0.4)' }}>{epic.lead}</span>
          </div>

          <div style={{ marginTop: 14, display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(220px, 1fr))', gap: 8 }}>
            {epic.tasks.map((t, i) => (
              <div key={i} style={{
                display: 'flex', alignItems: 'center', gap: 10,
                padding: '8px 10px', borderRadius: 7,
                background: 'rgba(255,255,255,0.025)',
                border: 'none',
              }}>
                <span style={{
                  width: 14, height: 14, borderRadius: 4,
                  background:
                    t.d === 'done'     ? 'var(--green)' :
                    t.d === 'progress' ? 'rgba(34,197,94,0.15)' :
                    t.d === 'review'   ? 'rgba(168,85,247,0.20)' :
                                          'rgba(255,255,255,0.05)',
                  border: '1px solid ' + (
                    t.d === 'done'     ? 'var(--green)' :
                    t.d === 'progress' ? 'rgba(34,197,94,0.5)' :
                    t.d === 'review'   ? 'rgba(168,85,247,0.5)' :
                                          'transparent'),
                  color: '#06170d',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  fontSize: 9, fontWeight: 700,
                  flexShrink: 0,
                }}>{t.d === 'done' ? '✓' : t.d === 'progress' ? '~' : ''}</span>
                <span style={{ fontSize: 12.5,
                  color: t.d === 'done' ? 'rgba(255,255,255,0.5)' : 'rgba(255,255,255,0.85)',
                  textDecoration: t.d === 'done' ? 'line-through' : 'none',
                }}>{t.t}</span>
              </div>
            ))}
          </div>
        </div>
      ))}
    </div>
  );
}

// --- Registry ---------------------------------------------
// --- Ticket pages (split from old PageTickets) ---
function PageTicketAbrir() {
  return (
    <div className="page">
      <PageHead eyebrow="TIME TECH & IA" title="Abrir ticket"
        sub="Registre um pedido, bug ou sugestão para o time de tecnologia." />
      <TicketCriar onCreated={() => {}} />
    </div>
  );
}

function PageTicketMeus() {
  const [reloadKey, setReloadKey] = usePS(0);
  return (
    <div className="page">
      <PageHead eyebrow="TIME TECH & IA" title="Meus tickets"
        sub="Acompanhe o status e as respostas dos tickets que você abriu."
        right={<button className="btn-ghost" onClick={() => setReloadKey(k => k + 1)}>Atualizar</button>} />
      <TicketAcomp reloadKey={reloadKey} onChange={() => setReloadKey(k => k + 1)} />
    </div>
  );
}

function PageTicketDev() {
  const [summary, setSummary] = usePS(null);
  const [key, setKey] = usePS(0);
  const refresh = () => { setKey(k => k + 1); window.CCApi.support.summary().then(setSummary).catch(() => {}); };
  usePE(() => { window.CCApi.support.summary().then(setSummary).catch(() => {}); }, [key]);
  return (
    <div className="page">
      <PageHead eyebrow="TIME TECH & IA" title="Acompanhar Desenvolvimento"
        sub="O que o time está construindo e próximas entregas." />
      <TicketResumo summary={summary} onRefresh={refresh} />
    </div>
  );
}

function PageTicketFeed() {
  return (
    <div className="page">
      <PageHead eyebrow="TIME TECH & IA" title="Feed"
        sub="Novidades, atualizações e entregas recentes." />
      <div className="card" style={{ padding: 24, color: 'rgba(255,255,255,0.5)', fontSize: 13 }}>
        Em breve — o feed de atualizações do time será exibido aqui.
      </div>
    </div>
  );
}

window.PAGES = {
  'at-conv-origem': PageConvOrigem,
  'at-backlog':     PageBacklog,
  'gs-cad-reset':   PageReset,
  'gs-cad-criar':   PageCriar,
  'gs-cad-role':    PageRole,
  'gs-cad-nivel':   PageNivel,
  'gs-fam-col':     PageFamCol,
  'gs-fam-time':    PageFamTime,
  'gs-fam-forn':    PageFamForn,
  'gs-alert-prod':  PageAlertas,
  'gs-rel-resol':   PageRelat,
  'gs-link-sac':    PageLinkSAC,
  'ld-fin':         PageFin,
  'ld-ia':          PageIA,
  'ld-prod':        PageProd,
  'tk-abrir':       PageTicketAbrir,
  'tk-meus':        PageTicketMeus,
  'tk-dev':         PageTicketDev,
  'tk-feed':        PageTicketFeed,
};
