<?php /* Dashboard principal pós-login */ ?>
<div class="page-header" style="display:flex;align-items:center;justify-content:space-between;gap:1rem;flex-wrap:wrap;">
  <div>
    <h1>Dashboard</h1>
    <p class="muted">Visão geral do negócio com KPIs, tendências e tempo real</p>
  </div>
  <div class="card" style="display:flex;gap:0.5rem;align-items:center;">
    <label class="muted">Período:</label>
    <input id="fStart" type="text" class="input js-datepicker" inputmode="numeric" placeholder="dd-mm-yyyy" aria-label="Início" />
    <span class="muted">a</span>
    <input id="fEnd" type="text" class="input js-datepicker" inputmode="numeric" placeholder="dd-mm-yyyy" aria-label="Fim" />
    <select id="fCanal" class="input">
      <option value="">Todos os canais</option>
      <option value="pdv">PDV</option>
      <option value="pedido">Pedidos</option>
      <option value="orcamento">Orçamentos</option>
    </select>
    <button id="btnApplyFilters" class="btn">Aplicar</button>
  </div>
  
  <div class="card" id="alertsBar" style="display:none; background:#fff7ed; border:1px solid #fed7aa; color:#7c2d12;">
    <strong>Alertas:</strong>
    <ul id="alertsList" style="margin:0.25rem 0 0 1rem;"></ul>
  </div>
</div>

<!-- Navegação por seções -->
<div class="tab-nav" role="tablist" aria-label="Navegação do dashboard">
  <a class="tab-btn active" href="#sec-resumo">Resumo</a>
  <a class="tab-btn" href="#sec-despesas">Despesas</a>
  <a class="tab-btn" href="#sec-receitas">Receitas</a>
  <a class="tab-btn" href="#sec-tendencias">Tendências</a>
  <a class="tab-btn" href="#sec-tempo-real">Tempo real</a>
  <a class="tab-btn" href="#sec-agenda">Agenda</a>
  <script>
    // Ativa visualmente o botão da aba conforme clique/âncora
    document.addEventListener('click', (e)=>{
      const a = e.target.closest('.tab-btn[href^="#"]'); if (!a) return;
      document.querySelectorAll('.tab-btn').forEach(b=>b.classList.remove('active'));
      a.classList.add('active');
    });
  </script>
</div>

<div id="sec-resumo"></div>
<!-- KPIs Financeiros -->
<section class="card" style="margin-top:0.75rem;">
  <h3 style="margin:0 0 0.5rem 0;">Despesas (Pagar)</h3>
  <div class="grid" style="grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 0.75rem;">
    <div class="card kpi accent-expense" id="kpiFinApagarTotal" data-lazy="finance-kpis" data-tip="Total pendente em despesas">
      <div class="kpi-row"><span class="kpi-icon">🔻</span><div class="muted title-expense">Total a pagar (pendente)</div></div>
      <div class="value">R$ 0,00</div>
      <div class="sub" id="kpiFinApagarTotalDelta" aria-live="polite">—</div>
    </div>
    <div class="card kpi accent-expense" id="kpiFinApagarHoje" data-lazy="finance-kpis" data-tip="Contas vencendo hoje">
      <div class="kpi-row"><span class="kpi-icon">⏰</span><div class="muted title-expense">Vencimentos hoje</div></div>
      <div class="value">0</div>
      <div class="sub" id="kpiFinApagarHojeDelta" aria-live="polite">—</div>
    </div>
    <div class="card kpi accent-expense" id="kpiFinApagarProx7" data-lazy="finance-kpis" data-tip="Despesas nos próximos 7 dias">
      <div class="kpi-row"><span class="kpi-icon">📅</span><div class="muted title-expense">Próximos 7 dias (pagar)</div></div>
      <div class="value">0</div>
      <div class="sub" id="kpiFinApagarProx7Delta" aria-live="polite">—</div>
    </div>
    <div class="card" id="kpiFinApagarProxDates" data-lazy="finance-kpis" data-tip="Próximos vencimentos de despesas">
      <div class="muted">Próximos 5 dias (pagar)</div>
      <div id="kpiFinApagarProxTotal5" style="font-size:1rem; font-weight:600;">R$ 0,00</div>
      <button id="btnPayNextDetail" class="btn btn-secondary" type="button" style="margin-top:0.25rem;">Detalhar</button>
    </div>
  </div>
</section>

<section class="card" style="margin-top:0.75rem;">
  <h3 style="margin:0 0 0.5rem 0;">Receitas (Receber)</h3>
  <div class="grid" style="grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 0.75rem;">
    <div class="card kpi accent-revenue" id="kpiFinAreceberTotal" data-lazy="finance-kpis" data-tip="Total pendente em receitas">
      <div class="kpi-row"><span class="kpi-icon">🔺</span><div class="muted title-revenue">Total a receber (pendente)</div></div>
      <div class="value">R$ 0,00</div>
      <div class="sub" id="kpiFinAreceberTotalDelta" aria-live="polite">—</div>
    </div>
    <div class="card kpi accent-revenue" id="kpiFinAreceberHoje" data-lazy="finance-kpis" data-tip="Recebimentos vencendo hoje">
      <div class="kpi-row"><span class="kpi-icon">⏰</span><div class="muted title-revenue">Receber hoje</div></div>
      <div class="value">0</div>
      <div class="sub" id="kpiFinAreceberHojeDelta" aria-live="polite">—</div>
    </div>
    <div class="card kpi accent-revenue" id="kpiFinAreceberProx7" data-lazy="finance-kpis" data-tip="Receitas nos próximos 7 dias">
      <div class="kpi-row"><span class="kpi-icon">📅</span><div class="muted title-revenue">Próximos 7 dias (receber)</div></div>
      <div class="value">0</div>
      <div class="sub" id="kpiFinAreceberProx7Delta" aria-live="polite">—</div>
    </div>
    <div class="card" id="kpiFinAreceberProxDates" data-lazy="finance-kpis" data-tip="Próximos recebimentos de receitas">
      <div class="muted">Próximos 5 dias (receber)</div>
      <div id="kpiFinAreceberProxTotal5" style="font-size:1rem; font-weight:600;">R$ 0,00</div>
      <button id="btnRecNextDetail" class="btn btn-secondary" type="button" style="margin-top:0.25rem;">Detalhar</button>
    </div>
  </div>
</section>
<div class="grid" style="grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 0.75rem;">
  <div class="card" id="kpiFatTotal" data-lazy="kpis">
    <div class="muted">Faturamento Total</div>
    <div style="font-size:1.5rem; font-weight:700;">R$ 0,00</div>
    <div class="muted" id="kpiFatTotalDelta">—</div>
  </div>
  <div class="card" id="kpiPedidosAbertos" data-lazy="kpis">
    <div class="muted">Pedidos Abertos</div>
    <div style="font-size:1.5rem; font-weight:700;">0</div>
    <div class="muted" id="kpiPedidosAbertosDelta">—</div>
  </div>
  <div class="card" id="kpiTicketMedio" data-lazy="kpis">
    <div class="muted">Ticket Médio</div>
    <div style="font-size:1.5rem; font-weight:700;">R$ 0,00</div>
    <div class="muted" id="kpiTicketMedioDelta">—</div>
  </div>
  <div class="card" id="kpiConversao" data-lazy="kpis">
    <div class="muted">Conversão (orc → ped)</div>
    <div style="font-size:1.5rem; font-weight:700;">0%</div>
    <div class="muted" id="kpiConversaoDelta">—</div>
  </div>
</div>

<!-- KPIs Fiscais -->
<div class="grid" style="grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 0.75rem; margin-top:0.75rem;">
  <div class="card" id="kpiFiscalAut" data-lazy="fiscal">
    <div class="muted">NFC-e Autorizadas</div>
    <div style="font-size:1.5rem; font-weight:700;">0</div>
    <div class="muted" id="kpiFiscalLast">Última emissão: —</div>
  </div>
  <div class="card" id="kpiFiscalRej" data-lazy="fiscal">
    <div class="muted">NFC-e Rejeitadas</div>
    <div style="font-size:1.5rem; font-weight:700;">0</div>
    <div class="muted" id="kpiFiscalErr">—</div>
  </div>
  <div class="card" id="kpiFiscalCanc" data-lazy="fiscal">
    <div class="muted">NFC-e Canceladas</div>
    <div style="font-size:1.5rem; font-weight:700;">0</div>
    <div class="muted">—</div>
  </div>
</div>

<div class="grid" style="grid-template-columns: 2fr 1fr; gap: 0.75rem; align-items:stretch; margin-top:0.75rem;">
  <div class="card" id="chartPred" data-lazy="charts" style="height:100%;display:flex;flex-direction:column;">
    <div style="display:flex;align-items:center;justify-content:space-between;">
      <h3 style="margin:0;">Tendência e Previsão (7d)</h3>
      <span class="muted" id="chartPredMeta">Meta diária: R$ 0,00</span>
    </div>
    <canvas id="predCanvas" width="900" height="360" style="width:100%;height:auto;display:block;margin-top:0.5rem;"></canvas>
  </div>
  <section class="card" id="sellerReport" data-lazy="sellers" aria-labelledby="sellerReportTitle" style="height:100%;display:flex;flex-direction:column;">
    <div style="display:flex;justify-content:space-between;align-items:center;gap:0.5rem;flex-wrap:wrap;">
      <h3 id="sellerReportTitle" style="margin:0;">Vendas por vendedor</h3>
      <div style="display:flex;gap:0.5rem;align-items:center;">
    <input id="svStart" type="text" class="input js-datepicker" inputmode="numeric" placeholder="dd-mm-yyyy" aria-label="Início" />
    <input id="svEnd" type="text" class="input js-datepicker" inputmode="numeric" placeholder="dd-mm-yyyy" aria-label="Fim" />
        <button id="svApply" class="btn btn-secondary">Aplicar</button>
        <button id="svExport" class="btn">Exportar CSV</button>
      </div>
    </div>
    <canvas id="sellerChart" width="900" height="320" style="width:100%;height:auto;margin-top:0.5rem;"></canvas>
    <div class="table-responsive" style="margin-top:0.5rem;">
      <table class="table">
        <thead><tr><th>Vendedor</th><th>Pedidos</th><th>Faturamento</th><th>Ticket Médio</th></tr></thead>
        <tbody id="svRows"><tr><td colspan="4" class="muted">Sem dados</td></tr></tbody>
      </table>
    </div>
</section>

<!-- Modal simples para detalhes financeiros próximos -->
<div id="finModal" style="display:none;position:fixed;inset:0;background:rgba(0,0,0,0.35);align-items:center;justify-content:center;z-index:1000;">
  <div style="background:#fff;border:1px solid #ddd;border-radius:6px;min-width:320px;max-width:520px;padding:0.75rem;box-shadow:0 8px 24px rgba(0,0,0,0.2);">
    <div style="display:flex;justify-content:space-between;align-items:center;gap:0.5rem;">
      <h4 id="finModalTitle" style="margin:0;">Detalhes</h4>
      <button id="finModalClose" class="btn btn-secondary" type="button">Fechar</button>
    </div>
    <div id="finModalBody" style="margin-top:0.5rem;max-height:260px;overflow:auto;"></div>
  </div>
  <script>
    (function(){
      const modal = document.getElementById('finModal');
      const btnClose = document.getElementById('finModalClose');
      if (btnClose) btnClose.addEventListener('click', ()=>{ modal.style.display='none'; });
      modal.addEventListener('click', (e)=>{ if (e.target === modal) modal.style.display='none'; });
    })();
  </script>
</div>
</div>

<!-- Quadros Financeiros -->
<div class="grid" style="grid-template-columns: 1fr 1fr; gap: 0.75rem; align-items:start; margin-top:0.75rem;">
  <section class="card accent-expense" id="financePayables" data-lazy="finance" aria-labelledby="payablesTitle">
    <div style="display:flex;justify-content:space-between;align-items:center;gap:0.5rem;flex-wrap:wrap;">
      <h3 id="payablesTitle" style="margin:0;" class="title-expense">Contas a pagar</h3>
      <div style="display:flex;gap:0.5rem;align-items:center;">
    <input id="fpStart" type="text" class="input js-datepicker" inputmode="numeric" placeholder="dd-mm-yyyy" aria-label="Início" />
    <input id="fpEnd" type="text" class="input js-datepicker" inputmode="numeric" placeholder="dd-mm-yyyy" aria-label="Fim" />
        <select id="fpCat" class="input" aria-label="Categoria">
          <option value="">Todas</option>
          <option value="fornecedores">Fornecedores</option>
          <option value="fixas">Fixas</option>
          <option value="impostos">Impostos</option>
        </select>
        <button id="fpApply" class="btn btn-secondary">Filtrar</button>
        <button id="fpToggle" class="btn btn-outline" type="button">Detalhes</button>
      </div>
    </div>
    <div role="status" aria-live="polite" class="muted" id="fpSummary">Carregando…</div>
    <div class="table-responsive" style="margin-top:0.5rem;" id="fpTableWrap">
      <table class="table" aria-describedby="payablesTitle">
        <thead>
          <tr><th>Vencimento</th><th>Descrição</th><th>Categoria</th><th>Status</th><th style="text-align:right;">Valor</th></tr>
        </thead>
        <tbody id="fpRows"><tr><td colspan="5" class="muted">Sem dados</td></tr></tbody>
      </table>
    </div>
  </section>

  <section class="card accent-revenue" id="financeReceivables" data-lazy="finance" aria-labelledby="receivablesTitle">
    <div style="display:flex;justify-content:space-between;align-items:center;gap:0.5rem;flex-wrap:wrap;">
      <h3 id="receivablesTitle" style="margin:0;" class="title-revenue">Contas a receber</h3>
      <div style="display:flex;gap:0.5rem;align-items:center;">
    <input id="frStart" type="text" class="input js-datepicker" inputmode="numeric" placeholder="dd-mm-yyyy" aria-label="Início" />
    <input id="frEnd" type="text" class="input js-datepicker" inputmode="numeric" placeholder="dd-mm-yyyy" aria-label="Fim" />
        <select id="frCat" class="input" aria-label="Categoria">
          <option value="">Todas</option>
          <option value="vendas">Vendas</option>
          <option value="assinaturas">Assinaturas</option>
          <option value="outros">Outros</option>
        </select>
        <button id="frApply" class="btn btn-secondary">Filtrar</button>
        <button id="frToggle" class="btn btn-outline" type="button">Detalhes</button>
      </div>
    </div>
    <div role="status" aria-live="polite" class="muted" id="frSummary">Carregando…</div>
    <div class="table-responsive" style="margin-top:0.5rem;" id="frTableWrap">
      <table class="table" aria-describedby="receivablesTitle">
        <thead>
          <tr><th>Recebimento</th><th>Cliente</th><th>Origem</th><th>Status</th><th style="text-align:right;">Valor</th></tr>
        </thead>
        <tbody id="frRows"><tr><td colspan="5" class="muted">Sem dados</td></tr></tbody>
      </table>
    </div>
  </section>
</div>

<!-- Tempo real e Alertas de Estoque -->
<div class="grid" id="sec-tempo-real" style="grid-template-columns: 2fr 1fr; gap: 0.75rem; align-items:start; margin-top:0.75rem;">
  <div class="card" id="rtPanel" data-lazy="realtime">
    <h3 style="margin-top:0;">Tempo real</h3>
    <div class="muted">Últimas vendas (PDV)</div>
    <ul id="rtList" style="margin-top:0.5rem; max-height:320px; overflow:auto;"></ul>
  </div>

  <section class="card" id="stockAlerts" data-lazy="stock" aria-labelledby="stockAlertsTitle">
    <h3 id="stockAlertsTitle" style="margin:0;">Alertas de estoque</h3>
    <ul id="stockList" style="margin-top:0.5rem;display:flex;flex-direction:column;gap:0.5rem;"></ul>
    <div class="muted" id="stockEmpty" style="display:none;">Nenhum item crítico.</div>
  </section>
</div>

<!-- Calendário e Gráfico Avançado -->
<div class="grid" id="sec-agenda" style="grid-template-columns: 1fr 1fr; gap: 0.75rem; align-items:stretch; margin-top:0.75rem;">
  <section class="card" id="calendar" data-lazy="calendar" aria-labelledby="calendarTitle" style="height:100%;display:flex;flex-direction:column;">
    <div style="display:flex;justify-content:space-between;align-items:center;gap:0.5rem;flex-wrap:wrap;">
      <h3 id="calendarTitle" style="margin:0;">Agenda</h3>
      <div role="tablist" aria-label="Modos de visualização" style="display:flex;gap:0.25rem;">
        <button class="btn btn-secondary" data-view="month" aria-selected="true">Mês</button>
        <button class="btn btn-secondary" data-view="week">Semana</button>
        <button class="btn btn-secondary" data-view="day">Dia</button>
      </div>
    </div>
    <div id="calendarGrid" style="margin-top:0.5rem;min-height:300px;" aria-live="polite"></div>
    <form id="calendarForm" style="display:flex;gap:0.5rem;align-items:end;margin-top:0.5rem;flex-wrap:wrap;">
      <div style="display:flex;flex-direction:column;gap:0.25rem;">
        <label for="calDate">Data</label>
    <input id="calDate" type="text" class="input js-datepicker" inputmode="numeric" placeholder="dd-mm-yyyy" required />
      </div>
      <div style="display:flex;flex-direction:column;gap:0.25rem;">
        <label for="calType">Tipo</label>
        <select id="calType" class="input">
          <option value="despesa">Despesa</option>
          <option value="receita">Receita</option>
        </select>
      </div>
      <div style="display:flex;flex-direction:column;gap:0.25rem;">
        <label for="calDesc">Descrição</label>
        <input id="calDesc" type="text" class="input" placeholder="Descrição" required />
      </div>
      <div style="display:flex;flex-direction:column;gap:0.25rem;">
        <label for="calValue">Valor</label>
        <input id="calValue" type="number" class="input" step="0.01" min="0" placeholder="0,00" required />
      </div>
      <button class="btn" type="submit">Adicionar</button>
    </form>
  </section>

  <section class="card" id="advancedChart" data-lazy="advchart" aria-labelledby="advChartTitle" style="height:100%;display:flex;flex-direction:column;">
    <div style="display:flex;justify-content:space-between;align-items:center;gap:0.5rem;flex-wrap:wrap;">
      <h3 id="advChartTitle" style="margin:0;">Vendas — Gráfico avançado</h3>
      <div style="display:flex;gap:0.5rem;align-items:center;flex-wrap:wrap;">
        <select id="gaType" class="input" aria-label="Tipo de gráfico">
          <option value="line">Linhas</option>
          <option value="bar">Barras</option>
          <option value="pie">Pizza</option>
        </select>
        <select id="gaPreset" class="input" aria-label="Comparativo">
          <option value="month">Mês atual vs anterior</option>
          <option value="quarter">Trimestre atual vs anterior</option>
          <option value="year">Ano atual vs anterior</option>
          <option value="custom">Personalizado</option>
        </select>
    <input id="gaStart" type="text" class="input js-datepicker" inputmode="numeric" placeholder="dd-mm-yyyy" aria-label="Início" />
    <input id="gaEnd" type="text" class="input js-datepicker" inputmode="numeric" placeholder="dd-mm-yyyy" aria-label="Fim" />
        <span class="muted" style="font-size:.9em;">Produto</span>
        <select id="gaProduct" class="input" aria-label="Produto"><option value="">Todos os produtos</option></select>
        <span class="muted" style="font-size:.9em;">Região</span>
        <select id="gaRegion" class="input" aria-label="Região"><option value="">Todas as regiões</option></select>
        <span class="muted" style="font-size:.9em;">Vendedor</span>
        <select id="gaSeller" class="input" aria-label="Vendedor"><option value="">Todos os vendedores</option></select>
        <button id="gaApply" class="btn btn-secondary">Aplicar</button>
      </div>
    </div>
    <div id="gaStatus" class="muted" style="margin-top:0.25rem;display:none;">&nbsp;</div>
    <canvas id="gaCanvas" width="900" height="360" style="width:100%;height:auto;margin-top:0.5rem;"></canvas>
  </section>
</div>

<!-- Predições e Insights -->
<div class="grid" id="sec-tendencias" style="grid-template-columns: 1fr 1fr; gap: 0.75rem; align-items:stretch; margin-top:0.75rem;">
  <section class="card" id="forecastPanel" data-lazy="forecast" aria-labelledby="forecastTitle">
    <div style="display:flex;justify-content:space-between;align-items:center;gap:0.5rem;flex-wrap:wrap;">
      <h3 id="forecastTitle" style="margin:0;">Predições (suavização exponencial)</h3>
      <div class="muted">Projeção 7 dias • Receitas</div>
    </div>
    <canvas id="forecastCanvas" width="900" height="240" style="width:100%;height:auto;margin-top:0.5rem;"></canvas>
  </section>
  <section class="card" id="insightsPanel" data-lazy="insights" aria-labelledby="insightsTitle">
    <h3 id="insightsTitle" style="margin:0;">Insights e Anomalias</h3>
    <ul id="insightsList" style="margin-top:0.5rem;"><li class="muted">Sem anomalias detectadas</li></ul>
  </section>
</div>

<script type="module">
  const state = {
    filters: { start: null, end: null, canal: '' },
    thresholds: { metaDiaria: 1000, alertaFaturamentoMin: 200 },
  };

  // Persistência de filtros globais
  (function initPersistedFilters(){
    // Converte qualquer valor persistido para dd-mm-yyyy para exibição
    const toBR = (s) => {
      if (!s) return '';
      try {
        if (typeof window !== 'undefined' && typeof window.fmtDateBR === 'function') {
          return window.fmtDateBR(s);
        }
        const d = new Date(s);
        if (!d || isNaN(d)) return String(s);
        const pad = (n) => String(n).padStart(2,'0');
        return `${pad(d.getDate())}-${pad(d.getMonth()+1)}-${d.getFullYear()}`;
      } catch (_) { return String(s||''); }
    };
    try {
      const s = localStorage.getItem('dashboard_filters_start');
      const e = localStorage.getItem('dashboard_filters_end');
      const c = localStorage.getItem('dashboard_filters_canal');
      const sBR = s ? toBR(s) : null;
      const eBR = e ? toBR(e) : null;
      if (sBR) { byId('fStart').value = sBR; state.filters.start = sBR; }
      if (eBR) { byId('fEnd').value = eBR; state.filters.end = eBR; }
      if (typeof c === 'string') { byId('fCanal').value = c; state.filters.canal = c; }
    } catch(_){}
  })();

  function byId(id){ return document.getElementById(id); }
  function fmtBRL(v){ try { return new Intl.NumberFormat('pt-BR',{style:'currency',currency:'BRL'}).format(v||0); } catch(e){ return 'R$ ' + Number(v||0).toFixed(2).replace('.', ','); } }

  // Lazy load dos módulos por interseção
  const modulesLoaded = { kpis: false, charts: false, realtime: false, finance: false, 'finance-kpis': false, sellers: false, stock: false, calendar: false, advchart: false, forecast: false, insights: false };
  const io = new IntersectionObserver((entries) => {
    entries.forEach(async entry => {
      if (!entry.isIntersecting) return;
      const kind = entry.target.getAttribute('data-lazy');
      if (!kind || modulesLoaded[kind]) return;
      modulesLoaded[kind] = true;
      if (kind === 'kpis') {
        const mod = await import('/js/dashboard/kpis.js');
        mod.initKpis(state, { fmtBRL });
      } else if (kind === 'charts') {
        const mod = await import('/js/dashboard/charts.js');
        mod.initPredChart(state, { fmtBRL });
      } else if (kind === 'realtime') {
        const mod = await import('/js/dashboard/realtime.js');
        mod.initRealtime(state, { fmtBRL });
      } else if (kind === 'finance') {
        const mod = await import('/js/dashboard/finance.js');
        mod.initFinance(state, { fmtBRL });
      } else if (kind === 'finance-kpis') {
        const mod = await import('/js/dashboard/finance-kpis.js');
        mod.initFinanceKpis(state, { fmtBRL });
      } else if (kind === 'sellers') {
        const mod = await import('/js/dashboard/sellers.js');
        mod.initSellers(state, { fmtBRL });
      } else if (kind === 'stock') {
        const mod = await import('/js/dashboard/stock.js');
        mod.initStockAlerts(state, { fmtBRL });
      } else if (kind === 'calendar') {
        const mod = await import('/js/dashboard/calendar.js');
        mod.initCalendar(state, { fmtBRL });
      } else if (kind === 'advchart') {
        const mod = await import('/js/dashboard/advanced-chart.js');
        mod.initAdvancedChart(state, { fmtBRL });
      } else if (kind === 'fiscal') {
        const mod = await import('/js/dashboard/fiscal.js');
        mod.initFiscal(state, { fmtBRL });
      } else if (kind === 'forecast') {
        const mod = await import('/js/dashboard/forecast.js');
        mod.initForecast(state, { fmtBRL });
      } else if (kind === 'insights') {
        const mod = await import('/js/dashboard/insights.js');
        mod.initInsights(state, { fmtBRL });
      }
    });
  }, { rootMargin: '0px 0px 120px 0px' });

  document.querySelectorAll('[data-lazy]').forEach(el => io.observe(el));

  // Alertas (lazy interno quando KPIs carregarem)
  async function refreshAlerts(snapshot){
    const { initAlerts } = await import('/js/dashboard/alerts.js');
    const alerts = initAlerts(snapshot, state.thresholds);
    const bar = byId('alertsBar');
    const list = byId('alertsList');
    if (alerts.length === 0){ bar.style.display='none'; list.innerHTML=''; return; }
    bar.style.display='block';
    list.innerHTML = alerts.map(a => `<li>${a}</li>`).join('');
  }

  // Filtros
  function applyFilters(){
    const s = byId('fStart').value || null;
    const e = byId('fEnd').value || null;
    const c = byId('fCanal').value || '';
    state.filters = { start: s, end: e, canal: c };
    try {
      if (s) localStorage.setItem('dashboard_filters_start', s); else localStorage.removeItem('dashboard_filters_start');
      if (e) localStorage.setItem('dashboard_filters_end', e); else localStorage.removeItem('dashboard_filters_end');
      localStorage.setItem('dashboard_filters_canal', c || '');
    } catch(_){}
    // reexecutar módulos ativos
    document.querySelectorAll('[data-lazy]').forEach(el => {
      const kind = el.getAttribute('data-lazy');
      if (kind === 'kpis' && modulesLoaded.kpis) import('/js/dashboard/kpis.js').then(m => m.initKpis(state,{fmtBRL}));
      if (kind === 'charts' && modulesLoaded.charts) import('/js/dashboard/charts.js').then(m => m.initPredChart(state,{fmtBRL}));
      if (kind === 'realtime' && modulesLoaded.realtime) import('/js/dashboard/realtime.js').then(m => m.initRealtime(state,{fmtBRL}));
      if (kind === 'finance' && modulesLoaded.finance) import('/js/dashboard/finance.js').then(m => m.initFinance(state,{fmtBRL}));
      if (kind === 'finance-kpis' && modulesLoaded['finance-kpis']) import('/js/dashboard/finance-kpis.js').then(m => m.initFinanceKpis(state,{fmtBRL}));
      if (kind === 'sellers' && modulesLoaded.sellers) import('/js/dashboard/sellers.js').then(m => m.initSellers(state,{fmtBRL}));
      if (kind === 'stock' && modulesLoaded.stock) import('/js/dashboard/stock.js').then(m => m.initStockAlerts(state,{fmtBRL}));
      if (kind === 'calendar' && modulesLoaded.calendar) import('/js/dashboard/calendar.js').then(m => m.initCalendar(state,{fmtBRL}));
      if (kind === 'advchart' && modulesLoaded.advchart) import('/js/dashboard/advanced-chart.js').then(m => m.initAdvancedChart(state,{fmtBRL}));
      if (kind === 'fiscal' && modulesLoaded.fiscal) import('/js/dashboard/fiscal.js').then(m => m.initFiscal(state,{fmtBRL}));
      if (kind === 'forecast' && modulesLoaded.forecast) import('/js/dashboard/forecast.js').then(m => m.initForecast(state,{fmtBRL}));
      if (kind === 'insights' && modulesLoaded.insights) import('/js/dashboard/insights.js').then(m => m.initInsights(state,{fmtBRL}));
    });
  }
  byId('btnApplyFilters').addEventListener('click', applyFilters);

  // Aplicar automaticamente filtros persistidos na carga inicial
  applyFilters();

  // Toggle de detalhes nas tabelas financeiras
  document.addEventListener('click', (e)=>{
    if (e.target && e.target.id === 'fpToggle') {
      const w = byId('fpTableWrap'); if (!w) return; const vis = w.style.display !== 'none'; w.style.display = vis ? 'none' : 'block';
    }
    if (e.target && e.target.id === 'frToggle') {
      const w = byId('frTableWrap'); if (!w) return; const vis = w.style.display !== 'none'; w.style.display = vis ? 'none' : 'block';
    }
  });

  // Expor hook para módulos emitirem snapshot e disparar alertas
  window.__dashboardReportSnapshot = refreshAlerts;
</script>