<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?>
<style>
/* ── Layout geral ── */
.ars-wrap{display:grid;grid-template-columns:1fr 340px;gap:16px;align-items:start}
@media(max-width:900px){.ars-wrap{grid-template-columns:1fr}}

/* ── Painel de disparo ── */
.ars-fire{background:#fff;border:1px solid #e2e6ea;border-radius:12px;padding:20px}
.ars-fire h3{font-size:15px;font-weight:700;color:#1e3a5f;margin:0 0 16px;display:flex;align-items:center;gap:8px}
.ars-section{margin-bottom:16px}
.ars-label{font-size:11px;font-weight:700;color:#888;text-transform:uppercase;letter-spacing:.5px;margin-bottom:6px;display:block}
.api-chip{display:inline-flex;align-items:center;gap:5px;padding:4px 10px;border:1px solid #d0d8e4;border-radius:20px;font-size:12px;cursor:pointer;margin:3px;background:#fff;transition:all .15s}
.api-chip input{margin:0}
.api-chip:has(input:checked){background:#1e3a5f;border-color:#1e3a5f;color:#fff}

/* ── Tribunais ── */
.trib-region{margin-bottom:10px}
.trib-region-title{font-size:10.5px;font-weight:700;color:#888;text-transform:uppercase;letter-spacing:.4px;margin-bottom:5px;display:flex;align-items:center;gap:6px}
.trib-chip{display:inline-flex;align-items:center;gap:4px;padding:3px 8px;border:1px solid #d0d8e4;border-radius:4px;font-size:11px;cursor:pointer;margin:2px;background:#fff;transition:all .1s}
.trib-chip input{margin:0;width:12px;height:12px}
.trib-chip:has(input:checked){background:#e3f2fd;border-color:#1565c0;color:#1565c0;font-weight:700}
.trib-chip.trab:has(input:checked){background:#fce4ec;border-color:#c62828;color:#c62828}
.trib-chip.fed:has(input:checked){background:#e8f5e9;border-color:#2e7d32;color:#2e7d32}
.trib-chip.sup:has(input:checked){background:#f3e5f5;border-color:#6a1b9a;color:#6a1b9a}
.sel-btns{display:flex;gap:5px;flex-wrap:wrap;margin-bottom:8px}
.sel-btn{padding:3px 10px;font-size:11px;border:1px solid #d0d8e4;border-radius:4px;background:#fff;cursor:pointer;font-weight:600}
.sel-btn:hover{background:#f0f4f8}

/* ── Botão investigar ── */
#btn-disparar{width:100%;padding:11px;font-size:14px;font-weight:700;border-radius:8px}

/* ── Loading ── */
#inv-loading{text-align:center;padding:30px;display:none}
#inv-loading .fa{font-size:28px;color:#1e3a5f;display:block;margin-bottom:10px}
#loading-txt{font-size:13px;color:#888;min-height:20px}

/* ── Resultados ── */
.res-bloco{background:#fff;border:1px solid #e2e6ea;border-left:4px solid #1e3a5f;border-radius:0 8px 8px 0;padding:12px 14px;margin-bottom:10px}
.res-bloco.verde{border-left-color:#2e7d32}
.res-bloco.vermelho{border-left-color:#c0392b}
.res-bloco.laranja{border-left-color:#e65100}
.res-bloco h5{font-size:13px;font-weight:700;color:#1e3a5f;margin:0 0 8px;display:flex;align-items:center;gap:7px}
.res-bloco table{font-size:11.5px;width:100%;margin-top:6px}
.res-bloco th{background:#f8fafc;padding:5px 8px;font-size:10.5px;text-transform:uppercase;letter-spacing:.3px;color:#888}
.res-bloco td{padding:6px 8px;border-bottom:1px solid #f0f2f5}
.res-bloco tr:last-child td{border:none}
.res-bloco tr.autor td{background:#f0fff4}
.pill{display:inline-block;padding:2px 8px;border-radius:10px;font-size:10.5px;font-weight:700}
.pill-verde{background:#e8f5e9;color:#2e7d32}
.pill-laranja{background:#fff3e0;color:#e65100}
.pill-vermelho{background:#ffebee;color:#c0392b}
.pill-cinza{background:#f5f5f5;color:#888}

/* ── Alertas ── */
.alerta-item{padding:10px 12px;border-radius:6px;margin-bottom:8px;font-size:12.5px}
.alerta-alta{background:#ffebee;border-left:3px solid #c0392b}
.alerta-media{background:#fff3e0;border-left:3px solid #e65100}
.alerta-baixa{background:#f5f5f5;border-left:3px solid #aaa}
.alerta-item strong{display:block;margin-bottom:3px}
.alerta-item .tese{font-size:11.5px;color:#555;margin-top:4px;font-style:italic}

/* ── Painel lateral de APIs ── */
.ars-sidebar{background:#fff;border:1px solid #e2e6ea;border-radius:12px;padding:16px}
.ars-sidebar h4{font-size:13px;font-weight:700;color:#1e3a5f;margin:0 0 12px}
.api-info-card{padding:8px 0;border-bottom:1px solid #f4f6f8;display:flex;align-items:flex-start;gap:8px}
.api-info-card:last-child{border:none}
.api-info-card .ic{font-size:18px;width:24px;text-align:center;flex-shrink:0}
.api-info-card .nome{font-size:12.5px;font-weight:700;color:#333}
.api-info-card .desc{font-size:11px;color:#888}
.tag{display:inline-block;padding:1px 6px;border-radius:3px;font-size:10px;font-weight:700;margin-left:4px}
.tag-free{background:#e8f5e9;color:#2e7d32}.tag-token{background:#fff3e0;color:#e65100}.tag-jud{background:#e3f2fd;color:#1565c0}

/* ── Score ── */
.score-wrap{text-align:center;padding:14px;background:#f8fafc;border-radius:8px;margin-bottom:14px}
.score-num{font-size:36px;font-weight:700;color:#1e3a5f}
.score-bar{height:8px;background:#e9ecef;border-radius:4px;overflow:hidden;margin:6px 0}
.score-fill{height:100%;border-radius:4px;transition:width .6s}
</style>

<section class="content-header">
    <h1><i class="fa fa-binoculars"></i> Arsenal de Investigação &nbsp;<small style="font-weight:400;color:#888"><?php echo htmlspecialchars($exp->devedor_nome) ?></small></h1>
    <ol class="breadcrumb">
        <li><a href="<?php echo site_url('admin') ?>"><i class="fa fa-dashboard"></i></a></li>
        <li><a href="<?php echo site_url('admin/patrimonio') ?>">Busca Patrimonial</a></li>
        <li><a href="<?php echo site_url('admin/patrimonio/view/'.$exp->id) ?>"><?php echo htmlspecialchars($exp->devedor_nome) ?></a></li>
        <li class="active">Arsenal</li>
    </ol>
</section>

<section class="content">
<div class="ars-wrap">

<!-- ── PAINEL PRINCIPAL ── -->
<div>

  <!-- Painel de disparo -->
  <div class="ars-fire">
    <h3><i class="fa fa-rocket" style="color:#e65100"></i> Disparar Investigação</h3>

    <!-- Documento -->
    <div class="ars-section">
      <span class="ars-label">Documento do devedor (CNPJ/CPF)</span>
      <input type="text" id="doc-principal" class="form-control"
             value="<?php echo htmlspecialchars($exp->devedor_doc) ?>"
             placeholder="CPF ou CNPJ" style="max-width:260px">
    </div>

    <!-- Nome para DataJud -->
    <div class="ars-section">
      <span class="ars-label">Nome para busca no DataJud</span>
      <input type="text" id="nome-datajud" class="form-control"
             value="<?php echo htmlspecialchars($exp->devedor_nome) ?>"
             placeholder="Nome completo ou razão social">
      <div style="font-size:11px;color:#888;margin-top:4px">
        <i class="fa fa-info-circle"></i>
        O DataJud indexa processos por <strong>nome da parte</strong>, não por CNPJ/CPF (LGPD).
        Use o nome exato como aparece nos processos — ex: <em>"AL EMPREENDIMENTOS S.A"</em> sem abreviações.
      </div>
    </div>

    <!-- APIs -->
    <div class="ars-section">
      <span class="ars-label">APIs a consultar</span>
      <div>
        <label class="api-chip"><input type="checkbox" class="api-check" value="cnpj" checked> 📊 CNPJ</label>
        <label class="api-chip"><input type="checkbox" class="api-check" value="datajud" checked id="chk-datajud"> ⚖️ DataJud</label>
        <label class="api-chip"><input type="checkbox" class="api-check" value="transparencia"> 🏛️ Transparência</label>
        <label class="api-chip"><input type="checkbox" class="api-check" value="sancoes"> 🚫 Sanções</label>
        <label class="api-chip"><input type="checkbox" class="api-check" value="offshore"> 🌍 Offshore</label>
      </div>
    </div>

    <!-- Tribunais -->
    <div class="ars-section" id="box-tribunais">
      <span class="ars-label">Tribunais (DataJud)</span>
      <div class="sel-btns">
        <button type="button" class="sel-btn" data-sel="all">✓ Todos</button>
        <button type="button" class="sel-btn" data-sel="none">✗ Nenhum</button>
        <button type="button" class="sel-btn" data-sel="pe">PE</button>
        <button type="button" class="sel-btn" data-sel="ne">Nordeste</button>
        <button type="button" class="sel-btn" data-sel="nac">Nacional</button>
        <button type="button" class="sel-btn" data-sel="sup">Superiores</button>
      </div>

      <div class="trib-region">
        <div class="trib-region-title">🟦 Pernambuco (padrão)</div>
        <label class="trib-chip"><input type="checkbox" class="trib-check" value="tjpe" checked> TJPE</label>
        <label class="trib-chip trab"><input type="checkbox" class="trib-check" value="trt6" checked> TRT 6ª</label>
      </div>
      <div class="trib-region">
        <div class="trib-region-title">🟩 Nordeste — TJs</div>
        <label class="trib-chip"><input type="checkbox" class="trib-check" value="tjpb"> TJPB</label>
        <label class="trib-chip"><input type="checkbox" class="trib-check" value="tjal"> TJAL</label>
        <label class="trib-chip"><input type="checkbox" class="trib-check" value="tjce"> TJCE</label>
        <label class="trib-chip"><input type="checkbox" class="trib-check" value="tjrn"> TJRN</label>
        <label class="trib-chip"><input type="checkbox" class="trib-check" value="tjma"> TJMA</label>
        <label class="trib-chip"><input type="checkbox" class="trib-check" value="tjpi"> TJPI</label>
        <label class="trib-chip"><input type="checkbox" class="trib-check" value="tjba"> TJBA</label>
        <label class="trib-chip"><input type="checkbox" class="trib-check" value="tjse"> TJSE</label>
      </div>
      <div class="trib-region">
        <div class="trib-region-title">🟥 Nordeste — TRTs</div>
        <label class="trib-chip trab"><input type="checkbox" class="trib-check" value="trt7"> TRT 7ª (CE)</label>
        <label class="trib-chip trab"><input type="checkbox" class="trib-check" value="trt13"> TRT 13ª (PB)</label>
        <label class="trib-chip trab"><input type="checkbox" class="trib-check" value="trt16"> TRT 16ª (MA)</label>
        <label class="trib-chip trab"><input type="checkbox" class="trib-check" value="trt19"> TRT 19ª (AL)</label>
        <label class="trib-chip trab"><input type="checkbox" class="trib-check" value="trt20"> TRT 20ª (SE)</label>
        <label class="trib-chip trab"><input type="checkbox" class="trib-check" value="trt21"> TRT 21ª (RN)</label>
        <label class="trib-chip trab"><input type="checkbox" class="trib-check" value="trt22"> TRT 22ª (PI)</label>
      </div>
      <div class="trib-region">
        <div class="trib-region-title">🟨 Federal</div>
        <label class="trib-chip fed"><input type="checkbox" class="trib-check" value="trf1"> TRF 1ª</label>
        <label class="trib-chip fed"><input type="checkbox" class="trib-check" value="trf2"> TRF 2ª</label>
        <label class="trib-chip fed"><input type="checkbox" class="trib-check" value="trf3"> TRF 3ª</label>
        <label class="trib-chip fed"><input type="checkbox" class="trib-check" value="trf4"> TRF 4ª</label>
        <label class="trib-chip fed"><input type="checkbox" class="trib-check" value="trf5"> TRF 5ª</label>
        <label class="trib-chip fed"><input type="checkbox" class="trib-check" value="trf6"> TRF 6ª</label>
      </div>
      <div class="trib-region">
        <div class="trib-region-title">🟪 Superiores <small style="font-weight:400;text-transform:none">(STF não disponível no DataJud)</small></div>
        <label class="trib-chip sup"><input type="checkbox" class="trib-check" value="stj"> STJ</label>
        <label class="trib-chip sup"><input type="checkbox" class="trib-check" value="tst"> TST</label>
      </div>
      <div class="trib-region">
        <div class="trib-region-title">🟦 Sudeste</div>
        <label class="trib-chip"><input type="checkbox" class="trib-check" value="tjsp"> TJSP</label>
        <label class="trib-chip"><input type="checkbox" class="trib-check" value="tjrj"> TJRJ</label>
        <label class="trib-chip"><input type="checkbox" class="trib-check" value="tjmg"> TJMG</label>
        <label class="trib-chip"><input type="checkbox" class="trib-check" value="tjes"> TJES</label>
        <label class="trib-chip trab"><input type="checkbox" class="trib-check" value="trt1"> TRT 1ª (RJ)</label>
        <label class="trib-chip trab"><input type="checkbox" class="trib-check" value="trt2"> TRT 2ª (SP)</label>
        <label class="trib-chip trab"><input type="checkbox" class="trib-check" value="trt3"> TRT 3ª (MG)</label>
        <label class="trib-chip trab"><input type="checkbox" class="trib-check" value="trt15"> TRT 15ª (Camp.)</label>
        <label class="trib-chip trab"><input type="checkbox" class="trib-check" value="trt17"> TRT 17ª (ES)</label>
      </div>
      <div class="trib-region">
        <div class="trib-region-title">🟦 Sul</div>
        <label class="trib-chip"><input type="checkbox" class="trib-check" value="tjrs"> TJRS</label>
        <label class="trib-chip"><input type="checkbox" class="trib-check" value="tjsc"> TJSC</label>
        <label class="trib-chip"><input type="checkbox" class="trib-check" value="tjpr"> TJPR</label>
        <label class="trib-chip trab"><input type="checkbox" class="trib-check" value="trt4"> TRT 4ª (RS)</label>
        <label class="trib-chip trab"><input type="checkbox" class="trib-check" value="trt9"> TRT 9ª (PR)</label>
        <label class="trib-chip trab"><input type="checkbox" class="trib-check" value="trt12"> TRT 12ª (SC)</label>
      </div>
      <div class="trib-region">
        <div class="trib-region-title">🟦 Centro-Oeste / Norte</div>
        <label class="trib-chip"><input type="checkbox" class="trib-check" value="tjdft"> TJDFT</label>
        <label class="trib-chip"><input type="checkbox" class="trib-check" value="tjgo"> TJGO</label>
        <label class="trib-chip"><input type="checkbox" class="trib-check" value="tjmt"> TJMT</label>
        <label class="trib-chip"><input type="checkbox" class="trib-check" value="tjms"> TJMS</label>
        <label class="trib-chip"><input type="checkbox" class="trib-check" value="tjam"> TJAM</label>
        <label class="trib-chip"><input type="checkbox" class="trib-check" value="tjpa"> TJPA</label>
        <label class="trib-chip"><input type="checkbox" class="trib-check" value="tjro"> TJRO</label>
        <label class="trib-chip"><input type="checkbox" class="trib-check" value="tjto"> TJTO</label>
        <label class="trib-chip"><input type="checkbox" class="trib-check" value="tjac"> TJAC</label>
        <label class="trib-chip"><input type="checkbox" class="trib-check" value="tjap"> TJAP</label>
        <label class="trib-chip"><input type="checkbox" class="trib-check" value="tjrr"> TJRR</label>
        <label class="trib-chip trab"><input type="checkbox" class="trib-check" value="trt8"> TRT 8ª (PA)</label>
        <label class="trib-chip trab"><input type="checkbox" class="trib-check" value="trt10"> TRT 10ª (DF)</label>
        <label class="trib-chip trab"><input type="checkbox" class="trib-check" value="trt11"> TRT 11ª (AM)</label>
        <label class="trib-chip trab"><input type="checkbox" class="trib-check" value="trt14"> TRT 14ª (RO)</label>
        <label class="trib-chip trab"><input type="checkbox" class="trib-check" value="trt18"> TRT 18ª (GO)</label>
        <label class="trib-chip trab"><input type="checkbox" class="trib-check" value="trt23"> TRT 23ª (MT)</label>
        <label class="trib-chip trab"><input type="checkbox" class="trib-check" value="trt24"> TRT 24ª (MS)</label>
      </div>

      <!-- Domínio -->
      <div style="margin-top:10px">
        <span class="ars-label">Domínio (opcional)</span>
        <div style="display:flex;gap:8px;align-items:center">
          <input type="text" id="dominio-input" class="form-control" placeholder="exemplo.com.br" style="max-width:200px">
          <label style="font-size:12px;cursor:pointer;white-space:nowrap"><input type="checkbox" class="api-check" value="dominio"> Consultar Registro.br</label>
        </div>
      </div>
    </div>

    <button id="btn-disparar" class="btn btn-primary">
      <i class="fa fa-rocket"></i> Investigar
    </button>
  </div>

  <!-- Loading -->
  <div id="inv-loading" style="margin-top:12px">
    <i class="fa fa-spin fa-circle-o-notch"></i>
    <div id="loading-txt">Iniciando investigação...</div>
  </div>

  <!-- Resultados -->
  <div id="inv-resultado" style="margin-top:14px;display:none">

    <!-- Score -->
    <div class="score-wrap" id="score-area" style="display:none">
      <div style="font-size:11px;color:#888;text-transform:uppercase;letter-spacing:.5px;margin-bottom:4px">Score de Risco Patrimonial</div>
      <div class="score-num" id="score-num">0</div>
      <div class="score-bar"><div class="score-fill" id="score-fill" style="width:0%"></div></div>
      <div id="acoes-recomendadas" style="margin-top:8px;display:flex;gap:6px;flex-wrap:wrap;justify-content:center"></div>
    </div>

    <!-- Alertas -->
    <div id="bloco-alertas" style="display:none">
      <h5 style="font-size:13px;font-weight:700;color:#c0392b;margin:0 0 8px"><i class="fa fa-exclamation-triangle"></i> Alertas de Correlação</h5>
      <div id="alertas-content"></div>
    </div>

    <!-- CNPJ -->
    <div id="bloco-cnpj" class="res-bloco" style="display:none">
      <h5><i class="fa fa-building"></i> Dados CNPJ</h5>
      <div id="cnpj-content"></div>
    </div>

    <!-- DataJud -->
    <div id="bloco-datajud" class="res-bloco" style="display:none">
      <h5><i class="fa fa-balance-scale"></i> DataJud CNJ</h5>
      <div id="datajud-content"></div>
    </div>

    <!-- Transparência -->
    <div id="bloco-transp" class="res-bloco" style="display:none">
      <h5><i class="fa fa-university"></i> Portal da Transparência</h5>
      <div id="transp-content"></div>
    </div>

    <!-- Sanções -->
    <div id="bloco-sancoes" class="res-bloco vermelho" style="display:none">
      <h5><i class="fa fa-ban"></i> Sanções CEIS/CNEP</h5>
      <div id="sancoes-content"></div>
    </div>

    <!-- Offshore -->
    <div id="bloco-offshore" class="res-bloco vermelho" style="display:none">
      <h5><i class="fa fa-globe"></i> ICIJ Offshore Leaks</h5>
      <div id="offshore-content"></div>
    </div>

    <!-- Domínio -->
    <div id="bloco-dominio" class="res-bloco" style="display:none">
      <h5><i class="fa fa-globe"></i> Domínio Registro.br</h5>
      <div id="dominio-content"></div>
    </div>

    <!-- Links manuais -->
    <div id="bloco-manuais" class="res-bloco" style="display:none;border-left-color:#f39c12">
      <h5><i class="fa fa-hand-o-right"></i> Consultas Manuais Recomendadas</h5>
      <p style="font-size:11.5px;color:#888;margin:0 0 8px">Fontes sem API gratuita — clique para abrir já direcionado:</p>
      <div id="manuais-content"></div>
    </div>

  </div><!-- /inv-resultado -->

  <!-- Alertas salvos -->
  <?php if(!empty($alertas_fraude)): ?>
  <div style="margin-top:14px">
    <h5 style="font-size:13px;font-weight:700;color:#1e3a5f;margin-bottom:8px"><i class="fa fa-flag"></i> Alertas Salvos (<?php echo count($alertas_fraude) ?>)</h5>
    <?php foreach($alertas_fraude as $al):
      $al_rel = $al->relevancia ?? 'media';
      $cl = $al_rel==='alta'?'alerta-alta':($al_rel==='media'?'alerta-media':'alerta-baixa');
    ?>
    <div class="alerta-item <?php echo $cl ?>">
      <strong><?php echo ucwords(str_replace('_',' ',$al->tipo)) ?>
        <span class="pill <?php echo $al_rel==='alta'?'pill-vermelho':($al_rel==='media'?'pill-laranja':'pill-cinza') ?>"><?php echo ucfirst($al_rel) ?></span>
      </strong>
      <?php echo htmlspecialchars($al->descricao) ?>
      <?php if(!empty($al->tese_juridica)): ?>
      <div class="tese"><?php echo htmlspecialchars($al->tese_juridica) ?></div>
      <?php endif; ?>
      <div style="margin-top:6px;display:flex;gap:6px">
        <?php if($al->status==='pendente'): ?>
        <a href="<?php echo site_url('admin/patrimonio/alerta_usar/'.$al->id) ?>" class="btn btn-success btn-xs">Usar em petição</a>
        <a href="<?php echo site_url('admin/patrimonio/alerta_descartar/'.$al->id) ?>" class="btn btn-default btn-xs">Descartar</a>
        <?php else: ?><span class="pill pill-cinza"><?php echo ucfirst($al->status) ?></span><?php endif; ?>
      </div>
    </div>
    <?php endforeach; ?>
  </div>
  <?php endif; ?>

</div><!-- /col principal -->

<!-- ── SIDEBAR ── -->
<div class="ars-sidebar">
  <h4><i class="fa fa-plug"></i> APIs Disponíveis</h4>

  <div class="api-info-card">
    <span class="ic">📊</span>
    <div><div class="nome">CNPJ (BrasilAPI/OpenCNPJ)<span class="tag tag-free">Gratuita</span></div>
    <div class="desc">QSA, capital social, CNAE, situação cadastral</div></div>
  </div>
  <div class="api-info-card">
    <span class="ic">⚖️</span>
    <div><div class="nome">DataJud CNJ<span class="tag tag-free">Pública</span></div>
    <div class="desc">91 tribunais — detecta onde devedor é credor</div></div>
  </div>
  <div class="api-info-card">
    <span class="ic">🏛️</span>
    <div><div class="nome">Portal Transparência<span class="tag tag-token">Token</span></div>
    <div class="desc">Contratos, notas fiscais com poder público</div></div>
  </div>
  <div class="api-info-card">
    <span class="ic">🚫</span>
    <div><div class="nome">Sanções CEIS/CNEP<span class="tag tag-token">Token</span></div>
    <div class="desc">Empresas inidôneas/punidas</div></div>
  </div>
  <div class="api-info-card">
    <span class="ic">🌍</span>
    <div><div class="nome">ICIJ Offshore Leaks<span class="tag tag-free">Pública</span></div>
    <div class="desc">Panama/Pandora Papers</div></div>
  </div>
  <div class="api-info-card">
    <span class="ic">🌐</span>
    <div><div class="nome">Registro.br (domínio)<span class="tag tag-free">Gratuita</span></div>
    <div class="desc">Detecta e-commerce não declarado</div></div>
  </div>
  <div class="api-info-card">
    <span class="ic">📋</span>
    <div><div class="nome">Consulta Manual<span class="tag" style="background:#eee;color:#777">Sem API</span></div>
    <div class="desc">INPI · TSE · CVM · ONR · CENSEC</div></div>
  </div>

  <div style="margin-top:14px;border-top:1px solid #f0f2f5;padding-top:12px">
    <a href="<?php echo site_url('admin/patrimonio/configuracoes') ?>" class="btn btn-default btn-sm btn-block">
      <i class="fa fa-key"></i> Configurar Tokens
    </a>
    <a href="<?php echo site_url('admin/patrimonio/diagnostico') ?>" class="btn btn-default btn-sm btn-block" style="margin-top:5px">
      <i class="fa fa-heartbeat"></i> Diagnóstico de APIs
    </a>
    <a href="<?php echo site_url('admin/patrimonio/dossie_ia/'.$exp->id) ?>" class="btn btn-sm btn-block" style="margin-top:5px;background:#7b1fa2;border-color:#6a1b9a;color:#fff">
      <i class="fa fa-robot"></i> Dossiê com IA
    </a>
  </div>
</div>

</div><!-- /ars-wrap -->
</section>

<script>
var peticaoUrl = '<?php echo site_url("admin/patrimonio/peticao_modelo/".$exp->id) ?>?tipo=penhora_rosto';
var grupos = {
    all:  ['tjpe','trt6','tjpb','tjal','tjce','tjrn','tjma','tjpi','tjba','tjse','trt7','trt13','trt16','trt19','trt20','trt21','trt22','trf1','trf2','trf3','trf4','trf5','trf6','stj','tst','tjsp','tjrj','tjmg','tjes','trt1','trt2','trt3','trt15','trt17','tjrs','tjsc','tjpr','trt4','trt9','trt12','tjdft','tjgo','tjmt','tjms','tjam','tjpa','tjro','tjto','tjac','tjap','tjrr','trt8','trt10','trt11','trt14','trt18','trt23','trt24'],
    none: [],
    pe:   ['tjpe','trt6'],
    ne:   ['tjpe','trt6','tjpb','tjal','tjce','tjrn','tjma','tjpi','tjba','tjse','trt7','trt13','trt16','trt19','trt20','trt21','trt22','trf5'],
    nac:  ['tjpe','trt6','tjsp','tjrj','tjmg','trt1','trt2','trt3','trf1','trf5','stj','tst'],
    sup:  ['stj','tst']
};
var corTipo = {trabalhista:'#c62828',federal:'#2e7d32',estadual:'#1565c0',superior:'#6a1b9a'};

$('.sel-btn').on('click', function(){
    var r = $(this).data('sel');
    document.querySelectorAll('.trib-check').forEach(function(c){ c.checked = false; });
    (grupos[r]||[]).forEach(function(v){
        var el = document.querySelector('.trib-check[value="'+v+'"]');
        if(el) el.checked = true;
    });
});

$('#chk-datajud').on('change', function(){
    document.getElementById('box-tribunais').style.display = this.checked ? '' : 'none';
});

$('#btn-disparar').on('click', function(){
    var doc = $('#doc-principal').val();
    var dominio = $('#dominio-input').val();
    var apis = [], tribunais = [];
    document.querySelectorAll('.api-check:checked').forEach(function(c){ apis.push(c.value); });
    document.querySelectorAll('.trib-check:checked').forEach(function(c){ tribunais.push(c.value); });
    if(!doc){ alert('Informe o documento.'); return; }
    if(!apis.length){ alert('Selecione ao menos uma API.'); return; }
    if(apis.indexOf('datajud')>=0 && !tribunais.length) tribunais = ['tjpe','trt6'];

    $(this).prop('disabled',true).html('<i class="fa fa-spin fa-spinner"></i> Investigando...');
    $('#inv-loading').show();
    $('#inv-resultado').hide();

    var steps=['Consultando CNPJ...','Varrendo tribunais ('+tribunais.length+')...','Cruzando Transparência...','Checando sanções...','Buscando Offshores...','Analisando correlações...'];
    var si=0, timer=setInterval(function(){
        if(si<steps.length) $('#loading-txt').text(steps[si++]);
        else clearInterval(timer);
    },1200);

    $.ajax({
        url:'<?php echo site_url("admin/patrimonio/api_arsenal") ?>',
        type:'POST',
        data:{documento:doc, nome_datajud:$('#nome-datajud').val(), expediente_id:<?php echo $exp->id ?>, apis:apis, dominio:dominio, tribunais:tribunais},
        success:function(r){
            clearInterval(timer);
            $('#inv-loading').hide();
            $('#inv-resultado').show();
            $('#btn-disparar').prop('disabled',false).html('<i class="fa fa-rocket"></i> Investigar');
            renderRes(r);
        },
        error:function(xhr){
            clearInterval(timer);
            $('#inv-loading').hide();
            $('#btn-disparar').prop('disabled',false).html('<i class="fa fa-rocket"></i> Investigar');
            alert('Erro: ' + (xhr.responseText ? xhr.responseText.substring(0,300) : 'Falha na requisição'));
        }
    });
});

function fmt(v){ return 'R$ ' + (parseFloat(v)||0).toLocaleString('pt-BR',{minimumFractionDigits:2}); }

function renderRes(r){
    var score = 0, acoes = '';

    // ── Alertas ─────────────────────────────────────────────────
    if(r.alertas && r.alertas.length){
        var h='';
        r.alertas.forEach(function(al){
            var cl = al.relevancia==='alta'?'alerta-alta':(al.relevancia==='media'?'alerta-media':'alerta-baixa');
            var pil = al.relevancia==='alta'?'pill-vermelho':(al.relevancia==='media'?'pill-laranja':'pill-cinza');
            h+='<div class="alerta-item '+cl+'"><strong>'+al.tipo.replace(/_/g,' ').replace(/\b\w/g,function(c){return c.toUpperCase();})+
               ' <span class="pill '+pil+'">'+al.relevancia.charAt(0).toUpperCase()+al.relevancia.slice(1)+'</span></strong>'+
               al.descricao+(al.tese?'<div class="tese">'+al.tese+'</div>':'')+'</div>';
            if(al.relevancia==='alta') score+=30;
            else if(al.relevancia==='media') score+=15;
        });
        $('#alertas-content').html(h);
        $('#bloco-alertas').show();
    }

    // ── CNPJ ────────────────────────────────────────────────────
    if(r.cnpj && !r.cnpj.erro){
        var c=r.cnpj, h='';
        h+='<table class="table" style="font-size:12.5px;margin:0"><tbody>';
        h+='<tr><td style="width:130px;color:#888;font-weight:700">Razão Social</td><td><strong>'+c.razao_social+'</strong></td></tr>';
        h+='<tr><td style="color:#888;font-weight:700">Situação</td><td><span class="pill '+(c.situacao&&c.situacao.toLowerCase().includes('ativ')?'pill-verde':'pill-vermelho')+'">'+c.situacao+'</span></td></tr>';
        h+='<tr><td style="color:#888;font-weight:700">Município</td><td>'+c.municipio+'</td></tr>';
        if(c.capital) h+='<tr><td style="color:#888;font-weight:700">Capital Social</td><td><strong style="color:#1e3a5f">'+fmt(c.capital)+'</strong></td></tr>';
        if(c.atividade) h+='<tr><td style="color:#888;font-weight:700">CNAE</td><td>'+c.atividade+'</td></tr>';
        if(c.email) h+='<tr><td style="color:#888;font-weight:700">E-mail</td><td>'+c.email+'</td></tr>';
        h+='</tbody></table>';
        if(c.socios && c.socios.length){
            h+='<div style="margin-top:8px"><span style="font-size:11px;font-weight:700;color:#888;text-transform:uppercase">Quadro Societário</span>';
            c.socios.forEach(function(s){
                var ini = s.nome.split(' ').map(function(p){return p[0]||'';}).join('').substring(0,2).toUpperCase();
                h+='<div style="display:flex;align-items:center;gap:8px;padding:5px 0;border-bottom:1px solid #f0f2f5">'+
                   '<div style="width:28px;height:28px;border-radius:50%;background:linear-gradient(135deg,#4a9fd4,#1e3a5f);display:flex;align-items:center;justify-content:center;font-size:10px;font-weight:700;color:#fff;flex-shrink:0">'+ini+'</div>'+
                   '<div><div style="font-size:12.5px;font-weight:600">'+s.nome+'</div>'+
                   '<div style="font-size:11px;color:#888">'+s.qual+(s.cpf?' — CPF: '+s.cpf:'')+'</div></div></div>';
            });
            h+='</div>';
            score += 10;
        }
        h+='<div style="font-size:10.5px;color:#aaa;margin-top:6px">Fonte: '+c.fonte+'</div>';
        $('#cnpj-content').html(h);
        $('#bloco-cnpj').show();
    }

    // ── DataJud ─────────────────────────────────────────────────
    if(r.datajud !== undefined){
        var d=r.datajud, h='';
        h+='<div style="display:flex;gap:8px;flex-wrap:wrap;margin-bottom:8px">';
        h+='<span class="pill pill-cinza">'+d.total+' processo(s)</span>';
        if(d.como_credor>0){ h+='<span class="pill pill-verde">⚡ '+d.como_credor+' como AUTOR/CREDOR</span>'; score+=25; acoes+='<a href="'+peticaoUrl+'" class="btn btn-success btn-xs"><i class="fa fa-gavel"></i> Penhora no Rosto dos Autos</a> '; }
        if(d.tribunais_ok>=0) h+='<span class="pill pill-cinza">'+d.tribunais_ok+' tribunal(is) ok</span>';
        if(d.tribunais_erro && d.tribunais_erro.length) h+='<span class="pill pill-vermelho">Erro: '+d.tribunais_erro.join(', ')+'</span>';
        h+='</div>';
        if(d.processos && d.processos.length){
            h+='<table><thead><tr><th>Número</th><th>Tribunal</th><th>Classe</th><th>Valor</th><th>Polo</th><th>Último mov.</th></tr></thead><tbody>';
            d.processos.forEach(function(p){
                var cor = corTipo[p.tribunal_tipo]||'#888';
                h+='<tr'+(p.como_autor?' class="autor"':'')+'>';
                h+='<td><code style="font-size:10px">'+p.numero+'</code></td>';
                h+='<td><span style="color:'+cor+';font-weight:700;font-size:11px">'+p.tribunal+'</span></td>';
                h+='<td style="font-size:11px">'+p.classe+(p.assunto?'<br><span style="color:#aaa">'+p.assunto+'</span>':'')+'</td>';
                h+='<td style="white-space:nowrap;font-size:11px">'+fmt(p.valor)+'</td>';
                h+='<td>'+(p.como_autor?'<span class="pill pill-verde">AUTOR</span>':'<span class="pill pill-cinza">RÉU</span>')+'</td>';
                h+='<td style="font-size:10px;color:#888">'+p.ultimo_movimento+'</td></tr>';
            });
            h+='</tbody></table>';
        } else {
            h+='<p style="color:#aaa;font-size:12.5px;text-align:center;padding:10px 0;margin:0">Nenhum processo encontrado nos tribunais consultados.<br><small>Dica: o DataJud busca por NOME da parte. Verifique se o nome no expediente corresponde ao nome nos processos.</small></p>';
        }
        $('#datajud-content').html(h);
        $('#bloco-datajud').show();
    }

    // ── Transparência ───────────────────────────────────────────
    if(r.transparencia && r.transparencia.total>0){
        var t=r.transparencia, h='<p style="font-size:12.5px">'+t.total+' contrato(s) com poder público</p><table><thead><tr><th>Objeto</th><th>Valor</th><th>Órgão</th></tr></thead><tbody>';
        t.contratos.forEach(function(c){ h+='<tr><td>'+c.objeto+'</td><td style="white-space:nowrap">'+fmt(c.valor)+'</td><td style="font-size:11px">'+c.orgao+'</td></tr>'; });
        h+='</tbody></table>';
        score+=20;
        $('#transp-content').html(h);
        $('#bloco-transp').show();
    }

    // ── Sanções ─────────────────────────────────────────────────
    if(r.sancoes && r.sancoes.total>0){
        var s=r.sancoes, h='<p style="font-size:12.5px">'+s.total+' sanção(ões) administrativa(s)</p><table><thead><tr><th>Tipo</th><th>Órgão</th><th>Início</th><th>Fim</th></tr></thead><tbody>';
        s.sancoes.forEach(function(sa){ h+='<tr><td>'+sa.tipo+'</td><td style="font-size:11px">'+sa.orgao+'</td><td>'+sa.dataInicio+'</td><td>'+sa.dataFim+'</td></tr>'; });
        h+='</tbody></table>';
        score+=15;
        $('#sancoes-content').html(h);
        $('#bloco-sancoes').show();
    }

    // ── Offshore ────────────────────────────────────────────────
    if(r.offshore && r.offshore.total>0){
        var o=r.offshore, h='<div class="pill pill-vermelho" style="margin-bottom:8px">'+o.total+' vinculação(ões) nos Panama/Pandora Papers</div><ul style="font-size:12px;margin:0;padding-left:18px">';
        o.entidades.forEach(function(e){ h+='<li>'+e.nome+' ('+e.tipo+') — '+e.pais+'</li>'; });
        h+='</ul>';
        score+=40;
        acoes+='<button class="btn btn-danger btn-xs"><i class="fa fa-globe"></i> Requerimento de Repatriação</button> ';
        $('#offshore-content').html(h);
        $('#bloco-offshore').show();
    }

    // ── Domínio ─────────────────────────────────────────────────
    if(r.dominio && r.dominio.dominio){
        var dm=r.dominio, h='<strong>'+dm.dominio+'</strong> — <span class="pill '+(dm.disponivel?'pill-cinza':'pill-vermelho')+'">'+(dm.disponivel?'Disponível':'REGISTRADO E ATIVO')+'</span>';
        $('#dominio-content').html(h);
        $('#bloco-dominio').show();
    }

    // ── Links manuais ───────────────────────────────────────────
    if(r.links_manuais && r.links_manuais.length){
        var h='';
        r.links_manuais.forEach(function(l){
            h+='<div style="padding:7px 0;border-bottom:1px solid #fef3cd"><strong style="font-size:12.5px">'+l.fonte+'</strong>'+
               ' <span class="pill pill-cinza" style="font-size:10px">'+l.motivo+'</span><br>'+
               '<a href="'+l.url+'" target="_blank" class="btn btn-xs btn-default" style="margin-top:4px"><i class="fa fa-external-link"></i> Abrir consulta</a></div>';
        });
        $('#manuais-content').html(h);
        $('#bloco-manuais').show();
    }

    // ── Score final ─────────────────────────────────────────────
    if(score > 0){
        score = Math.min(score, 100);
        var cor = score>=70?'#c0392b':(score>=40?'#e65100':'#2e7d32');
        $('#score-num').text(score).css('color', cor);
        $('#score-fill').css({'width':score+'%','background':cor});
        if(acoes) $('#acoes-recomendadas').html(acoes);
        $('#score-area').show();
    }
}
</script>
