// Additional screens: DRE, Cashflow, Integrations tab, Notifications drawer, MobileShell

const { useState: useStateE, useMemo: useMemoE, useEffect: useEffectE } = React;

// ─────────────────────────────────────────────────────────────────────────────
// DRE (Demonstrativo de Resultado do Exercício)
// ─────────────────────────────────────────────────────────────────────────────
function DREScreen() {
  const [period, setPeriod] = useStateE("ytd");
  const M = window.MOCK;

  // Multiplicadores e labels por período
  const periodMeta = {
    month:   { label: `Mês atual (${M.NOW.monthShort}/${M.NOW.year})`, mult: 0.11 },
    quarter: { label: `Trimestre (Q${M.NOW.quarter}/${M.NOW.year})`,    mult: 0.33 },
    ytd:     { label: `YTD ${M.NOW.year}`,                              mult: 1.00 },
    year:    { label: `Ano completo projetado ${M.NOW.year}`,           mult: 1.34 },
  };
  const cur = periodMeta[period];
  const mult = cur.mult;
  const adj = (v) => Math.round(v * mult);

  // Placeholder DRE structure — valores escalam com período
  const dre = {
    "Receita Bruta de Vendas":            { value: adj(20_860_000), isHeader: true, growth: 0.241 },
    "  Vendas de Mercadorias":            { value: adj(19_420_000) },
    "  Outras Receitas Operacionais":     { value: adj( 1_440_000) },
    "(-) Deduções e Impostos sobre Vendas": { value: adj(-3_756_000), negative: true },
    "  ICMS, PIS, COFINS":                { value: adj(-3_240_000) },
    "  Devoluções e Abatimentos":         { value: adj(  -516_000) },
    "= Receita Líquida":                  { value: adj(17_104_000), isSubtotal: true, growth: 0.226 },
    "(-) Custo das Mercadorias Vendidas (CMV)": { value: adj(-10_604_000), negative: true },
    "= Lucro Bruto":                      { value: adj( 6_500_000), isSubtotal: true, growth: 0.318, margin: 0.38 },
    "(-) Despesas Operacionais":          { value: adj(-3_980_000), isHeader: true, negative: true },
    "  Despesas com Pessoal":             { value: adj(-1_820_000) },
    "  Despesas Administrativas":         { value: adj(  -740_000) },
    "  Despesas Comerciais":              { value: adj(  -980_000) },
    "  Logística e Frete":                { value: adj(  -440_000) },
    "= EBITDA":                           { value: adj( 2_520_000), isSubtotal: true, growth: 0.412, margin: 0.147 },
    "(-) Depreciação e Amortização":      { value: adj(  -180_000), negative: true },
    "= EBIT (Lucro Operacional)":         { value: adj( 2_340_000), isSubtotal: true, growth: 0.398 },
    "(+/-) Resultado Financeiro":         { value: adj(  -240_000), negative: true },
    "(-) Impostos sobre o Lucro":         { value: adj(  -420_000), negative: true },
    "= Lucro Líquido":                    { value: adj( 1_680_000), isFinal: true, growth: 0.348, margin: 0.098 },
  };

  return (
    <div className="page">
      <div className="page-head">
        <div>
          <div className="muted">Resultado consolidado · {cur.label}</div>
          <h2 style={{ margin: 0, fontWeight: 600 }}>DRE · Demonstrativo de Resultado</h2>
        </div>
        <div className="page-head-actions">
          <div className="seg-control">
            <button className={`seg-btn ${period==="month"?"active":""}`} onClick={()=>setPeriod("month")}>Mês</button>
            <button className={`seg-btn ${period==="quarter"?"active":""}`} onClick={()=>setPeriod("quarter")}>Trim.</button>
            <button className={`seg-btn ${period==="ytd"?"active":""}`} onClick={()=>setPeriod("ytd")}>YTD</button>
            <button className={`seg-btn ${period==="year"?"active":""}`} onClick={()=>setPeriod("year")}>Ano</button>
          </div>
          <button className="btn btn-outline" onClick={() => window.openPrintPreview()}><Icon name="printer" size={14}/> Imprimir PDF</button>
        </div>
      </div>

      <div className="kpi-grid kpi-4">
        <KPI label={`Receita Bruta · ${cur.label}`} value={fmtBRLshort(adj(20_860_000))} delta={0.241} />
        <KPI label="Lucro Bruto" value={fmtBRLshort(adj(6_500_000))} delta={0.318} sub="Margem 38,0%" />
        <KPI label="EBITDA" value={fmtBRLshort(adj(2_520_000))} delta={0.412} sub="Margem 14,7%" accent="var(--cefeq-blue)" />
        <KPI label="Lucro Líquido" value={fmtBRLshort(adj(1_680_000))} delta={0.348} sub="Margem 9,8%" accent="var(--success)" />
      </div>

      <div className="grid-2-1">
        <div className="card">
          <div className="card-head">
            <h3>Demonstrativo detalhado</h3>
            <div className="muted">{cur.label} · em R$</div>
          </div>
          <div className="dre-table">
            {Object.entries(dre).map(([label, row]) => (
              <div key={label} className={`dre-row ${row.isHeader?"dre-header":""} ${row.isSubtotal?"dre-subtotal":""} ${row.isFinal?"dre-final":""}`}>
                <div className="dre-label">{label}</div>
                <div className={`dre-value mono ${row.negative?"down":""}`}>{fmtBRL(row.value)}</div>
                {row.margin != null && (
                  <div className="dre-margin">{(row.margin * 100).toFixed(1).replace(".",",")}%</div>
                )}
                {row.growth != null && (
                  <div className={`dre-growth ${row.growth>=0?"up":"down"}`}>{fmtPct(row.growth)}</div>
                )}
              </div>
            ))}
          </div>
        </div>

        <div className="card">
          <div className="card-head">
            <h3>Composição do resultado</h3>
          </div>
          <Waterfall />
        </div>
      </div>
    </div>
  );
}

function Waterfall() {
  // Simplified waterfall: receita → cmv → despesas → impostos → lucro
  const steps = [
    { label: "Receita Bruta", value: 20.86, color: "var(--cefeq-blue)", type: "start" },
    { label: "Deduções",      value: -3.76, color: "var(--danger)" },
    { label: "CMV",           value: -10.60, color: "var(--danger)" },
    { label: "Despesas Op.",  value: -3.98, color: "var(--warn)" },
    { label: "Dep. + Fin. + IR", value: -0.84, color: "var(--warn)" },
    { label: "Lucro Líquido", value: 1.68, color: "var(--success)", type: "end" },
  ];
  let cum = 0;
  const data = steps.map(s => {
    if (s.type === "start") { cum = s.value; return { ...s, start: 0, end: s.value, h: s.value }; }
    if (s.type === "end")   { return { ...s, start: 0, end: s.value, h: s.value }; }
    const start = cum, end = cum + s.value;
    cum = end;
    return { ...s, start: Math.min(start, end), end: Math.max(start, end), h: Math.abs(s.value) };
  });
  const max = Math.max(...data.map(d => Math.max(d.end, d.start)));

  return (
    <div className="waterfall">
      {data.map((d, i) => (
        <div key={i} className="wf-col">
          <div className="wf-stack">
            <div className="wf-bar" style={{
              height: `${(d.h / max) * 100}%`,
              marginTop: `${((max - d.end) / max) * 100}%`,
              background: d.color,
            }}>
              <span className="wf-val">R$ {d.value.toFixed(1).replace(".",",")}M</span>
            </div>
          </div>
          <div className="wf-lbl">{d.label}</div>
        </div>
      ))}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// CASHFLOW
// ─────────────────────────────────────────────────────────────────────────────
function CashflowScreen() {
  const [period, setPeriod] = useStateE("month");
  const [view, setView] = useStateE("chart");
  const [calMonth, setCalMonth] = useStateE(new Date(2026, 8, 1)); // Set: Sep 2026
  const [dayDetail, setDayDetail] = useStateE(null);

  const months = ["Jan", "Fev", "Mar", "Abr", "Mai", "Jun", "Jul", "Ago", "Set"];
  // simplified: inflow, outflow, balance
  const data = [
    { m: "Jan", inflow: 1_680, outflow: 1_510, balance: 170 },
    { m: "Fev", inflow: 1_590, outflow: 1_470, balance: 290 },
    { m: "Mar", inflow: 1_840, outflow: 1_620, balance: 510 },
    { m: "Abr", inflow: 1_910, outflow: 1_680, balance: 740 },
    { m: "Mai", inflow: 1_960, outflow: 1_720, balance: 980 },
    { m: "Jun", inflow: 2_080, outflow: 1_850, balance: 1_210 },
    { m: "Jul", inflow: 2_140, outflow: 1_810, balance: 1_540 },
    { m: "Ago", inflow: 2_190, outflow: 1_980, balance: 1_750 },
    { m: "Set", inflow: 2_240, outflow: 2_010, balance: 1_980 },
  ];

  const totalIn = data.reduce((s, d) => s + d.inflow, 0) * 1000;
  const totalOut = data.reduce((s, d) => s + d.outflow, 0) * 1000;
  const totalBal = totalIn - totalOut;

  const accounts = [
    { name: "Banco Bradesco · CC 12345", balance: 842_000, type: "Conta corrente" },
    { name: "Banco Itaú · CC 67890",     balance: 524_000, type: "Conta corrente" },
    { name: "Aplicação CDB · Caixa",     balance: 380_000, type: "Investimento" },
    { name: "Cofre / Caixa físico",       balance:  18_000, type: "Caixa" },
  ];

  const upcoming = [
    { date: "26/05", desc: "Fornecedor · Bosch BR",        value: -184_000, type: "Pagamento" },
    { date: "27/05", desc: "Cliente · Construtora Aurora", value:  +62_400, type: "Recebimento" },
    { date: "28/05", desc: "Folha de pagamento",            value: -212_000, type: "Pagamento" },
    { date: "30/05", desc: "Impostos · DARF + GPS",         value:  -98_500, type: "Impostos" },
    { date: "31/05", desc: "Aluguel · Sede + 2 lojas",      value:  -42_000, type: "Pagamento" },
    { date: "02/06", desc: "Cliente · Reformas Boa Vista",  value:  +28_900, type: "Recebimento" },
  ];

  return (
    <div className="page">
      <div className="page-head">
        <div>
          <div className="muted">Tesouraria · YTD 2026</div>
          <h2 style={{ margin: 0, fontWeight: 600 }}>Fluxo de Caixa</h2>
        </div>
        <div className="page-head-actions">
          <div className="seg-control">
            <button className={`seg-btn ${view==="chart"?"active":""}`} onClick={()=>setView("chart")}>
              <Icon name="overview" size={13} style={{marginRight:4}}/> Visão geral
            </button>
            <button className={`seg-btn ${view==="calendar"?"active":""}`} onClick={()=>setView("calendar")}>
              <Icon name="recurring" size={13} style={{marginRight:4}}/> Calendário
            </button>
          </div>
          <button className="btn btn-outline" onClick={() => window.openPrintPreview()}><Icon name="printer" size={14}/> Imprimir PDF</button>
        </div>
      </div>

      <div className="kpi-grid kpi-4">
        <KPI label="Saldo atual consolidado" value={fmtBRLshort(accounts.reduce((s,a)=>s+a.balance,0))} delta={0.14} sub="4 contas" accent="var(--cefeq-blue)" />
        <KPI label="Entradas YTD" value={fmtBRLshort(totalIn)} delta={0.241} accent="var(--success)" />
        <KPI label="Saídas YTD" value={fmtBRLshort(totalOut)} delta={0.198} accent="var(--danger)" />
        <KPI label="Resultado de caixa" value={fmtBRLshort(totalBal)} delta={0.36} sub="Geração positiva" />
      </div>

      {view === "calendar" ? (
        <CashflowCalendar
          month={calMonth}
          onPrevMonth={() => setCalMonth(new Date(calMonth.getFullYear(), calMonth.getMonth() - 1, 1))}
          onNextMonth={() => setCalMonth(new Date(calMonth.getFullYear(), calMonth.getMonth() + 1, 1))}
          onSelectDay={setDayDetail}
        />
      ) : (
        <>
          <div className="card">
            <div className="card-head">
              <div>
                <h3>Entradas vs Saídas · {months.length} meses</h3>
                <div className="muted">Em R$ · valores em milhares</div>
              </div>
              <div className="legend">
                <span className="lg-dot" style={{ background: "var(--success)" }}/> Entradas
                <span className="lg-dot" style={{ background: "var(--danger)" }}/> Saídas
                <span className="lg-dot" style={{ background: "var(--cefeq-blue)" }}/> Saldo acumulado
              </div>
            </div>
            <CashflowChart data={data} />
          </div>

          <div className="grid-2-1">
            <div className="card">
              <div className="card-head">
                <h3>Próximas movimentações</h3>
                <div className="muted">Próximos 7 dias</div>
              </div>
              <div className="table">
                <div className="table-head">
                  <div style={{ width: 70 }}>Data</div>
                  <div style={{ flex: 2 }}>Descrição</div>
                  <div style={{ flex: 1 }}>Tipo</div>
                  <div style={{ flex: 1, textAlign: "right" }}>Valor</div>
                </div>
                {upcoming.map((u, i) => (
                  <div key={i} className="table-row">
                    <div style={{ width: 70 }} className="mono">{u.date}</div>
                    <div style={{ flex: 2, fontWeight: 600 }}>{u.desc}</div>
                    <div style={{ flex: 1 }}>
                      <Pill variant={u.value > 0 ? "success" : u.type === "Impostos" ? "warn" : "neutral"}>{u.type}</Pill>
                    </div>
                    <div style={{ flex: 1, textAlign: "right", fontFamily: "var(--font-mono)", fontWeight: 600 }} className={u.value >= 0 ? "up" : "down"}>
                      {fmtBRL(u.value)}
                    </div>
                  </div>
                ))}
              </div>
            </div>

            <div className="card">
              <div className="card-head">
                <h3>Contas e saldos</h3>
              </div>
              <div className="acc-list">
                {accounts.map((a, i) => (
                  <div key={i} className="acc-row">
                    <div>
                      <div className="acc-name">{a.name}</div>
                      <div className="muted" style={{ fontSize: 11 }}>{a.type}</div>
                    </div>
                    <div className="acc-bal mono">{fmtBRL(a.balance)}</div>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </>
      )}

      <DayDetailModal day={dayDetail} onClose={() => setDayDetail(null)}/>
    </div>
  );
}

function CashflowChart({ data }) {
  const w = 760, h = 320, padX = 40, padY = 40;
  const max = Math.max(...data.map(d => Math.max(d.inflow, d.outflow))) * 1000;
  const colW = (w - 2 * padX) / data.length;
  const fmtK = (n) => n >= 1000 ? `${Math.round(n/1000)}K` : `${n.toFixed(0)}`;

  return (
    <svg viewBox={`0 0 ${w} ${h}`} className="cashflow-chart">
      {/* baseline */}
      <line x1={padX} y1={h-padY} x2={w-padX} y2={h-padY} stroke="var(--border-strong)"/>
      {/* gridlines */}
      {[0.25, 0.5, 0.75, 1].map((p, i) => (
        <line key={i} x1={padX} y1={h-padY - p*(h-2*padY)} x2={w-padX} y2={h-padY - p*(h-2*padY)} stroke="var(--grid-line)"/>
      ))}
      {data.map((d, i) => {
        const x = padX + colW * i + colW/2;
        const barW = colW * 0.32;
        const inH = (d.inflow * 1000 / max) * (h - 2*padY);
        const outH = (d.outflow * 1000 / max) * (h - 2*padY);
        const inY = h - padY - inH;
        const outY = h - padY - outH;
        return (
          <g key={i}>
            <rect x={x - barW - 2} y={inY} width={barW} height={inH} fill="var(--success)" opacity="0.85" rx="3"/>
            <rect x={x + 2} y={outY} width={barW} height={outH} fill="var(--danger)" opacity="0.85" rx="3"/>
            {/* Rótulos de valor nas barras */}
            <text x={x - barW/2 - 2} y={inY - 4} textAnchor="middle" fill="var(--success)" fontSize="10" fontWeight="700">
              {fmtK(d.inflow)}
            </text>
            <text x={x + barW/2 + 2} y={outY - 4} textAnchor="middle" fill="var(--danger)" fontSize="10" fontWeight="700">
              {fmtK(d.outflow)}
            </text>
            {/* Nome do mês */}
            <text x={x} y={h - padY + 16} textAnchor="middle" fill="var(--text)" fontSize="11" fontWeight="600">{d.m}</text>
          </g>
        );
      })}
      {/* balance line + rótulos no ponto */}
      <path d={data.map((d, i) => {
        const x = padX + colW * i + colW/2;
        const y = h - padY - (d.balance * 1000 / max) * (h - 2*padY);
        return (i === 0 ? `M${x},${y}` : `L${x},${y}`);
      }).join(" ")} fill="none" stroke="var(--cefeq-blue)" strokeWidth="2.5"/>
      {data.map((d, i) => {
        const x = padX + colW * i + colW/2;
        const y = h - padY - (d.balance * 1000 / max) * (h - 2*padY);
        const showLabel = i === 0 || i === data.length - 1 || i === Math.floor(data.length / 2);
        return (
          <g key={i}>
            <circle cx={x} cy={y} r="4" fill="var(--cefeq-blue)" stroke="white" strokeWidth="1.5"/>
            {showLabel && (
              <g>
                <rect x={x - 22} y={y - 22} width="44" height="16" rx="3" fill="var(--cefeq-blue)"/>
                <text x={x} y={y - 11} textAnchor="middle" fill="white" fontSize="10" fontWeight="700">
                  {fmtK(d.balance)}
                </text>
              </g>
            )}
          </g>
        );
      })}
    </svg>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// CASHFLOW CALENDAR
// ─────────────────────────────────────────────────────────────────────────────
function genDayData(year, month, day) {
  // deterministic pseudo-random per day
  const seed = year * 10000 + (month + 1) * 100 + day;
  const r = (n) => {
    let t = (seed + n * 13) + 0x6D2B79F5;
    t = Math.imul(t ^ (t >>> 15), t | 1);
    t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
  // Weekends slower
  const date = new Date(year, month, day);
  const isWeekend = date.getDay() === 0 || date.getDay() === 6;
  const baseIn = isWeekend ? 8_000 : 60_000;
  const baseOut = isWeekend ? 4_000 : 48_000;
  const inflow = Math.round(baseIn + r(1) * (isWeekend ? 12_000 : 80_000));
  const outflow = Math.round(baseOut + r(2) * (isWeekend ? 8_000 : 70_000));
  const net = inflow - outflow;

  // sample transactions (3-7 per day)
  const txCount = 3 + Math.floor(r(3) * 5);
  const txTypes = [
    { desc: "Cliente · Construções",      type: "Recebimento", sign: +1 },
    { desc: "E-commerce · Pix",            type: "Recebimento", sign: +1 },
    { desc: "Cliente · Marcenaria",        type: "Recebimento", sign: +1 },
    { desc: "Fornecedor · Bosch",          type: "Pagamento",   sign: -1 },
    { desc: "Fornecedor · Tramontina",     type: "Pagamento",   sign: -1 },
    { desc: "Energia / Aluguel",           type: "Operacional", sign: -1 },
    { desc: "Folha de pagamento",          type: "Folha",       sign: -1 },
    { desc: "Impostos · DARF",             type: "Impostos",    sign: -1 },
    { desc: "Frete · Transportadora",      type: "Operacional", sign: -1 },
    { desc: "Comissões · Vendedores",      type: "Folha",       sign: -1 },
    { desc: "Estorno · Devolução",         type: "Devolução",   sign: -1 },
  ];
  const txs = [];
  for (let i = 0; i < txCount; i++) {
    const tx = txTypes[Math.floor(r(10 + i) * txTypes.length)];
    const amount = Math.round((tx.sign > 0 ? inflow / txCount : outflow / txCount) * (0.6 + r(20 + i) * 0.8));
    txs.push({ ...tx, value: tx.sign * amount });
  }
  return { inflow, outflow, net, txs };
}

function CashflowCalendar({ month, onPrevMonth, onNextMonth, onSelectDay }) {
  const year = month.getFullYear();
  const m = month.getMonth();
  const monthName = month.toLocaleDateString("pt-BR", { month: "long", year: "numeric" });
  const firstDay = new Date(year, m, 1);
  const daysInMonth = new Date(year, m + 1, 0).getDate();
  const startWeekday = firstDay.getDay(); // 0 = Sunday

  // Build cells (with padding for first week)
  const cells = [];
  for (let i = 0; i < startWeekday; i++) cells.push(null);
  for (let d = 1; d <= daysInMonth; d++) cells.push(d);
  // pad to multiple of 7
  while (cells.length % 7 !== 0) cells.push(null);

  // Aggregates for the visible month
  let totalIn = 0, totalOut = 0;
  for (let d = 1; d <= daysInMonth; d++) {
    const dd = genDayData(year, m, d);
    totalIn += dd.inflow; totalOut += dd.outflow;
  }

  // Find max abs net to scale visual intensity
  const allNets = [];
  for (let d = 1; d <= daysInMonth; d++) allNets.push(Math.abs(genDayData(year, m, d).net));
  const maxAbs = Math.max(...allNets, 1);

  return (
    <div className="card">
      <div className="card-head cal-head">
        <div className="cal-nav">
          <button className="icon-btn cal-nav-btn" onClick={onPrevMonth}>
            <Icon name="chevron" size={14} style={{ transform: "rotate(180deg)" }}/>
          </button>
          <div className="cal-title">
            <h3 style={{ margin: 0, textTransform: "capitalize" }}>{monthName}</h3>
            <div className="muted" style={{ fontSize: 12 }}>Clique em qualquer dia para ver as movimentações</div>
          </div>
          <button className="icon-btn cal-nav-btn" onClick={onNextMonth}>
            <Icon name="chevron" size={14}/>
          </button>
        </div>
        <div className="cal-summary">
          <div>
            <div className="muted" style={{ fontSize: 10 }}>ENTRADAS</div>
            <div className="up mono" style={{ fontWeight: 700, fontSize: 14 }}>{fmtBRLshort(totalIn)}</div>
          </div>
          <div>
            <div className="muted" style={{ fontSize: 10 }}>SAÍDAS</div>
            <div className="down mono" style={{ fontWeight: 700, fontSize: 14 }}>{fmtBRLshort(totalOut)}</div>
          </div>
          <div>
            <div className="muted" style={{ fontSize: 10 }}>RESULTADO</div>
            <div className={`mono ${totalIn-totalOut>=0?"up":"down"}`} style={{ fontWeight: 700, fontSize: 14 }}>{fmtBRLshort(totalIn-totalOut)}</div>
          </div>
        </div>
      </div>

      <div className="calendar-grid">
        {["Dom","Seg","Ter","Qua","Qui","Sex","Sáb"].map(w => (
          <div key={w} className="cal-weekday">{w}</div>
        ))}
        {cells.map((d, i) => {
          if (d === null) return <div key={i} className="cal-day cal-empty"/>;
          const data = genDayData(year, m, d);
          const today = new Date();
          const isToday = year === today.getFullYear() && m === today.getMonth() && d === today.getDate();
          const intensity = Math.min(1, Math.abs(data.net) / maxAbs);
          const positive = data.net >= 0;
          const bg = positive
            ? `rgba(15, 127, 80, ${0.04 + intensity * 0.20})`
            : `rgba(194, 40, 43, ${0.04 + intensity * 0.18})`;
          return (
            <button key={i} className={`cal-day ${isToday ? "today" : ""}`} style={{ background: bg }}
              onClick={() => onSelectDay({ year, month: m, day: d, ...data })}>
              <div className="cal-day-num">{d}</div>
              <div className="cal-day-net mono" style={{ color: positive ? "var(--success)" : "var(--danger)" }}>
                {positive ? "+" : ""}{fmtBRLshort(data.net)}
              </div>
              <div className="cal-day-bars">
                <div className="cal-bar cal-in" style={{ width: `${Math.min(100, (data.inflow / maxAbs) * 50)}%` }}/>
                <div className="cal-bar cal-out" style={{ width: `${Math.min(100, (data.outflow / maxAbs) * 50)}%` }}/>
              </div>
            </button>
          );
        })}
      </div>

      <div className="cal-legend">
        <div><span className="cal-bar cal-in" style={{ width: 20, display: "inline-block" }}/> Entradas</div>
        <div><span className="cal-bar cal-out" style={{ width: 20, display: "inline-block" }}/> Saídas</div>
        <div className="muted">Intensidade da cor = magnitude do saldo do dia</div>
      </div>
    </div>
  );
}

function DayDetailModal({ day, onClose }) {
  if (!day) return null;
  const date = new Date(day.year, day.month, day.day);
  const dayName = date.toLocaleDateString("pt-BR", { weekday: "long", day: "numeric", month: "long", year: "numeric" });
  const positive = day.net >= 0;

  return (
    <Modal open={true} onClose={onClose} wide
      title={dayName.charAt(0).toUpperCase() + dayName.slice(1)}
      subtitle="Movimentações financeiras do dia"
      footer={<button className="btn btn-primary" onClick={onClose}>Fechar</button>}>
      <div className="modal-kpi-row" style={{ gridTemplateColumns: "repeat(3, 1fr)" }}>
        <div className="mk">
          <div className="muted">Entradas</div>
          <div className="mk-v up">{fmtBRL(day.inflow)}</div>
        </div>
        <div className="mk">
          <div className="muted">Saídas</div>
          <div className="mk-v down">{fmtBRL(day.outflow)}</div>
        </div>
        <div className="mk">
          <div className="muted">Saldo do dia</div>
          <div className={`mk-v ${positive?"up":"down"}`}>{positive?"+":""}{fmtBRL(day.net)}</div>
        </div>
      </div>

      <div className="modal-section">
        <h4>Transações ({day.txs.length})</h4>
        <div className="table" style={{ marginTop: 6 }}>
          <div className="table-head">
            <div style={{ flex: 2 }}>Descrição</div>
            <div style={{ flex: 1 }}>Tipo</div>
            <div style={{ flex: 1, textAlign: "right" }}>Valor</div>
          </div>
          {day.txs.map((tx, i) => (
            <div key={i} className="table-row">
              <div style={{ flex: 2, fontWeight: 600 }}>{tx.desc}</div>
              <div style={{ flex: 1 }}>
                <Pill variant={tx.value > 0 ? "success" : tx.type === "Impostos" ? "warn" : "neutral"}>{tx.type}</Pill>
              </div>
              <div style={{ flex: 1, textAlign: "right", fontFamily: "var(--font-mono)", fontWeight: 600 }} className={tx.value >= 0 ? "up" : "down"}>
                {tx.value > 0 ? "+" : ""}{fmtBRL(tx.value)}
              </div>
            </div>
          ))}
        </div>
      </div>
    </Modal>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// INTEGRATIONS (Sollus NRT) — used inside AdminScreen as a tab
// ─────────────────────────────────────────────────────────────────────────────
function IntegrationsTab() {
  const [syncing, setSyncing] = useStateE(false);
  const [lastSync, setLastSync] = useStateE("agora há 2 min");
  const [toastNode, showToast] = useToast();

  function manualSync() {
    setSyncing(true);
    setTimeout(() => {
      setSyncing(false);
      setLastSync("agora há poucos segundos");
      showToast("Sincronização concluída · 4.182 registros atualizados");
    }, 1600);
  }

  const pipelines = [
    { name: "Vendas (NF-e)",       status: "ok", records: "2.847", latency: "1.2 min", lastEvent: "há 38s" },
    { name: "Clientes (CRM)",      status: "ok", records: "12.493", latency: "2.4 min", lastEvent: "há 1min" },
    { name: "Produtos / SKUs",     status: "ok", records: "8.612",  latency: "5.0 min", lastEvent: "há 4min" },
    { name: "Estoque",             status: "warn", records: "8.612", latency: "12 min", lastEvent: "há 11min", note: "Latência acima do esperado" },
    { name: "Compras / Pedidos",   status: "ok", records: "1.428",  latency: "3.1 min", lastEvent: "há 2min" },
    { name: "Vendedores",          status: "ok", records: "12",     latency: "60 min", lastEvent: "há 14min" },
    { name: "E-commerce (orders)", status: "ok", records: "924",    latency: "0.8 min", lastEvent: "há 21s" },
    { name: "Financeiro (DRE)",    status: "ok", records: "486",    latency: "daily",   lastEvent: "hoje 03:00" },
  ];

  const events = [
    { time: "14:38:12", type: "info",  msg: "Novo pedido sincronizado · NF #28471" },
    { time: "14:37:55", type: "info",  msg: "Atualização de estoque · 24 SKUs" },
    { time: "14:37:21", type: "info",  msg: "Cliente atualizado · Construções Aurora" },
    { time: "14:35:08", type: "warn",  msg: "Pipeline 'Estoque' com latência elevada (12 min)" },
    { time: "14:34:42", type: "info",  msg: "Sync completo · 312 NF-e processadas" },
    { time: "14:30:00", type: "info",  msg: "Agendamento NRT executado · 4.182 registros" },
    { time: "14:22:14", type: "info",  msg: "Conexão Sollus validada" },
  ];

  return (
    <>
      <div className="integ-hero card">
        <div className="integ-status">
          <div className="integ-glow"/>
          <div className="integ-icon"><Icon name="check" size={24}/></div>
        </div>
        <div className="integ-meta">
          <div className="integ-title">Sollus ERP · Conectado</div>
          <div className="integ-sub">Integração NRT (Near Real-Time) ativa · Última sincronização {lastSync}</div>
          <div className="integ-tags">
            <Pill variant="success" icon="check">Online</Pill>
            <Pill variant="blue">v4.2.1</Pill>
            <Pill variant="neutral">Polling 60s</Pill>
            <Pill variant="neutral">8 pipelines</Pill>
          </div>
        </div>
        <div className="integ-actions">
          <button className="btn btn-ghost"><Icon name="settings" size={14}/> Configurar</button>
          <button className="btn btn-primary" onClick={manualSync} disabled={syncing}>
            {syncing ? <><span className="spin"/> Sincronizando...</> : <><Icon name="recurring" size={14}/> Forçar sincronização</>}
          </button>
        </div>
      </div>

      <div className="kpi-grid kpi-4">
        <KPI label="Pipelines ativas" value="8/8" sub="todas operando" accent="var(--success)" />
        <KPI label="Latência média" value="3,4 min" sub="abaixo do SLA (15 min)" />
        <KPI label="Eventos (24h)" value="38.412" sub="registros sincronizados" sparkline={[28,32,30,35,33,38,42]}/>
        <KPI label="Uptime (30d)" value="99,94%" sub="2 incidentes resolvidos" accent="var(--cefeq-blue)" />
      </div>

      <div className="grid-2-1">
        <div className="card">
          <div className="card-head">
            <h3>Pipelines de dados</h3>
            <div className="muted">Conexão Sollus ERP → CEFEQ BI</div>
          </div>
          <div className="table">
            <div className="table-head">
              <div style={{ flex: 2 }}>Pipeline</div>
              <div style={{ flex: 1 }}>Status</div>
              <div style={{ flex: 1 }}>Registros</div>
              <div style={{ flex: 1 }}>Latência</div>
              <div style={{ flex: 1 }}>Último evento</div>
            </div>
            {pipelines.map((p, i) => (
              <div key={i} className="table-row">
                <div style={{ flex: 2 }}>
                  <div style={{ fontWeight: 600 }}>{p.name}</div>
                  {p.note && <div className="muted" style={{ fontSize: 11 }}>{p.note}</div>}
                </div>
                <div style={{ flex: 1 }}>
                  <span className={`status-dot ${p.status === "ok" ? "on" : "warn"}`}/>
                  <span style={{ marginLeft: 6, textTransform: "capitalize" }}>{p.status === "ok" ? "Saudável" : "Atenção"}</span>
                </div>
                <div style={{ flex: 1 }} className="mono">{p.records}</div>
                <div style={{ flex: 1 }} className="mono">{p.latency}</div>
                <div style={{ flex: 1 }} className="muted">{p.lastEvent}</div>
              </div>
            ))}
          </div>
        </div>

        <div className="card">
          <div className="card-head">
            <h3>Log de eventos</h3>
            <div className="muted">tempo real</div>
          </div>
          <div className="event-log">
            {events.map((e, i) => (
              <div key={i} className="event-row">
                <span className={`event-dot event-${e.type}`}/>
                <span className="event-time mono">{e.time}</span>
                <span className="event-msg">{e.msg}</span>
              </div>
            ))}
          </div>
        </div>
      </div>

      <div className="card">
        <div className="card-head">
          <h3>Conexão técnica</h3>
        </div>
        <div className="conn-grid">
          <div className="conn-item">
            <div className="muted">Endpoint Sollus</div>
            <div className="mono">https://api.sollus.cefeq.local/v4/nrt</div>
          </div>
          <div className="conn-item">
            <div className="muted">Método de autenticação</div>
            <div>OAuth 2.0 + mTLS</div>
          </div>
          <div className="conn-item">
            <div className="muted">Token expira em</div>
            <div className="mono">14d 8h 22min</div>
          </div>
          <div className="conn-item">
            <div className="muted">Modo</div>
            <div>NRT (Polling + Webhooks)</div>
          </div>
          <div className="conn-item">
            <div className="muted">Ambiente</div>
            <div><Pill variant="success">Produção</Pill></div>
          </div>
          <div className="conn-item">
            <div className="muted">Backup secundário</div>
            <div>Snapshot diário · 03:00</div>
          </div>
        </div>
      </div>

      {toastNode}
    </>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// NOTIFICATIONS DRAWER
// ─────────────────────────────────────────────────────────────────────────────
// Gera lista de alertas dinâmicos baseados em dados reais (re-calcula em cada render)
function computeAlerts() {
  const M = window.MOCK;
  const now = window.MOCK.NOW;
  const alerts = [];

  // 1. Clientes com 90+ dias sem comprar (recência > 90)
  const inactive90 = M.CUSTOMERS.filter(c => c.daysInactive >= 90);
  if (inactive90.length > 0) {
    alerts.push({
      id: "inactive-90",
      type: "alert", icon: "inactive",
      title: `${inactive90.length} clientes ultrapassaram 90 dias sem comprar`,
      sub: `LTV em risco: ${fmtBRLshort(inactive90.reduce((s, c) => s + c.ltv, 0))}`,
      time: "agora", action: "inactive",
    });
  }

  // 2. Bateu meta? (mock: usa growth YTD > 5%)
  const ytd25 = M.REVENUE_MONTHLY.slice(0, 9).reduce((s, r) => s + (r.y25 || 0), 0);
  const ytd26 = M.REVENUE_MONTHLY.slice(0, 9).reduce((s, r) => s + (r.y26 || 0), 0);
  const growth = (ytd26 - ytd25) / ytd25;
  if (growth >= 0.05) {
    alerts.push({
      id: "goal-month",
      type: "goal", icon: "overview",
      title: `${now.monthLong} acima do esperado · +${(growth * 100).toFixed(1).replace(".", ",")}%`,
      sub: `Faturamento: ${fmtBRLshort(ytd26)} vs ${fmtBRLshort(ytd25)} em ${now.prevYear}`,
      time: "há 2h", action: "overview",
    });
  }

  // 3. Marca em maior crescimento (oportunidade)
  const topGrowthBrand = [...M.BRANDS].sort((a, b) => b.growth - a.growth)[0];
  if (topGrowthBrand && topGrowthBrand.growth >= 0.20) {
    alerts.push({
      id: "growth-brand",
      type: "growth", icon: "brands",
      title: `${topGrowthBrand.name} em alta · +${(topGrowthBrand.growth * 100).toFixed(1).replace(".", ",")}% YoY`,
      sub: `Oportunidade de aumentar mix com este fornecedor`,
      time: "há 4h", action: "brands",
    });
  }

  // 4. Maior cliente em risco (VIP + dias inativo)
  const vipAtRisk = [...M.CUSTOMERS]
    .filter(c => c.daysInactive >= 90 && c.ltv >= 50_000)
    .sort((a, b) => b.ltv - a.ltv)[0];
  if (vipAtRisk) {
    alerts.push({
      id: "risk-vip",
      type: "risk", icon: "inactive",
      title: `${vipAtRisk.name} · ${vipAtRisk.daysInactive} dias sem compra`,
      sub: `Cliente VIP · LTV ${fmtBRLshort(vipAtRisk.ltv)} em risco`,
      time: "ontem", action: "inactive",
    });
  }

  // 5. Marca em queda relevante
  const fallingBrand = [...M.BRANDS]
    .filter(b => b.growth < 0 && b.rev > 200_000)
    .sort((a, b) => a.growth - b.growth)[0];
  if (fallingBrand) {
    alerts.push({
      id: "alert-brand-fall",
      type: "alert", icon: "brands",
      title: `${fallingBrand.name} caiu ${(fallingBrand.growth * 100).toFixed(1).replace(".", ",")}% YoY`,
      sub: `Reavaliar mix · faturamento ainda relevante (${fmtBRLshort(fallingBrand.rev)})`,
      time: "2 dias", action: "brands",
    });
  }

  // 6. Setor em queda
  const fallingSector = [...M.SECTORS]
    .filter(s => s.growth < 0)
    .sort((a, b) => a.growth - b.growth)[0];
  if (fallingSector) {
    alerts.push({
      id: "alert-sector-fall",
      type: "alert", icon: "sectors",
      title: `${fallingSector.name} caiu ${(fallingSector.growth * 100).toFixed(1).replace(".", ",")}% no período`,
      sub: `Avaliar campanha promocional ou descontinuar SKUs parados`,
      time: "2 dias", action: "sectors",
    });
  }

  // 7. Top vendedor do mês
  const topSeller = [...M.SELLERS].sort((a, b) => b.growth - a.growth)[0];
  if (topSeller) {
    alerts.push({
      id: "info-seller",
      type: "info", icon: "sellers",
      title: `${topSeller.name.split(" ")[0]} ${topSeller.name.split(" ")[1]} lidera crescimento em ${now.monthLong}`,
      sub: `+${(topSeller.growth * 100).toFixed(1).replace(".", ",")}% YoY · ticket médio ${fmtBRL(topSeller.ticket)}`,
      time: "ontem", action: "sellers",
    });
  }

  // 8. Concentração de LTV (top 5% recorrentes)
  const recurring = M.CUSTOMERS.filter(c => c.totalOrders > 1).sort((a, b) => b.ltv - a.ltv);
  const top5pct = recurring.slice(0, Math.floor(recurring.length * 0.05));
  const totalLTV = recurring.reduce((s, c) => s + c.ltv, 0);
  const top5LTV = top5pct.reduce((s, c) => s + c.ltv, 0);
  if (top5pct.length > 0) {
    alerts.push({
      id: "goal-concentration",
      type: "goal", icon: "recurring",
      title: `Top 5% da carteira concentra ${Math.round((top5LTV / totalLTV) * 100)}% do LTV`,
      sub: `${top5pct.length} clientes representam ${fmtBRLshort(top5LTV)} · acionar plano de fidelização`,
      time: "3 dias", action: "recurring",
    });
  }

  return alerts;
}

window.computeAlerts = computeAlerts;

function NotificationsDrawer({ open, onClose, onNavigate }) {
  const [filter, setFilter] = useStateE("all");
  const items = computeAlerts();

  if (!open) return null;

  const filtered = filter === "all" ? items : items.filter(i => {
    if (filter === "alerts") return ["alert", "risk"].includes(i.type);
    if (filter === "goals") return i.type === "goal";
    if (filter === "opportunities") return ["growth", "info"].includes(i.type);
    return true;
  });

  const counts = {
    all: items.length,
    alerts: items.filter(i => ["alert", "risk"].includes(i.type)).length,
    goals: items.filter(i => i.type === "goal").length,
    opportunities: items.filter(i => ["growth", "info"].includes(i.type)).length,
  };

  return (
    <>
      <div className="drawer-overlay" onClick={onClose}/>
      <div className="drawer">
        <div className="drawer-head">
          <div>
            <h3>Notificações inteligentes</h3>
            <div className="muted" style={{ fontSize: 12 }}>{items.length} sinais detectados nos seus dados</div>
          </div>
          <button className="icon-btn" onClick={onClose}><Icon name="close" size={16}/></button>
        </div>
        <div className="drawer-filter">
          <button className={`seg-btn ${filter === "all" ? "active" : ""}`} onClick={() => setFilter("all")}>
            Todas <span className="notif-count">{counts.all}</span>
          </button>
          <button className={`seg-btn ${filter === "alerts" ? "active" : ""}`} onClick={() => setFilter("alerts")}>
            Alertas <span className="notif-count">{counts.alerts}</span>
          </button>
          <button className={`seg-btn ${filter === "goals" ? "active" : ""}`} onClick={() => setFilter("goals")}>
            Metas <span className="notif-count">{counts.goals}</span>
          </button>
          <button className={`seg-btn ${filter === "opportunities" ? "active" : ""}`} onClick={() => setFilter("opportunities")}>
            Oportunidades <span className="notif-count">{counts.opportunities}</span>
          </button>
        </div>
        <div className="drawer-list">
          {filtered.length === 0 && (
            <div className="muted" style={{ padding: 20, textAlign: "center", fontSize: 13 }}>
              Nenhuma notificação nesta categoria.
            </div>
          )}
          {filtered.map(it => (
            <button key={it.id} className={`notif-row notif-${it.type}`} onClick={() => { onNavigate(it.action); onClose(); }}>
              <div className="notif-icon"><Icon name={it.icon} size={16}/></div>
              <div className="notif-meta">
                <div className="notif-title">{it.title}</div>
                <div className="notif-sub">{it.sub}</div>
                <div className="notif-time">{it.time}</div>
              </div>
              <Icon name="chevron" size={14} style={{ alignSelf: "center", opacity: 0.4 }}/>
            </button>
          ))}
        </div>
        <div className="drawer-foot">
          <button className="btn btn-ghost btn-block">Marcar todas como lidas</button>
        </div>
      </div>
    </>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// BOTTOM NAV (mobile)
// ─────────────────────────────────────────────────────────────────────────────
function BottomNav({ current, onNavigate }) {
  const items = [
    { key: "overview", label: "Início",    icon: "overview" },
    { key: "sellers",  label: "Vendedores", icon: "sellers" },
    { key: "inactive", label: "Clientes",  icon: "inactive" },
    { key: "cashflow", label: "Caixa",     icon: "recurring" },
    { key: "more",     label: "Mais",      icon: "dots" },
  ];
  return (
    <nav className="bottom-nav">
      {items.map(it => (
        <button key={it.key}
          className={`bn-btn ${current === it.key || (it.key === "more" && !["overview","sellers","inactive","cashflow"].includes(current)) ? "active" : ""}`}
          onClick={() => onNavigate(it.key)}>
          <Icon name={it.icon} size={20}/>
          <span>{it.label}</span>
        </button>
      ))}
    </nav>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// MOBILE SHELL (wraps app in iPhone frame)
// ─────────────────────────────────────────────────────────────────────────────
function MobileShell({ screen, onNavigate, dark, onToggleTheme, onOpenNotifs, onSwitchToDesktop, notifsOpen, onCloseNotifs, children }) {
  const [moreOpen, setMoreOpen] = useStateE(false);
  const [profileOpen, setProfileOpen] = useStateE(false);
  const showingMore = screen === "more";

  return (
    <div className="mobile-stage">
      <div className="mobile-stage-bg">
        <div className="ms-blob ms-blob-1"/>
        <div className="ms-blob ms-blob-2"/>
        <div className="ms-grid"/>
      </div>

      <IOSDevice width={402} height={874} dark={dark}>
        <div className="mobile-app" data-view="mobile">
          {/* status bar spacer */}
          <div style={{ height: 56 }}/>

          {/* mobile topbar */}
          <header className="m-topbar">
            <CefeqMark height={24}/>
            <div style={{ flex: 1 }}/>
            <button className="m-icon-btn" onClick={onOpenNotifs}>
              <Icon name="bell" size={17}/>
              <span className="badge-dot" style={{ top: 6, right: 6 }}/>
            </button>
            <button className="m-avatar-btn" onClick={() => setProfileOpen(true)}>
              <div className="avatar sm" style={{ width: 30, height: 30, fontSize: 11 }}>FS</div>
            </button>
          </header>

          <div className="m-content">
            {showingMore ? <MobileMoreMenu onNavigate={onNavigate}/> : children}
          </div>

          {/* bottom nav */}
          <BottomNav current={screen} onNavigate={onNavigate}/>

          {/* home indicator spacer */}
          <div style={{ height: 38 }}/>

          {/* Profile sheet (inside frame so it slides up from bottom) */}
          <MobileProfileSheet
            open={profileOpen}
            onClose={() => setProfileOpen(false)}
            onNavigate={onNavigate}
            dark={dark}
            onToggleTheme={onToggleTheme}
            onSwitchToDesktop={onSwitchToDesktop}
          />

          {/* Notifications panel (inside frame) */}
          <MobileNotifsPanel
            open={notifsOpen}
            onClose={onCloseNotifs}
            onNavigate={(s) => { onNavigate(s); onCloseNotifs && onCloseNotifs(); }}
          />
        </div>
      </IOSDevice>

      <div className="mobile-stage-foot">
        <span>Vista prévia mobile · interativa, mesmas telas, mesmo motor de dados</span>
        <button className="back-to-desktop" onClick={onSwitchToDesktop}>
          <Icon name="chevron" size={12} style={{ transform: "rotate(180deg)" }}/>
          Voltar para versão desktop
        </button>
      </div>
    </div>
  );
}

function MobileMoreMenu({ onNavigate }) {
  const items = [
    { key: "brands",    label: "Marcas / Produtos", icon: "brands",    sub: "Ranking multi-dimensão" },
    { key: "sectors",   label: "Setores",           icon: "sectors",   sub: "Análise por categoria" },
    { key: "recurring", label: "Recorrentes",       icon: "recurring", sub: "Clientes com >1 venda" },
    { key: "dre",       label: "DRE",               icon: "overview",  sub: "Demonstrativo de resultado" },
    { key: "cashflow",  label: "Fluxo de Caixa",    icon: "recurring", sub: "Entradas, saídas e saldo" },
    { key: "forecast",  label: "Previsão de Vendas", icon: "arrowUp",  sub: "Projeção com ML · Premium" },
    { key: "ecommerce", label: "E-commerce",        icon: "recurring", sub: "Canal online · funil e tráfego" },
    { key: "admin",     label: "Administração",     icon: "admin",     sub: "Usuários, lojas, integrações" },
  ];
  return (
    <div className="m-more">
      <h2 className="m-h1">Mais</h2>
      <div className="m-list">
        {items.map(it => (
          <button key={it.key} className="m-list-row" onClick={() => onNavigate(it.key)}>
            <div className="m-list-icon"><Icon name={it.icon} size={18}/></div>
            <div className="m-list-meta">
              <div className="m-list-title">{it.label}</div>
              <div className="m-list-sub">{it.sub}</div>
            </div>
            <Icon name="chevron" size={14} style={{ opacity: 0.4 }}/>
          </button>
        ))}
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// PRICING & PLANS — acessível apenas via ?planos=1 (não exposto ao cliente no Admin)
// Estrutura: preço por LOJA/mês (anchor agressivo). Mais plano = mais valor = mais R$/loja.
// ─────────────────────────────────────────────────────────────────────────────
function PricingTab() {
  // CEFEQ tem 5 unidades operacionais (Matriz PG + Loja 2 PG + Castro + Ecom + Assist)
  const [stores, setStores] = useStateE(5);
  const [interval, setInterval] = useStateE("monthly");
  const yearlyDiscount = 0.15; // 15% desconto anual

  const plans = [
    {
      id: "essencial",
      name: "Essencial",
      tagline: "BI básico pra começar a olhar dados com seriedade",
      pricePerStore: 600,
      tone: "neutral",
      highlights: [
        "KPIs principais e drill básico",
        "Análise por vendedor e setor",
        "Clientes inativos e recorrentes",
        "Mobile + Imprimir PDF",
        "Atualização D-1 (dia seguinte)",
      ],
    },
    {
      id: "profissional",
      name: "Profissional",
      tagline: "BI completo com alertas e ações sugeridas — sweet spot do varejo",
      pricePerStore: 1100,
      tone: "blue",
      highlight: true,
      ribbon: "MAIS ESCOLHIDO",
      highlights: [
        "Tudo do Essencial",
        "Alertas inteligentes (sino com sinais reais)",
        "Resumo executivo automático no topo",
        "DRE completo + Fluxo de caixa",
        "Drill multi-dimensão (marcas, setores, categorias, produtos)",
        "Ações sugeridas em carteira de clientes",
        "Comparativo entre lojas",
        "Suporte por WhatsApp em horário comercial",
      ],
    },
    {
      id: "avancado",
      name: "Avançado",
      tagline: "BI em tempo quase real + você participa do produto",
      pricePerStore: 2000,
      tone: "yellow",
      ribbon: "BETA TESTER + CUSTOM",
      highlights: [
        "Tudo do Profissional",
        "Frescor dos dados no ritmo do ERP (Sollus, Bling, Tiny — geralmente 15min-2h)",
        "Integração ERP + e-commerce reconciliados",
        "Previsão de vendas com ML básica",
        "API pra integrações customizadas",
        "Painel de gestão de acessos + heatmap de uso",
        "Beta tester oficial · features novas antes",
        "Customização sob demanda · pediu, vai pro roadmap",
        "Suporte prioritário + reuniões mensais",
      ],
    },
    {
      id: "enterprise",
      name: "Enterprise",
      tagline: "Operação completa com Adri, sua Gestora de Insights Automatizados",
      pricePerStore: 4500,
      tone: "dark",
      ribbon: "PREMIUM",
      highlights: [
        "Tudo do Avançado",
        "🤖 Adri · Gestora de Insights Automatizados",
        "Alertas direcionados via WhatsApp pra CEO e gerentes",
        "Relatório diário com onde está a sangria e onde está o lucro",
        "Geração de campanhas integradas por loja",
        "Sistema operacional integrado (alertas em tempo real)",
        "Suporte 24/7 com IA + humano",
        "Gerente de conta dedicado · reuniões quinzenais",
        "Consultor de pricing de produto",
        "White-label completo · sua marca",
        "Servidor dedicado / on-premise opcional",
      ],
    },
  ];

  // Tabela comparativa — recursos vs planos
  const comparisonRows = [
    { section: "📊 ANÁLISE E DASHBOARDS" },
    { feature: "KPIs principais (faturamento, margem, ticket)",     essencial: true, profissional: true, avancado: true, enterprise: true },
    { feature: "Análise por vendedor e setor",                       essencial: true, profissional: true, avancado: true, enterprise: true },
    { feature: "Clientes inativos e recorrentes",                    essencial: true, profissional: true, avancado: true, enterprise: true },
    { feature: "Drill multi-dimensão (marcas / categorias / produtos)", essencial: false, profissional: true, avancado: true, enterprise: true },
    { feature: "Comparativo entre lojas",                            essencial: false, profissional: true, avancado: true, enterprise: true },
    { feature: "Geografia de e-commerce (estado → cidade)",          essencial: false, profissional: false, avancado: true, enterprise: true },
    { feature: "Previsão de vendas com Machine Learning",            essencial: false, profissional: false, avancado: "básica", enterprise: "avançada" },

    { section: "🚨 ALERTAS E AÇÕES" },
    { feature: "Resumo executivo automático no topo",                essencial: false, profissional: true, avancado: true, enterprise: true },
    { feature: "Alertas inteligentes no sino",                       essencial: false, profissional: true, avancado: true, enterprise: true },
    { feature: "Ações sugeridas por cliente (Inativos/Recorrentes)", essencial: false, profissional: true, avancado: true, enterprise: true },
    { feature: "Adri — alertas via WhatsApp pra CEO/gerentes",       essencial: false, profissional: false, avancado: false, enterprise: true },
    { feature: "Adri — relatório diário com onde está a sangria",    essencial: false, profissional: false, avancado: false, enterprise: true },
    { feature: "Adri — geração de campanhas por loja",               essencial: false, profissional: false, avancado: false, enterprise: true },

    { section: "💰 FINANCEIRO" },
    { feature: "DRE completo (Receita → Lucro Líquido)",             essencial: false, profissional: true, avancado: true, enterprise: true },
    { feature: "Fluxo de caixa com calendário",                      essencial: false, profissional: true, avancado: true, enterprise: true },
    { feature: "Consultor de pricing de produto",                    essencial: false, profissional: false, avancado: false, enterprise: true },

    { section: "🔄 ATUALIZAÇÃO E INTEGRAÇÃO" },
    { feature: "Frescor dos dados",                                  essencial: "D-1 (dia seguinte)", profissional: "D-1 + alertas no dia", avancado: "O mais rápido que o ERP permitir", enterprise: "Tempo real quando viável" },
    { feature: "Integração com ERP (Sollus, Bling, Tiny, etc)",      essencial: false, profissional: false, avancado: true, enterprise: true },
    { feature: "Integração com e-commerce (Tray, Shopify, etc)",     essencial: false, profissional: false, avancado: true, enterprise: true },
    { feature: "Reconciliação ERP + e-commerce",                     essencial: false, profissional: false, avancado: true, enterprise: true },
    { feature: "API pra integrações customizadas",                   essencial: false, profissional: false, avancado: true, enterprise: true },
    { feature: "Sistema operacional integrado",                      essencial: false, profissional: false, avancado: false, enterprise: true },

    { section: "🎨 EXPERIÊNCIA" },
    { feature: "Mobile responsivo + dark mode",                      essencial: true, profissional: true, avancado: true, enterprise: true },
    { feature: "Imprimir relatórios em PDF",                         essencial: true, profissional: true, avancado: true, enterprise: true },
    { feature: "Filtros avançados multi-dimensão",                   essencial: false, profissional: true, avancado: true, enterprise: true },
    { feature: "White-label completo (sua marca)",                   essencial: false, profissional: false, avancado: false, enterprise: true },

    { section: "🛠️ PRODUTO E SUPORTE" },
    { feature: "Suporte por chat / e-mail",                          essencial: true, profissional: true, avancado: true, enterprise: true },
    { feature: "Suporte por WhatsApp comercial",                     essencial: false, profissional: true, avancado: true, enterprise: true },
    { feature: "Suporte prioritário + reuniões mensais",             essencial: false, profissional: false, avancado: true, enterprise: true },
    { feature: "Suporte 24/7 com IA + humano",                       essencial: false, profissional: false, avancado: false, enterprise: true },
    { feature: "Gerente de conta dedicado",                          essencial: false, profissional: false, avancado: false, enterprise: true },
    { feature: "Beta tester oficial (features antes)",               essencial: false, profissional: false, avancado: true, enterprise: true },
    { feature: "Customização sob demanda (roadmap compartilhado)",   essencial: false, profissional: false, avancado: true, enterprise: true },

    { section: "🏗️ INFRA" },
    { feature: "Hospedagem",                                          essencial: "Compartilhada", profissional: "Compartilhada", avancado: "Schema dedicado", enterprise: "Servidor dedicado" },
    { feature: "SLA",                                                 essencial: false, profissional: false, avancado: "99,5%", enterprise: "99,9%" },
    { feature: "On-premise opcional",                                essencial: false, profissional: false, avancado: false, enterprise: true },
  ];

  const addons = [
    { name: "Marketplace adicional",  desc: "Tray, Magalu, Mercado Livre — cada conexão extra",  price: "R$ 690/mês cada" },
    { name: "Onboarding presencial",  desc: "Visita técnica de 1 dia em Ponta Grossa ou Castro",  price: "R$ 2.500 (único)" },
    { name: "Treinamento de equipe",  desc: "Sessão de 4h presencial ou online",                  price: "R$ 1.500 por sessão" },
    { name: "Hora extra de desenvolvimento", desc: "Customizações pontuais fora do roadmap padrão", price: "R$ 250/hora" },
  ];

  function priceFor(plan) {
    const monthly = plan.pricePerStore * stores;
    if (interval === "yearly") return Math.round(monthly * (1 - yearlyDiscount));
    return monthly;
  }

  function renderCell(v) {
    if (v === true) return <span className="pcmp-check">✓</span>;
    if (v === false) return <span className="pcmp-x">—</span>;
    return <span className="pcmp-text">{v}</span>;
  }

  return (
    <>
      {/* HERO */}
      <div className="pricing-hero pricing-hero-v2">
        <div className="pricing-eyebrow">PLANOS · INVESTIMENTO POR LOJA</div>
        <h2 className="pricing-h1">Cada plano é um nível de profundidade diferente</h2>
        <p className="pricing-sub">
          Quanto mais profundo, mais análise, automação e suporte. Por isso o investimento por loja sobe — não desce.
          Mais lojas + mais complexidade de análise = mais valor entregue.
        </p>

        <div className="pricing-controls">
          <div className="pricing-stores">
            <label>Sua operação tem</label>
            <div className="seg-control">
              {[1, 3, 5, 8, 12].map(n => (
                <button
                  key={n}
                  type="button"
                  className={`seg-btn ${stores === n ? "active" : ""}`}
                  onClick={() => setStores(n)}
                >
                  {n} {n === 1 ? "loja" : "lojas"}
                </button>
              ))}
            </div>
          </div>
          <div className="pricing-interval-v2">
            <div className="seg-control">
              <button className={`seg-btn ${interval==="monthly"?"active":""}`} onClick={()=>setInterval("monthly")}>Mensal</button>
              <button className={`seg-btn ${interval==="yearly"?"active":""}`} onClick={()=>setInterval("yearly")}>
                Anual <span className="save-pill">−15%</span>
              </button>
            </div>
          </div>
        </div>
      </div>

      {/* 4 CARDS */}
      <div className="plans-grid-v2">
        {plans.map((p) => {
          const totalPrice = priceFor(p);
          const adjPerStore = interval === "yearly"
            ? Math.round(p.pricePerStore * (1 - yearlyDiscount))
            : p.pricePerStore;
          return (
            <div
              key={p.id}
              className={`plan-card-v2 plan-tone-${p.tone} ${p.highlight ? "is-highlight" : ""}`}
            >
              {p.ribbon && (
                <div className={`plan-ribbon plan-ribbon-${p.tone}`}>{p.ribbon}</div>
              )}

              <div className="plan-card-head">
                <div className="plan-name">{p.name}</div>
                <div className="plan-tagline">{p.tagline}</div>
              </div>

              <div className="plan-price-block">
                <div className="plan-price-hero">
                  <span className="pp-currency">R$</span>
                  <span className="pp-val">{adjPerStore.toLocaleString("pt-BR")}</span>
                  <span className="pp-period">/loja/mês</span>
                </div>
                <div className="plan-total-row">
                  Operação com <strong>{stores} {stores === 1 ? "loja" : "lojas"}</strong>:
                  <span className="plan-total">R$ {totalPrice.toLocaleString("pt-BR")}/mês</span>
                </div>
                {interval === "yearly" && (
                  <div className="plan-yearly-hint">
                    Anual: R$ {(totalPrice * 12).toLocaleString("pt-BR")} (economia de 15%)
                  </div>
                )}
              </div>

              <ul className="plan-features-v2">
                {p.highlights.map((h, i) => (
                  <li key={i}><span className="plan-feat-check">✓</span> {h}</li>
                ))}
              </ul>

              <button className={`btn ${p.highlight ? "btn-primary" : "btn-outline"} btn-block plan-cta`}>
                Falar com vendas
              </button>
            </div>
          );
        })}
      </div>

      {/* TABELA COMPARATIVA DETALHADA */}
      <div className="card pricing-compare-card">
        <div className="card-head">
          <div>
            <h3>Comparativo completo entre planos</h3>
            <div className="muted">Cada linha é um recurso · veja o salto de valor entre os níveis</div>
          </div>
        </div>
        <div className="pcmp-table">
          <div className="pcmp-row pcmp-row-head">
            <div className="pcmp-feature">Recurso</div>
            <div className="pcmp-cell">Essencial</div>
            <div className="pcmp-cell">Profissional</div>
            <div className="pcmp-cell">Avançado</div>
            <div className="pcmp-cell">Enterprise</div>
          </div>
          {comparisonRows.map((row, i) => {
            if (row.section) {
              return (
                <div key={i} className="pcmp-row pcmp-row-section">
                  <div className="pcmp-section">{row.section}</div>
                </div>
              );
            }
            return (
              <div key={i} className="pcmp-row">
                <div className="pcmp-feature">{row.feature}</div>
                <div className="pcmp-cell">{renderCell(row.essencial)}</div>
                <div className="pcmp-cell">{renderCell(row.profissional)}</div>
                <div className="pcmp-cell">{renderCell(row.avancado)}</div>
                <div className="pcmp-cell">{renderCell(row.enterprise)}</div>
              </div>
            );
          })}
        </div>
      </div>

      {/* ADD-ONS */}
      <div className="card pricing-addons-card">
        <div className="card-head">
          <div>
            <h3>Add-ons opcionais</h3>
            <div className="muted">Cobrados separado · não estão incluídos nos planos acima</div>
          </div>
        </div>
        <div className="addons-grid">
          {addons.map((a, i) => (
            <div key={i} className="addon-card-v2">
              <div className="addon-name">{a.name}</div>
              <div className="addon-desc">{a.desc}</div>
              <div className="addon-price">{a.price}</div>
            </div>
          ))}
        </div>
      </div>

      {/* FOOTNOTE */}
      <div className="pricing-footnote">
        <strong>Por que cobramos por loja?</strong> Cada loja adicional traz volumetria,
        integrações específicas, suporte e relacionamento. O custo de operação cresce com o
        tamanho da operação — então o preço também. Quanto mais lojas, mais entrega.
        Quanto mais plano, mais profundidade de análise e automação. As duas dimensões se
        somam — não se anulam.
      </div>
    </>
  );
}

window.PricingTab = PricingTab;
// ─────────────────────────────────────────────────────────────────────────────
function FilterDialog({ open, onClose, onApply, scope = "overview" }) {
  const M = window.MOCK;
  const [showToast, setShowToast] = useStateE(false);

  if (!open) return null;

  return (
    <Modal open={open} onClose={onClose} wide
      title="Filtros"
      subtitle="Refine os dados exibidos"
      footer={<>
        <button className="btn btn-ghost" onClick={onClose}>Cancelar</button>
        <button className="btn btn-outline">Limpar filtros</button>
        <button className="btn btn-primary" onClick={() => { onApply && onApply(); onClose(); }}>Aplicar</button>
      </>}>
      <div className="filter-grid">
        <div className="filter-block">
          <h4>Período</h4>
          <div className="seg-control" style={{ width: "100%" }}>
            <button className="seg-btn active">Mês</button>
            <button className="seg-btn">Trimestre</button>
            <button className="seg-btn">Semestre</button>
            <button className="seg-btn">YTD</button>
            <button className="seg-btn">12 meses</button>
            <button className="seg-btn">Personalizado</button>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10, marginTop: 10 }}>
            <label className="field"><span>De</span><input type="date" defaultValue="2026-01-01"/></label>
            <label className="field"><span>Até</span><input type="date" defaultValue={window.MOCK.NOW.monthEndIso}/></label>
          </div>
        </div>

        <div className="filter-block">
          <h4>Loja / Canal</h4>
          <div className="check-list">
            <label className="check"><input type="checkbox" defaultChecked/> Matriz · Ponta Grossa</label>
            <label className="check"><input type="checkbox" defaultChecked/> Filial · Castro</label>
            <label className="check"><input type="checkbox" defaultChecked/> Assistência técnica</label>
            <label className="check"><input type="checkbox" defaultChecked/> E-commerce · cefeq.com.br</label>
            <label className="check"><input type="checkbox" defaultChecked/> CD Logístico · Carambeí</label>
          </div>
        </div>

        <div className="filter-block">
          <h4>Setor</h4>
          <div className="chip-list">
            {M.SECTORS.map(s => (
              <label key={s.name} className="chip">
                <input type="checkbox" defaultChecked/>
                <span style={{ display: "inline-block", width: 8, height: 8, borderRadius: 99, background: s.color, marginRight: 6 }}/>
                {s.name}
              </label>
            ))}
          </div>
        </div>

        <div className="filter-block">
          <h4>Vendedor</h4>
          <select className="filter-select" multiple style={{ height: 110 }} defaultValue={M.SELLERS.slice(0,4).map(s=>s.id)}>
            {M.SELLERS.map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
          </select>
          <div className="muted" style={{ fontSize: 11, marginTop: 4 }}>Segure Ctrl/Cmd para selecionar múltiplos</div>
        </div>

        <div className="filter-block">
          <h4>Marca</h4>
          <div className="chip-list">
            {M.BRANDS.slice(0, 10).map(b => (
              <label key={b.name} className="chip">
                <input type="checkbox" defaultChecked/> {b.name}
              </label>
            ))}
          </div>
        </div>

        <div className="filter-block">
          <h4>Tipo de cliente</h4>
          <div className="seg-control" style={{ width: "100%" }}>
            <button className="seg-btn active">Todos</button>
            <button className="seg-btn">Recorrente</button>
            <button className="seg-btn">Novo</button>
            <button className="seg-btn">VIP</button>
            <button className="seg-btn">Em recuperação</button>
          </div>
        </div>

        <div className="filter-block">
          <h4>Comparação</h4>
          <div className="check-list">
            <label className="check"><input type="checkbox" defaultChecked/> Comparar com ano anterior (2025)</label>
            <label className="check"><input type="checkbox"/> Comparar com mesmo período do mês anterior</label>
            <label className="check"><input type="checkbox"/> Comparar com meta do período</label>
          </div>
        </div>
      </div>
    </Modal>
  );
}

window.FilterDialog = FilterDialog;

// ─────────────────────────────────────────────────────────────────────────────
// FILTROS — fonte da verdade global (lida por Overview/Brands/etc pra reagir)
// ─────────────────────────────────────────────────────────────────────────────
const FILTER_OPTIONS = {
  period: () => {
    const M = window.MOCK;
    return [
      { id: "month",     label: "Mês atual",       range: `${M.NOW.monthShort}/${M.NOW.year}`,     mult: 0.11 },
      { id: "quarter",   label: "Trimestre",       range: M.NOW.quarterRange,                       mult: 0.33 },
      { id: "semester",  label: "Semestre",        range: `S${M.NOW.monthIdx < 6 ? "1" : "2"}/${M.NOW.year}`, mult: 0.55 },
      { id: "ytd",       label: "Ano atual (YTD)", range: `Jan→${M.NOW.monthShort}/${M.NOW.year}`,  mult: 1.00 },
      { id: "12m",       label: "12 meses",        range: M.NOW.last12Range,                        mult: 1.32 },
      { id: "custom",    label: "Personalizado",   range: "Escolher datas",                         mult: 0.75 },
    ];
  },
  stores: () => [
    { id: "s01", short: "Matriz PG",   label: "Matriz · Ponta Grossa",     weight: 0.34 },
    { id: "s02", short: "Loja 2 PG",   label: "Loja 2 · Ponta Grossa",     weight: 0.20 },
    { id: "s03", short: "Castro",      label: "Filial · Castro",           weight: 0.16 },
    { id: "s04", short: "E-commerce",  label: "E-commerce · cefeq.com.br", weight: 0.27 },
    { id: "s05", short: "Assistência", label: "Assistência técnica",       weight: 0.03 },
  ],
  clientType: () => [
    { id: "all",       label: "Todos",          mult: 1.00 },
    { id: "recurring", label: "Recorrente",     mult: 0.72 },
    { id: "new",       label: "Novo",           mult: 0.18 },
    { id: "vip",       label: "VIP",            mult: 0.34 },
    { id: "recovery",  label: "Em recuperação", mult: 0.08 },
  ],
};

// Default = mês atual + todas lojas + comparar YoY (faz sentido pra demo)
function getDefaultFilters() {
  return {
    period: "ytd",
    stores: ["s01", "s02", "s03", "s04", "s05"],
    clientType: "all",
    sectors: window.MOCK.SECTORS.map(s => s.name),
    brands: window.MOCK.BRANDS.slice(0, 10).map(b => b.name),
    sellers: window.MOCK.SELLERS.map(s => s.id),
    compareYoY: true,
  };
}

// Init no boot
if (!window.MOCK.activeFilters) {
  window.MOCK.activeFilters = getDefaultFilters();
  window.MOCK._filterListeners = new Set();
}

// Hook simples pra forçar re-render quando filtros mudam
function useActiveFilters() {
  const [, setTick] = useStateE(0);
  useEffectE(() => {
    const fn = () => setTick(t => t + 1);
    window.MOCK._filterListeners.add(fn);
    return () => window.MOCK._filterListeners.delete(fn);
  }, []);
  return window.MOCK.activeFilters;
}

function applyFilters(next) {
  window.MOCK.activeFilters = next;
  window.MOCK._filterListeners.forEach(fn => fn());
}

// Computa o multiplicador efetivo aplicado aos KPIs (usado pelas telas)
function computeFilterMultiplier(filters) {
  const f = filters || window.MOCK.activeFilters;
  const periodMult = FILTER_OPTIONS.period().find(p => p.id === f.period)?.mult ?? 1.0;
  const stores = FILTER_OPTIONS.stores();
  const storeWeight = stores
    .filter(s => f.stores.includes(s.id))
    .reduce((sum, s) => sum + s.weight, 0);
  const clientMult = FILTER_OPTIONS.clientType().find(c => c.id === f.clientType)?.mult ?? 1.0;
  return periodMult * storeWeight * clientMult;
}

window.useActiveFilters = useActiveFilters;
window.applyFilters = applyFilters;
window.computeFilterMultiplier = computeFilterMultiplier;
window.FILTER_OPTIONS = FILTER_OPTIONS;

// ─────────────────────────────────────────────────────────────────────────────
// FilterBar — versão inline com pending state + Aplicar
// ─────────────────────────────────────────────────────────────────────────────
function FilterBar({ open, onClose }) {
  const M = window.MOCK;
  const applied = window.useActiveFilters();
  // Pending começa copiando do applied
  const [pending, setPending] = useStateE(applied);
  const [advancedOpen, setAdvancedOpen] = useStateE(false);

  // Reset pending quando applied muda externamente (ex: cleared from another spot)
  useEffectE(() => { setPending(applied); }, [applied]);

  if (!open) return null;

  const periodOptions = FILTER_OPTIONS.period();
  const storeOptions = FILTER_OPTIONS.stores();
  const clientTypeOptions = FILTER_OPTIONS.clientType();

  const dirty = JSON.stringify(pending) !== JSON.stringify(applied);
  const currentPeriod = periodOptions.find(p => p.id === pending.period) || periodOptions[0];

  function toggleStore(id) {
    setPending(prev => ({
      ...prev,
      stores: prev.stores.includes(id) ? prev.stores.filter(s => s !== id) : [...prev.stores, id],
    }));
  }
  const allStores = pending.stores.length === storeOptions.length;
  const activeCount = pending.stores.length;

  function handleApply() {
    window.applyFilters(pending);
  }
  function handleReset() {
    const def = getDefaultFilters();
    setPending(def);
    window.applyFilters(def);
  }

  return (
    <div className="fbar">
      <div className="fbar-head">
        <div className="fbar-title">
          <Icon name="filter" size={14}/>
          <span>Filtros</span>
          <span className="fbar-summary">
            {currentPeriod.label} <span className="muted">({currentPeriod.range})</span>
            {" · "}
            {allStores ? "Todas as lojas" : `${activeCount} loja${activeCount !== 1 ? "s" : ""}`}
            {pending.clientType !== "all" && (
              <> · {clientTypeOptions.find(c => c.id === pending.clientType).label}</>
            )}
            {pending.compareYoY && <> · comparando com 2025</>}
          </span>
          {dirty && (
            <span className="fbar-dirty-badge">alterações não aplicadas</span>
          )}
        </div>
        <div className="fbar-head-actions">
          <button className="btn btn-ghost btn-sm" onClick={() => setAdvancedOpen(true)}>
            Mais filtros…
          </button>
          <button className="btn btn-ghost btn-sm" onClick={handleReset} title="Restaurar padrão">
            Limpar
          </button>
          <button
            className={`btn btn-sm ${dirty ? "btn-primary" : "btn-outline"}`}
            onClick={handleApply}
            disabled={!dirty}
          >
            <Icon name="check" size={12}/> Aplicar
          </button>
          <button className="icon-btn" onClick={onClose} title="Fechar barra">
            <Icon name="close" size={14}/>
          </button>
        </div>
      </div>

      <div className="fbar-row">
        <div className="fbar-field">
          <label>Período</label>
          <div className="seg-control fbar-seg">
            {periodOptions.map(p => (
              <button
                key={p.id}
                className={`seg-btn ${pending.period === p.id ? "active" : ""}`}
                onClick={() => setPending(prev => ({ ...prev, period: p.id }))}
                type="button"
              >
                {p.label}
              </button>
            ))}
          </div>
        </div>
      </div>

      <div className="fbar-row">
        <div className="fbar-field">
          <label>Lojas e canais</label>
          <div className="fbar-chips">
            <button
              type="button"
              className={`fbar-chip ${allStores ? "is-active" : ""}`}
              onClick={() => setPending(prev => ({
                ...prev,
                stores: allStores ? [] : storeOptions.map(s => s.id),
              }))}
            >
              <span className="fbar-chip-dot" style={{ background: "var(--cefeq-blue)" }}/>
              Todas
            </button>
            {storeOptions.map(s => {
              const active = pending.stores.includes(s.id);
              return (
                <button
                  key={s.id}
                  type="button"
                  className={`fbar-chip ${active ? "is-active" : ""}`}
                  onClick={() => toggleStore(s.id)}
                  title={s.label}
                >
                  {active && <Icon name="check" size={11}/>}
                  {s.label}
                </button>
              );
            })}
          </div>
        </div>

        <div className="fbar-field">
          <label>Tipo de cliente</label>
          <div className="seg-control fbar-seg">
            {clientTypeOptions.map(c => (
              <button
                key={c.id}
                className={`seg-btn ${pending.clientType === c.id ? "active" : ""}`}
                onClick={() => setPending(prev => ({ ...prev, clientType: c.id }))}
                type="button"
              >
                {c.label}
              </button>
            ))}
          </div>
        </div>

        <div className="fbar-field fbar-field-toggle">
          <label>Comparação</label>
          <label className="fbar-toggle">
            <input
              type="checkbox"
              checked={pending.compareYoY}
              onChange={(e) => setPending(prev => ({ ...prev, compareYoY: e.target.checked }))}
            />
            <span>Comparar com {M.NOW.prevYear} (YoY)</span>
          </label>
        </div>
      </div>

      <AdvancedFilterDialog
        open={advancedOpen}
        onClose={() => setAdvancedOpen(false)}
        pending={pending}
        setPending={setPending}
      />
    </div>
  );
}

window.FilterBar = FilterBar;

// ─────────────────────────────────────────────────────────────────────────────
// AdvancedFilterDialog — modal pra setor/marca/vendedor (mesma linguagem visual)
// ─────────────────────────────────────────────────────────────────────────────
function AdvancedFilterDialog({ open, onClose, pending, setPending }) {
  const M = window.MOCK;
  if (!open) return null;

  function toggleArr(key, val) {
    setPending(prev => ({
      ...prev,
      [key]: prev[key].includes(val) ? prev[key].filter(x => x !== val) : [...prev[key], val],
    }));
  }

  function setAll(key, arr) {
    setPending(prev => ({ ...prev, [key]: arr }));
  }

  const allSectors = pending.sectors.length === M.SECTORS.length;
  const allBrands = pending.brands.length === M.BRANDS.slice(0, 10).length;
  const allSellers = pending.sellers.length === M.SELLERS.length;

  return (
    <Modal
      open={open}
      onClose={onClose}
      title="Filtros avançados"
      subtitle="Refine por setor, marca e vendedor"
      footer={<>
        <button className="btn btn-ghost" onClick={onClose}>Fechar</button>
      </>}
    >
      <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
        {/* SETORES */}
        <div className="fbar-field">
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 6 }}>
            <label>Setores ({pending.sectors.length}/{M.SECTORS.length})</label>
            <button className="link" type="button"
              onClick={() => setAll("sectors", allSectors ? [] : M.SECTORS.map(s => s.name))}
            >
              {allSectors ? "Desmarcar todos" : "Marcar todos"}
            </button>
          </div>
          <div className="fbar-chips">
            {M.SECTORS.map(s => {
              const active = pending.sectors.includes(s.name);
              return (
                <button
                  key={s.name}
                  type="button"
                  className={`fbar-chip ${active ? "is-active" : ""}`}
                  onClick={() => toggleArr("sectors", s.name)}
                >
                  <span className="fbar-chip-dot" style={{ background: s.color }}/>
                  {s.name}
                </button>
              );
            })}
          </div>
        </div>

        {/* MARCAS */}
        <div className="fbar-field">
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 6 }}>
            <label>Marcas (top 10) ({pending.brands.length}/10)</label>
            <button className="link" type="button"
              onClick={() => setAll("brands", allBrands ? [] : M.BRANDS.slice(0, 10).map(b => b.name))}
            >
              {allBrands ? "Desmarcar todas" : "Marcar todas"}
            </button>
          </div>
          <div className="fbar-chips">
            {M.BRANDS.slice(0, 10).map(b => {
              const active = pending.brands.includes(b.name);
              return (
                <button
                  key={b.name}
                  type="button"
                  className={`fbar-chip ${active ? "is-active" : ""}`}
                  onClick={() => toggleArr("brands", b.name)}
                >
                  {active && <Icon name="check" size={11}/>}
                  {b.name}
                </button>
              );
            })}
          </div>
        </div>

        {/* VENDEDORES */}
        <div className="fbar-field">
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 6 }}>
            <label>Vendedores ({pending.sellers.length}/{M.SELLERS.length})</label>
            <button className="link" type="button"
              onClick={() => setAll("sellers", allSellers ? [] : M.SELLERS.map(s => s.id))}
            >
              {allSellers ? "Desmarcar todos" : "Marcar todos"}
            </button>
          </div>
          <div className="fbar-chips">
            {M.SELLERS.map(s => {
              const active = pending.sellers.includes(s.id);
              return (
                <button
                  key={s.id}
                  type="button"
                  className={`fbar-chip ${active ? "is-active" : ""}`}
                  onClick={() => toggleArr("sellers", s.id)}
                >
                  <span
                    className="fbar-chip-dot"
                    style={{
                      background: "var(--cefeq-blue)",
                      opacity: active ? 1 : 0.3,
                    }}
                  />
                  {s.name}
                </button>
              );
            })}
          </div>
        </div>

        <div className="muted" style={{ fontSize: 12, padding: "8px 12px", background: "var(--surface-alt)", borderRadius: 8 }}>
          💡 As mudanças são aplicadas quando você clicar em <b>Aplicar</b> na barra de filtros principal.
        </div>
      </div>
    </Modal>
  );
}

window.AdvancedFilterDialog = AdvancedFilterDialog;

// ─────────────────────────────────────────────────────────────────────────────
// PrintPreviewModal — prévia visual de como o PDF vai ficar
// Substitui window.print() (que abre dialog do navegador e atrapalha a demo).
// ─────────────────────────────────────────────────────────────────────────────
const PRINT_PREVIEW_STATE = { open: false, scope: "overview" };

// Mapeia nome de tela → scope do PDF (Sidebar e Topbar atualizam isso)
window.CURRENT_SCREEN = "overview";

window.openPrintPreview = function(scope) {
  PRINT_PREVIEW_STATE.open = true;
  PRINT_PREVIEW_STATE.scope = scope || window.CURRENT_SCREEN || "overview";
  window.MOCK._filterListeners.forEach(fn => fn());
};
window.closePrintPreview = function() {
  PRINT_PREVIEW_STATE.open = false;
  window.MOCK._filterListeners.forEach(fn => fn());
};

function PrintPreviewModal() {
  const M = window.MOCK;
  window.useActiveFilters(); // pra forçar re-render no toggle
  const [confirmed, setConfirmed] = useStateE(false);

  // Reset confirmed sempre que o modal abrir (sem depender de state React)
  useEffectE(() => {
    if (PRINT_PREVIEW_STATE.open && confirmed) {
      // Modal já tinha sido confirmado antes, reseta
      const t = setTimeout(() => setConfirmed(false), 100);
      return () => clearTimeout(t);
    }
  });

  if (!PRINT_PREVIEW_STATE.open) return null;

  const filters = M.activeFilters;
  const currentPeriod = window.FILTER_OPTIONS.period().find(p => p.id === filters.period);
  const storesOpts = window.FILTER_OPTIONS.stores();
  const allStores = filters.stores.length === storesOpts.length;
  const storesLabel = allStores
    ? "Todas as lojas e canais"
    : filters.stores.map(id => storesOpts.find(s => s.id === id)?.label).filter(Boolean).join(" · ");

  const mult = window.computeFilterMultiplier(filters);
  const ytd26 = M.REVENUE_MONTHLY.slice(0, 9).reduce((s, r) => s + (r.y26 || 0), 0) * mult;
  const ytd25 = M.REVENUE_MONTHLY.slice(0, 9).reduce((s, r) => s + (r.y25 || 0), 0) * mult;
  const totalDeals = Math.round(M.SELLERS.reduce((s, v) => s + v.deals, 0) * mult);
  const blendedTicket = totalDeals > 0 ? ytd26 / totalDeals : 0;

  const scope = PRINT_PREVIEW_STATE.scope || "overview";

  // Labels e títulos por scope
  const scopeMeta = {
    overview:  { title: "Resumo Executivo",         subtitle: "Visão geral e KPIs principais" },
    brands:    { title: "Análise de Marcas",   subtitle: "Ranking, participação e crescimento" },
    sectors:   { title: "Análise de Setores",  subtitle: "Distribuição por categoria de produto" },
    sellers:   { title: "Performance Comercial",    subtitle: "Ranking de vendedores" },
    inactive:  { title: "Clientes Inativos",        subtitle: "Carteira em risco e ações sugeridas" },
    recurring: { title: "Clientes Recorrentes",     subtitle: "Carteira fiel e oportunidades de upsell" },
    dre:       { title: "DRE",                       subtitle: "Demonstrativo do Resultado" },
    cashflow:  { title: "Fluxo de Caixa",           subtitle: "Entradas e saídas do período" },
    closing:   { title: "Fechamento Diário",   subtitle: "Resultado operacional do dia" },
    forecast:  { title: "Previsão de Vendas",  subtitle: "Projeção pelos próximos meses" },
    ecommerce: { title: "E-commerce",               subtitle: "Performance do canal online" },
  };
  const meta = scopeMeta[scope] || scopeMeta.overview;

  function handleClose() { window.closePrintPreview(); }
  function handleConfirm() {
    setConfirmed(true);
    setTimeout(() => {
      setConfirmed(false);
      handleClose();
    }, 1600);
  }

  // Conteúdo específico por scope (renderiza tabelas/cards diferentes)
  function renderScopeContent() {
    if (scope === "brands") {
      const sorted = [...M.BRANDS].sort((a, b) => b.rev - a.rev).slice(0, 10);
      const totalRev = M.BRANDS.reduce((s, b) => s + b.rev, 0);
      return (
        <>
          <div className="pp-section-title">Top 10 marcas · {currentPeriod.label}</div>
          <table className="pp-table">
            <thead><tr><th style={{ width: 30 }}>#</th><th>Marca</th><th style={{ textAlign: "right" }}>Faturamento</th><th style={{ textAlign: "right" }}>Margem</th><th style={{ textAlign: "right" }}>Crescimento</th><th style={{ textAlign: "right" }}>Particip.</th></tr></thead>
            <tbody>
              {sorted.map((b, i) => (
                <tr key={b.name}>
                  <td>{i === 0 ? "🥇" : i === 1 ? "🥈" : i === 2 ? "🥉" : String(i+1).padStart(2,"0")}</td>
                  <td style={{ fontWeight: 600 }}>{b.name}</td>
                  <td className="mono" style={{ textAlign: "right" }}>R$ {(b.rev * mult / 1000).toFixed(0)}k</td>
                  <td className="mono" style={{ textAlign: "right" }}>{(b.margin*100).toFixed(1)}%</td>
                  <td className="mono" style={{ textAlign: "right", color: b.growth >= 0 ? "#0F7F50" : "#C2282B" }}>{b.growth >= 0 ? "+" : ""}{(b.growth*100).toFixed(1)}%</td>
                  <td className="mono" style={{ textAlign: "right" }}>{((b.rev / totalRev) * 100).toFixed(1)}%</td>
                </tr>
              ))}
            </tbody>
          </table>
        </>
      );
    }
    if (scope === "sectors") {
      return (
        <>
          <div className="pp-section-title">Setores por faturamento · {currentPeriod.label}</div>
          <table className="pp-table">
            <thead><tr><th style={{ width: 30 }}>#</th><th>Setor</th><th style={{ textAlign: "right" }}>Faturamento</th><th style={{ textAlign: "right" }}>Margem</th><th style={{ textAlign: "right" }}>Crescimento</th></tr></thead>
            <tbody>
              {[...M.SECTORS].sort((a, b) => b.rev - a.rev).map((s, i) => (
                <tr key={s.name}>
                  <td>{String(i+1).padStart(2,"0")}</td>
                  <td style={{ fontWeight: 600 }}><span style={{ display: "inline-block", width: 8, height: 8, borderRadius: 4, background: s.color, marginRight: 6 }}/>{s.name}</td>
                  <td className="mono" style={{ textAlign: "right" }}>R$ {(s.rev * mult / 1000).toFixed(0)}k</td>
                  <td className="mono" style={{ textAlign: "right" }}>{(s.margin*100).toFixed(1)}%</td>
                  <td className="mono" style={{ textAlign: "right", color: s.growth >= 0 ? "#0F7F50" : "#C2282B" }}>{s.growth >= 0 ? "+" : ""}{(s.growth*100).toFixed(1)}%</td>
                </tr>
              ))}
            </tbody>
          </table>
        </>
      );
    }
    if (scope === "sellers") {
      return (
        <>
          <div className="pp-section-title">Ranking de vendedores · {currentPeriod.label}</div>
          <table className="pp-table">
            <thead><tr><th style={{ width: 30 }}>#</th><th>Vendedor</th><th style={{ textAlign: "right" }}>Faturamento</th><th style={{ textAlign: "right" }}>Pedidos</th><th style={{ textAlign: "right" }}>Ticket médio</th><th style={{ textAlign: "right" }}>Crescimento</th></tr></thead>
            <tbody>
              {M.SELLERS.map((s, i) => (
                <tr key={s.id}>
                  <td>{String(i+1).padStart(2,"0")}</td>
                  <td style={{ fontWeight: 600 }}>{s.name}</td>
                  <td className="mono" style={{ textAlign: "right" }}>R$ {(s.rev * mult / 1000).toFixed(0)}k</td>
                  <td className="mono" style={{ textAlign: "right" }}>{Math.round(s.deals * mult)}</td>
                  <td className="mono" style={{ textAlign: "right" }}>R$ {s.ticket.toLocaleString("pt-BR")}</td>
                  <td className="mono" style={{ textAlign: "right", color: s.growth >= 0 ? "#0F7F50" : "#C2282B" }}>{s.growth >= 0 ? "+" : ""}{(s.growth*100).toFixed(1)}%</td>
                </tr>
              ))}
            </tbody>
          </table>
        </>
      );
    }
    if (scope === "inactive") {
      const inactive180 = M.CUSTOMERS.filter(c => c.daysInactive >= 180).sort((a, b) => b.ltv - a.ltv).slice(0, 15);
      return (
        <>
          <div className="pp-section-title">Top 15 clientes inativos por LTV · ≥180 dias</div>
          <table className="pp-table">
            <thead><tr><th>Cliente</th><th>Vendedor</th><th style={{ textAlign: "right" }}>LTV</th><th style={{ textAlign: "right" }}>Pedidos</th><th style={{ textAlign: "right" }}>Dias inativo</th></tr></thead>
            <tbody>
              {inactive180.map(c => (
                <tr key={c.id}>
                  <td style={{ fontWeight: 600 }}>{c.name}</td>
                  <td>{c.seller}</td>
                  <td className="mono" style={{ textAlign: "right" }}>R$ {(c.ltv / 1000).toFixed(0)}k</td>
                  <td className="mono" style={{ textAlign: "right" }}>{c.totalOrders}</td>
                  <td className="mono" style={{ textAlign: "right", color: "#C2282B" }}>{c.daysInactive}d</td>
                </tr>
              ))}
            </tbody>
          </table>
        </>
      );
    }
    if (scope === "recurring") {
      const recurring = M.CUSTOMERS.filter(c => c.totalOrders > 1).sort((a, b) => b.ltv - a.ltv).slice(0, 15);
      return (
        <>
          <div className="pp-section-title">Top 15 clientes recorrentes por LTV</div>
          <table className="pp-table">
            <thead><tr><th>Cliente</th><th>Vendedor</th><th style={{ textAlign: "right" }}>LTV</th><th style={{ textAlign: "right" }}>Pedidos</th><th style={{ textAlign: "right" }}>Ticket médio</th></tr></thead>
            <tbody>
              {recurring.map(c => (
                <tr key={c.id}>
                  <td style={{ fontWeight: 600 }}>{c.name}</td>
                  <td>{c.seller}</td>
                  <td className="mono" style={{ textAlign: "right" }}>R$ {(c.ltv / 1000).toFixed(0)}k</td>
                  <td className="mono" style={{ textAlign: "right" }}>{c.totalOrders}</td>
                  <td className="mono" style={{ textAlign: "right" }}>R$ {c.avgTicket.toLocaleString("pt-BR")}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </>
      );
    }
    // Fallback / overview: KPIs + Top 5 marcas + Top 5 vendedores
    return (
      <>
        <div className="pp-kpi-grid">
          <div className="pp-kpi-card">
            <div className="pp-kpi-label">FATURAMENTO</div>
            <div className="pp-kpi-value" style={{ color: "#203090" }}>R$ {(ytd26 / 1_000_000).toFixed(1).replace(".", ",")}M</div>
            {filters.compareYoY && ytd25 > 0 && (
              <div className="pp-kpi-delta up">↑ +{((ytd26/ytd25 - 1) * 100).toFixed(1).replace(".", ",")}% vs {M.NOW.prevYear}</div>
            )}
          </div>
          <div className="pp-kpi-card">
            <div className="pp-kpi-label">TICKET MÉDIO</div>
            <div className="pp-kpi-value">R$ {Math.round(blendedTicket).toLocaleString("pt-BR")}</div>
            {filters.compareYoY && <div className="pp-kpi-delta up">↑ +6,4%</div>}
          </div>
          <div className="pp-kpi-card">
            <div className="pp-kpi-label">NEGÓCIOS</div>
            <div className="pp-kpi-value">{totalDeals.toLocaleString("pt-BR")}</div>
            <div className="pp-kpi-delta muted">pedidos no período</div>
          </div>
          <div className="pp-kpi-card">
            <div className="pp-kpi-label">MARGEM MÉDIA</div>
            <div className="pp-kpi-value">32,9%</div>
            {filters.compareYoY && <div className="pp-kpi-delta up">↑ +1,8 pp</div>}
          </div>
        </div>

        <div className="pp-section-title">Top 5 marcas no período</div>
        <table className="pp-table">
          <thead><tr><th style={{ width: 40 }}>#</th><th>Marca</th><th style={{ textAlign: "right" }}>Faturamento</th><th style={{ textAlign: "right" }}>Margem</th><th style={{ textAlign: "right" }}>Crescimento</th></tr></thead>
          <tbody>
            {[...M.BRANDS].sort((a,b) => b.rev - a.rev).slice(0, 5).map((b, i) => (
              <tr key={b.name}>
                <td>{i === 0 ? "🥇" : i === 1 ? "🥈" : i === 2 ? "🥉" : String(i+1).padStart(2,"0")}</td>
                <td style={{ fontWeight: 600 }}>{b.name}</td>
                <td className="mono" style={{ textAlign: "right" }}>R$ {(b.rev * mult / 1000).toFixed(0)}k</td>
                <td className="mono" style={{ textAlign: "right" }}>{(b.margin*100).toFixed(1)}%</td>
                <td className="mono" style={{ textAlign: "right", color: b.growth >= 0 ? "#0F7F50" : "#C2282B" }}>
                  {b.growth >= 0 ? "+" : ""}{(b.growth*100).toFixed(1)}%
                </td>
              </tr>
            ))}
          </tbody>
        </table>

        <div className="pp-section-title">Top 5 vendedores no período</div>
        <table className="pp-table">
          <thead><tr><th style={{ width: 40 }}>#</th><th>Vendedor</th><th style={{ textAlign: "right" }}>Faturamento</th><th style={{ textAlign: "right" }}>Pedidos</th><th style={{ textAlign: "right" }}>Ticket médio</th></tr></thead>
          <tbody>
            {M.SELLERS.slice(0, 5).map((s, i) => (
              <tr key={s.id}>
                <td>{String(i+1).padStart(2,"0")}</td>
                <td style={{ fontWeight: 600 }}>{s.name}</td>
                <td className="mono" style={{ textAlign: "right" }}>R$ {(s.rev * mult / 1000).toFixed(0)}k</td>
                <td className="mono" style={{ textAlign: "right" }}>{Math.round(s.deals * mult)}</td>
                <td className="mono" style={{ textAlign: "right" }}>R$ {s.ticket.toLocaleString("pt-BR")}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </>
    );
  }

  return (
    <div className="print-preview-overlay" onClick={handleClose}>
      <div className="print-preview-shell" onClick={e => e.stopPropagation()}>
        <div className="print-preview-head">
          <div>
            <div className="print-preview-eyebrow">📄 Pré-visualização do PDF</div>
            <div className="print-preview-title">{meta.title} · {currentPeriod.label}</div>
            <div className="muted" style={{ fontSize: 12 }}>
              {meta.subtitle} · Confira antes de gerar.
            </div>
          </div>
          <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
            {confirmed && (
              <span style={{
                background: "rgba(15,127,80,0.12)",
                color: "var(--success)",
                fontSize: 12,
                fontWeight: 700,
                padding: "6px 12px",
                borderRadius: 6,
              }}>
                ✓ PDF gerado · download iniciado
              </span>
            )}
            <button className="btn btn-ghost btn-sm" onClick={handleClose}>Fechar</button>
            <button className="btn btn-primary btn-sm" onClick={handleConfirm} disabled={confirmed}>
              <Icon name="printer" size={12}/> {confirmed ? "Gerando..." : "Gerar PDF"}
            </button>
          </div>
        </div>

        <div className="print-preview-paper">
          {/* Página simulada A4 */}
          <div className="pp-page">
            <div className="pp-page-header">
              <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
                <img src="/mockup/assets/cefeq-logo.png" alt="CEFEQ" style={{ height: 56, width: "auto", objectFit: "contain" }}/>
                <div>
                  <div style={{ fontSize: 16, fontWeight: 800, color: "#203090" }}>CEFEQ Ferramentas</div>
                  <div style={{ fontSize: 10, fontStyle: "italic", color: "#203090", fontWeight: 600, marginTop: 2 }}>
                    Equipando Quem Constrói o Futuro!
                  </div>
                  <div style={{ fontSize: 10, color: "#666", marginTop: 3 }}>Relatório · {meta.title}</div>
                </div>
              </div>
              <div style={{ textAlign: "right", fontSize: 11, color: "#666" }}>
                <div>Gerado em {new Date().toLocaleDateString("pt-BR", { day: "2-digit", month: "long", year: "numeric" })}</div>
                <div>Por {(M.currentUser && M.currentUser.name) || "Felipe Sergio"}</div>
              </div>
            </div>

            <div className="pp-title-block">
              <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: "0.12em", color: "#999" }}>
                PERÍODO ANALISADO
              </div>
              <div style={{ fontSize: 22, fontWeight: 700, color: "#1a1a1a", marginTop: 2 }}>
                {currentPeriod.label}
              </div>
              <div style={{ fontSize: 13, color: "#666", marginTop: 2 }}>
                {currentPeriod.range} · {storesLabel}
              </div>
            </div>

            {renderScopeContent()}

            <div className="pp-footer">
              <div>CEFEQ Ferramentas · Confidencial</div>
              <div>{meta.title} · Gerado pelo Painel BI · Grupo DashM</div>
            </div>
          </div>
        </div>

        <div className="print-preview-foot">
          <div className="muted" style={{ fontSize: 11 }}>
            💡 PDF reflete a tela atual ({meta.title.toLowerCase()}) + filtros aplicados.
          </div>
        </div>
      </div>
    </div>
  );
}

window.PrintPreviewModal = PrintPreviewModal;

// ─────────────────────────────────────────────────────────────────────────────
// SearchHelpModal — busca rápida com lista de exemplos do que pode ser buscado
// ─────────────────────────────────────────────────────────────────────────────
const SEARCH_HELP_STATE = { open: false };
window.openSearchHelp = function() {
  SEARCH_HELP_STATE.open = true;
  window.MOCK._filterListeners.forEach(fn => fn());
};
window.closeSearchHelp = function() {
  SEARCH_HELP_STATE.open = false;
  window.MOCK._filterListeners.forEach(fn => fn());
};

function SearchHelpModal() {
  window.useActiveFilters();
  const [query, setQuery] = useStateE("");
  const [selectedCustomer, setSelectedCustomer] = useStateE(null);

  useEffectE(() => {
    function onKey(e) {
      if (e.shiftKey && (e.key === "K" || e.key === "k") && !SEARCH_HELP_STATE.open) {
        if (document.activeElement && ["INPUT","TEXTAREA"].includes(document.activeElement.tagName)) return;
        e.preventDefault();
        window.openSearchHelp();
      }
      if (e.key === "Escape" && SEARCH_HELP_STATE.open) {
        window.closeSearchHelp();
      }
    }
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, []);

  if (!SEARCH_HELP_STATE.open) return null;

  const M = window.MOCK;
  const q = query.trim().toLowerCase();

  // Quando o user digita algo, busca de verdade nos dados mockados
  const results = q.length >= 2 ? {
    clientes: M.CUSTOMERS.filter(c =>
      c.name.toLowerCase().includes(q) || (c.cnpj && c.cnpj.includes(q))
    ).slice(0, 5),
    marcas: M.BRANDS.filter(b => b.name.toLowerCase().includes(q)).slice(0, 5),
    produtos: (M.PRODUCTS || []).filter(p =>
      p.name.toLowerCase().includes(q) || (p.sku && p.sku.toLowerCase().includes(q))
    ).slice(0, 5),
    vendedores: M.SELLERS.filter(s => s.name.toLowerCase().includes(q)).slice(0, 5),
    lojas: M.STORES.filter(s => s.name.toLowerCase().includes(q)).slice(0, 3),
  } : null;

  const hasResults = results && (
    results.clientes.length || results.marcas.length || results.produtos.length ||
    results.vendedores.length || results.lojas.length
  );

  const examples = [
    { category: "Clientes",   items: ["Construções Aurora", "Hidro Princesa dos Campos", "Empreiteira"], hint: "busca por nome ou CNPJ" },
    { category: "Marcas",     items: ["Bosch", "Makita", "Vonder", "Kärcher"], hint: "vai pro detalhe da marca" },
    { category: "Produtos",   items: ["Furadeira", "Bosch GSB", "BSH-0601217603 (SKU)"], hint: "busca por nome ou código" },
    { category: "Vendedores", items: ["Anderson", "Beatriz Moraes", "Daniela"], hint: "performance individual" },
    { category: "Comandos",   items: ["/dre", "/fluxo de caixa", "/fechamento"], hint: "atalho de navegação" },
  ];

  return (
    <div className="search-overlay" onClick={() => window.closeSearchHelp()}>
      <div className="search-shell" onClick={e => e.stopPropagation()}>
        <div className="search-input-wrap">
          <Icon name="search" size={16}/>
          <input
            type="text"
            autoFocus
            placeholder="Busque clientes, marcas, produtos, vendedores, lojas, comandos…"
            value={query}
            onChange={(e) => setQuery(e.target.value)}
          />
          {query && (
            <button
              type="button"
              className="search-clear"
              onClick={() => setQuery("")}
              title="Limpar busca (Esc também limpa)"
              aria-label="Limpar busca"
            >
              <Icon name="close" size={14}/>
            </button>
          )}
          <span className="kbd">Esc</span>
        </div>

        <div className="search-body">
          {/* SE TEM QUERY → mostra resultados */}
          {q.length >= 2 && (
            <>
              <div className="muted" style={{ fontSize: 11, fontWeight: 700, letterSpacing: "0.08em", marginBottom: 6 }}>
                RESULTADOS PARA "{query}"
              </div>

              {!hasResults && (
                <div style={{ padding: 16, textAlign: "center", color: "var(--text-muted)", fontSize: 12 }}>
                  Nenhum resultado encontrado. Tente um nome de cliente, marca, SKU ou comando com <code>/</code>.
                </div>
              )}

              {results.clientes.length > 0 && (
                <div className="search-results-group">
                  <div className="search-results-head">
                    <Icon name="user" size={12}/> Clientes ({results.clientes.length})
                  </div>
                  {results.clientes.map(c => (
                    <button key={c.id} type="button" className="search-result-row" onClick={() => setSelectedCustomer(c)}>
                      <div>
                        <div style={{ fontWeight: 600 }}>{c.name}</div>
                        <div className="muted mono" style={{ fontSize: 10 }}>{c.cnpj} · {c.sector || "—"}</div>
                      </div>
                      <div style={{ textAlign: "right" }}>
                        <div className="mono" style={{ fontWeight: 700, fontSize: 12 }}>{fmtBRLshort(c.ltv)}</div>
                        <div className="muted" style={{ fontSize: 10 }}>{c.totalOrders} pedidos · {c.daysInactive}d</div>
                      </div>
                    </button>
                  ))}
                </div>
              )}

              {results.marcas.length > 0 && (
                <div className="search-results-group">
                  <div className="search-results-head">
                    <Icon name="brands" size={12}/> Marcas ({results.marcas.length})
                  </div>
                  {results.marcas.map(b => (
                    <button key={b.name} type="button" className="search-result-row" onClick={() => { window.closeSearchHelp(); }}>
                      <div>
                        <div style={{ fontWeight: 600 }}>{b.name}</div>
                        <div className="muted" style={{ fontSize: 10 }}>{b.items} SKUs · margem {(b.margin*100).toFixed(0)}%</div>
                      </div>
                      <div style={{ textAlign: "right" }}>
                        <div className="mono" style={{ fontWeight: 700, fontSize: 12 }}>{fmtBRLshort(b.rev)}</div>
                        <div className={`mini-delta ${b.growth >= 0 ? "up" : "down"}`} style={{ fontSize: 10 }}>{(b.growth*100).toFixed(1).replace(".",",")}%</div>
                      </div>
                    </button>
                  ))}
                </div>
              )}

              {results.produtos.length > 0 && (
                <div className="search-results-group">
                  <div className="search-results-head">
                    <Icon name="overview" size={12}/> Produtos ({results.produtos.length})
                  </div>
                  {results.produtos.map(p => (
                    <button key={p.sku} type="button" className="search-result-row" onClick={() => { window.closeSearchHelp(); }}>
                      <div>
                        <div style={{ fontWeight: 600 }}>{p.name}</div>
                        <div className="muted mono" style={{ fontSize: 10 }}>{p.sku} · {p.brand} · {p.category}</div>
                      </div>
                      <div style={{ textAlign: "right" }}>
                        <div className="mono" style={{ fontWeight: 700, fontSize: 12 }}>{fmtBRLshort(p.rev)}</div>
                        <div className="muted mono" style={{ fontSize: 10 }}>{p.units} unid.</div>
                      </div>
                    </button>
                  ))}
                </div>
              )}

              {results.vendedores.length > 0 && (
                <div className="search-results-group">
                  <div className="search-results-head">
                    <Icon name="sellers" size={12}/> Vendedores ({results.vendedores.length})
                  </div>
                  {results.vendedores.map(s => (
                    <button key={s.id} type="button" className="search-result-row" onClick={() => { window.closeSearchHelp(); }}>
                      <div>
                        <div style={{ fontWeight: 600 }}>{s.name}</div>
                        <div className="muted" style={{ fontSize: 10 }}>{s.channel} · ticket {fmtBRL(s.ticket)}</div>
                      </div>
                      <div style={{ textAlign: "right" }}>
                        <div className="mono" style={{ fontWeight: 700, fontSize: 12 }}>{fmtBRLshort(s.rev)}</div>
                        <div className={`mini-delta ${s.growth >= 0 ? "up" : "down"}`} style={{ fontSize: 10 }}>{(s.growth*100).toFixed(1).replace(".",",")}%</div>
                      </div>
                    </button>
                  ))}
                </div>
              )}

              {results.lojas.length > 0 && (
                <div className="search-results-group">
                  <div className="search-results-head">
                    <Icon name="brands" size={12}/> Lojas ({results.lojas.length})
                  </div>
                  {results.lojas.map(s => (
                    <button key={s.id} type="button" className="search-result-row" onClick={() => { window.closeSearchHelp(); }}>
                      <div>
                        <div style={{ fontWeight: 600 }}>{s.name}</div>
                        <div className="muted" style={{ fontSize: 10 }}>{s.address} · gerente {s.manager}</div>
                      </div>
                      <div style={{ textAlign: "right" }}>
                        <div className="mono" style={{ fontWeight: 700, fontSize: 12 }}>{fmtBRLshort(s.rev)}</div>
                        <div className="muted" style={{ fontSize: 10 }}>{s.orders} pedidos</div>
                      </div>
                    </button>
                  ))}
                </div>
              )}
            </>
          )}

          {/* SE NÃO TEM QUERY → mostra exemplos do que pode buscar */}
          {q.length < 2 && (
            <>
              <div className="search-hint">
                <strong>Atalho:</strong> pressione <span className="kbd">Shift</span> + <span className="kbd">K</span> em qualquer tela pra abrir a busca.
              </div>

              <div className="muted" style={{ fontSize: 11, fontWeight: 700, letterSpacing: "0.08em", marginTop: 14, marginBottom: 6 }}>
                EXEMPLOS DO QUE VOCÊ PODE BUSCAR
              </div>

              {examples.map(g => (
                <div key={g.category} className="search-group">
                  <div className="search-group-head">
                    {g.category}
                    <span className="muted" style={{ fontWeight: 400, marginLeft: 8, fontSize: 10 }}>· {g.hint}</span>
                  </div>
                  <div className="search-suggestions">
                    {g.items.map(item => (
                      <button
                        key={item}
                        type="button"
                        className="search-suggestion"
                        onClick={() => setQuery(item.replace(" (SKU)", ""))}
                      >
                        {item}
                      </button>
                    ))}
                  </div>
                </div>
              ))}

              <div className="muted" style={{ fontSize: 11, marginTop: 14, padding: 10, background: "var(--surface-alt)", borderRadius: 6 }}>
                💡 Comece a digitar pra ver resultados reais dos seus dados — busca por nome, CNPJ, SKU, código de pedido ou navegação por comando com <code>/</code>.
              </div>
            </>
          )}
        </div>
      </div>

      {/* Modal de detalhe do cliente quando clica no resultado */}
      {selectedCustomer && (
        <CustomerDetailModal
          customer={selectedCustomer}
          onClose={() => setSelectedCustomer(null)}
        />
      )}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// CustomerDetailModal — abre da busca, mostra visão consolidada do cliente
// ─────────────────────────────────────────────────────────────────────────────
function CustomerDetailModal({ customer, onClose }) {
  const M = window.MOCK;
  const c = customer;
  if (!c) return null;

  // Ação sugerida baseada em LTV/recência (mesma engine de Inativos/Recorrentes)
  let suggest;
  if (c.daysInactive >= 90) {
    suggest = c.ltv >= 80_000
      ? { emoji: "🚨", label: "Visita presencial", desc: `Cliente VIP com LTV ${fmtBRLshort(c.ltv)} sumido há ${c.daysInactive} dias`, color: "var(--danger)" }
      : { emoji: "📞", label: "Ligar", desc: `${c.daysInactive} dias sem pedido — entender o motivo`, color: "var(--warn)" };
  } else if (c.totalOrders >= 20 && c.daysInactive >= 10 && c.daysInactive <= 30) {
    suggest = { emoji: "📞", label: "Antecipar pedido", desc: `Compra a cada ~${Math.round(365/c.totalOrders)}d · janela ideal pra próximo contato`, color: "var(--cefeq-blue)" };
  } else if (c.avgTicket >= 5_000 && c.totalOrders >= 5) {
    suggest = { emoji: "📈", label: "Upsell premium", desc: "Ticket alto · oferecer linha premium / contrato PJ", color: "var(--success)" };
  } else {
    suggest = { emoji: "✓", label: "Acompanhar", desc: "Carteira saudável · check periódico", color: "var(--text-soft)" };
  }

  // Histórico simulado de pedidos (5 últimos)
  const orderHistory = Array.from({ length: Math.min(5, c.totalOrders) }, (_, i) => ({
    id: `${c.id.slice(1)}-${String(c.totalOrders - i).padStart(3, "0")}`,
    days: c.daysInactive + i * 18,
    value: Math.round(c.avgTicket * (0.85 + (i % 3) * 0.1)),
  }));

  return (
    <div className="cust-detail-overlay" onClick={onClose}>
      <div className="cust-detail-shell" onClick={e => e.stopPropagation()}>
        <div className="cust-detail-head">
          <div>
            <div className="cust-detail-eyebrow">DETALHE DO CLIENTE · {c.sector || "Diversos"}</div>
            <div className="cust-detail-title">{c.name}</div>
            <div className="muted mono" style={{ fontSize: 12, marginTop: 4 }}>{c.cnpj}</div>
          </div>
          <button className="icon-btn" onClick={onClose} title="Fechar (Esc)">
            <Icon name="close" size={16}/>
          </button>
        </div>

        <div className="cust-detail-body">
          {/* KPIs consolidados */}
          <div className="cust-kpi-grid">
            <div className="cust-kpi">
              <div className="cust-kpi-label">LTV total</div>
              <div className="cust-kpi-value" style={{ color: "var(--cefeq-blue)" }}>{fmtBRL(c.ltv)}</div>
            </div>
            <div className="cust-kpi">
              <div className="cust-kpi-label">Pedidos</div>
              <div className="cust-kpi-value">{c.totalOrders}</div>
            </div>
            <div className="cust-kpi">
              <div className="cust-kpi-label">Ticket médio</div>
              <div className="cust-kpi-value mono">{fmtBRL(c.avgTicket)}</div>
            </div>
            <div className="cust-kpi">
              <div className="cust-kpi-label">Última compra</div>
              <div className="cust-kpi-value" style={{ fontSize: 18 }}>{c.daysInactive} dias</div>
            </div>
          </div>

          {/* Ação sugerida */}
          <div className="cust-detail-block" style={{ borderLeft: `4px solid ${suggest.color}` }}>
            <div className="cust-detail-label">💡 Ação sugerida</div>
            <div style={{ display: "flex", alignItems: "center", gap: 10, marginTop: 6 }}>
              <span style={{ fontSize: 22 }}>{suggest.emoji}</span>
              <div>
                <div style={{ fontWeight: 700, fontSize: 14 }}>{suggest.label}</div>
                <div className="muted" style={{ fontSize: 12, marginTop: 2 }}>{suggest.desc}</div>
              </div>
            </div>
          </div>

          {/* Dados de contato/relacionamento */}
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
            <div className="cust-detail-block">
              <div className="cust-detail-label">Vendedor responsável</div>
              <div style={{ fontWeight: 600, marginTop: 4 }}>{c.seller}</div>
            </div>
            <div className="cust-detail-block">
              <div className="cust-detail-label">Setor</div>
              <div style={{ fontWeight: 600, marginTop: 4 }}>{c.sector || "—"}</div>
            </div>
            <div className="cust-detail-block">
              <div className="cust-detail-label">Canal habitual</div>
              <div style={{ fontWeight: 600, marginTop: 4 }}>{c.channel || "—"}</div>
            </div>
            <div className="cust-detail-block">
              <div className="cust-detail-label">Frequência média</div>
              <div style={{ fontWeight: 600, marginTop: 4 }}>
                {c.totalOrders > 0 ? `~${Math.round(365/c.totalOrders)} dias entre pedidos` : "Sem histórico"}
              </div>
            </div>
          </div>

          {/* Histórico de pedidos */}
          <div>
            <div className="cust-detail-label" style={{ marginBottom: 8 }}>Histórico recente (simulado)</div>
            <div className="cust-history">
              {orderHistory.map((o, i) => (
                <div key={i} className="cust-history-row">
                  <div className="mono" style={{ fontSize: 11, color: "var(--text-muted)" }}>#{o.id}</div>
                  <div style={{ fontSize: 12 }}>{o.days} dias atrás</div>
                  <div className="mono" style={{ fontWeight: 700, textAlign: "right" }}>{fmtBRL(o.value)}</div>
                </div>
              ))}
            </div>
          </div>
        </div>

        <div className="cust-detail-foot">
          <button className="btn btn-ghost btn-sm" onClick={onClose}>Fechar</button>
          <button className="btn btn-outline btn-sm">
            <Icon name="user" size={12}/> Ver ficha completa
          </button>
          <button className="btn btn-primary btn-sm">
            <Icon name="whatsapp" size={12}/> Abrir WhatsApp
          </button>
        </div>
      </div>
    </div>
  );
}

window.CustomerDetailModal = CustomerDetailModal;
window.SearchHelpModal = SearchHelpModal;
// ─────────────────────────────────────────────────────────────────────────────
function StoresTab() {
  const M = window.MOCK;
  const [selected, setSelected] = useStateE(null);
  const [editing, setEditing] = useStateE(null);
  const [createOpen, setCreateOpen] = useStateE(false);
  const [toastNode, showToast] = useToast();

  const totalRev = M.STORES.reduce((s, st) => s + st.rev, 0);
  const activeStores = M.STORES.filter(s => s.status === "ativa").length;
  const totalSqm = M.STORES.reduce((s, st) => s + st.sqm, 0);
  const totalSellers = M.STORES.reduce((s, st) => s + st.sellers, 0);

  const typeIcon = (type) => {
    if (type === "Matriz") return "brands";
    if (type === "Filial") return "brands";
    if (type === "E-commerce") return "recurring";
    return "sectors";
  };

  return (
    <>
      <div className="kpi-grid kpi-4">
        <KPI label="Unidades ativas" value={`${activeStores}/${M.STORES.length}`} sub="1 em construção" />
        <KPI label="Faturamento consolidado" value={fmtBRLshort(totalRev)} delta={0.224} />
        <KPI label="Área total · loja física" value={`${fmtInt(totalSqm)} m²`} sub="5 unidades físicas" />
        <KPI label="Vendedores alocados" value={totalSellers} sub="distribuídos nas unidades" accent="var(--cefeq-blue)" />
      </div>

      <div className="stores-actions">
        <div className="muted">{M.STORES.length} unidades no total · {activeStores} operando</div>
        <button className="btn btn-primary" onClick={() => setCreateOpen(true)}>
          <Icon name="plus" size={14}/> Nova unidade
        </button>
      </div>

      <div className="stores-grid">
        {M.STORES.map(s => (
          <div key={s.id} className={`store-card ${s.status === "construcao" ? "construcao" : ""}`}>
            <div className="store-card-head">
              <div className="store-icon"><Icon name={typeIcon(s.type)} size={18}/></div>
              <div style={{ flex: 1 }}>
                <div className="store-name">{s.name}</div>
                <div className="store-addr">{s.address}</div>
              </div>
              <Pill variant={s.status === "ativa" ? "success" : "warn"}>
                {s.status === "ativa" ? "Ativa" : "Em obras"}
              </Pill>
            </div>
            <div className="store-tags">
              <Pill variant="blue">{s.type}</Pill>
              {s.sqm > 0 && <Pill variant="neutral">{s.sqm} m²</Pill>}
              <Pill variant="neutral">Desde {s.opened}</Pill>
            </div>
            <div className="store-stats">
              <div>
                <div className="muted">Faturamento (YTD)</div>
                <div className="store-stat mono">{s.rev > 0 ? fmtBRLshort(s.rev) : "—"}</div>
              </div>
              <div>
                <div className="muted">Ticket médio</div>
                <div className="store-stat mono">{s.ticket > 0 ? fmtBRL(s.ticket) : "—"}</div>
              </div>
              <div>
                <div className="muted">Pedidos</div>
                <div className="store-stat mono">{s.orders > 0 ? fmtInt(s.orders) : "—"}</div>
              </div>
              <div>
                <div className="muted">Vendedores</div>
                <div className="store-stat mono">{s.sellers || "—"}</div>
              </div>
            </div>
            <div className="store-foot">
              <div className="store-manager">
                <div className="avatar sm">{s.manager === "—" ? "?" : s.manager.split(" ").map(n=>n[0]).slice(0,2).join("")}</div>
                <div>
                  <div className="muted" style={{ fontSize: 10 }}>Gerente</div>
                  <div style={{ fontSize: 12, fontWeight: 600 }}>{s.manager}</div>
                </div>
              </div>
              <div style={{ display: "flex", gap: 4 }}>
                <button className="btn-mini" title="Detalhes" onClick={() => setSelected(s)}><Icon name="eye" size={13}/></button>
                <button className="btn-mini" title="Editar" onClick={() => setEditing(s)}><Icon name="settings" size={13}/></button>
              </div>
            </div>
          </div>
        ))}
      </div>

      {/* Store detail */}
      <Modal open={!!selected} onClose={() => setSelected(null)} wide
        title={selected?.name}
        subtitle={selected?.address}
        footer={<>
          <button className="btn btn-ghost" onClick={() => { setEditing(selected); setSelected(null); }}>Editar</button>
          <button className="btn btn-primary">Abrir relatório da loja</button>
        </>}>
        {selected && (
          <>
            <div className="modal-kpi-row">
              <div className="mk"><div className="muted">Faturamento</div><div className="mk-v">{selected.rev > 0 ? fmtBRL(selected.rev) : "—"}</div></div>
              <div className="mk"><div className="muted">Pedidos</div><div className="mk-v">{selected.orders > 0 ? fmtInt(selected.orders) : "—"}</div></div>
              <div className="mk"><div className="muted">Ticket médio</div><div className="mk-v">{selected.ticket > 0 ? fmtBRL(selected.ticket) : "—"}</div></div>
              <div className="mk"><div className="muted">Vendedores</div><div className="mk-v">{selected.sellers || "—"}</div></div>
            </div>
            <div className="modal-section">
              <h4>Dados da unidade</h4>
              <div className="kv-grid">
                <div><span className="muted">Tipo</span><b>{selected.type}</b></div>
                <div><span className="muted">Status</span><b>{selected.status === "ativa" ? "Ativa" : "Em construção"}</b></div>
                <div><span className="muted">Gerente</span><b>{selected.manager}</b></div>
                <div><span className="muted">Telefone</span><b>{selected.phone}</b></div>
                <div><span className="muted">Área</span><b>{selected.sqm > 0 ? `${selected.sqm} m²` : "—"}</b></div>
                <div><span className="muted">Inaugurada em</span><b>{selected.opened}</b></div>
              </div>
            </div>
          </>
        )}
      </Modal>

      {/* Edit / create */}
      <Modal open={!!editing || createOpen} onClose={() => { setEditing(null); setCreateOpen(false); }}
        title={editing ? `Editar · ${editing.name}` : "Nova unidade"}
        subtitle={editing ? "Atualize as informações da unidade" : "Cadastre uma nova loja, filial ou CD"}
        footer={<>
          <button className="btn btn-ghost" onClick={() => { setEditing(null); setCreateOpen(false); }}>Cancelar</button>
          <button className="btn btn-primary" onClick={() => {
            showToast(editing ? "Unidade atualizada" : "Unidade cadastrada");
            setEditing(null); setCreateOpen(false);
          }}>Salvar</button>
        </>}>
        <div className="invite-form">
          <label className="field"><span>Nome da unidade</span><input defaultValue={editing?.name || ""} placeholder="Ex: Filial · Cidade"/></label>
          <label className="field"><span>Endereço</span><input defaultValue={editing?.address || ""} placeholder="Rua, número, bairro, cidade/UF"/></label>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
            <label className="field"><span>Tipo</span>
              <select defaultValue={editing?.type || "Filial"}>
                <option>Matriz</option><option>Filial</option><option>E-commerce</option><option>Centro de distribuição</option>
              </select>
            </label>
            <label className="field"><span>Status</span>
              <select defaultValue={editing?.status || "ativa"}>
                <option value="ativa">Ativa</option>
                <option value="construcao">Em construção</option>
                <option value="inativa">Inativa</option>
              </select>
            </label>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
            <label className="field"><span>Gerente responsável</span>
              <select defaultValue={editing?.manager || ""}>
                <option value="">— Selecionar —</option>
                {window.MOCK.USERS.map(u => <option key={u.id}>{u.name}</option>)}
              </select>
            </label>
            <label className="field"><span>Telefone</span><input defaultValue={editing?.phone || ""} placeholder="(00) 0000-0000"/></label>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
            <label className="field"><span>Área (m²)</span><input type="number" defaultValue={editing?.sqm || ""} placeholder="0"/></label>
            <label className="field"><span>Inaugurada em</span><input defaultValue={editing?.opened || ""} placeholder="Ex: 2024"/></label>
          </div>
        </div>
      </Modal>

      {toastNode}
    </>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// MOBILE NOTIFICATIONS PANEL (inside iPhone frame, slides from top)
// ─────────────────────────────────────────────────────────────────────────────
function MobileNotifsPanel({ open, onClose, onNavigate }) {
  const items = [
    { id: 1, type: "alert",  icon: "inactive",  title: "12 clientes ultrapassaram 90 dias sem comprar",
      sub: "Distribuídos entre 4 vendedores", time: "agora", action: "inactive" },
    { id: 2, type: "goal",   icon: "overview",  title: `${window.MOCK.NOW.monthLong} bateu a meta · 108%`,
      sub: "Faturamento de R$ 2,24M contra meta de R$ 2,07M", time: "há 2h", action: "overview" },
    { id: 3, type: "growth", icon: "brands",    title: "Vonder em alta · +31% YoY",
      sub: "Oportunidade de aumentar mix com fornecedor", time: "há 4h", action: "brands" },
    { id: 4, type: "risk",   icon: "inactive",  title: "Construções Aurora · 187 dias sem compra",
      sub: "LTV R$ 142.300 em risco", time: "ontem", action: "inactive" },
    { id: 5, type: "info",   icon: "sellers",   title: `Daniela liderou e-commerce em ${window.MOCK.NOW.monthLong}`,
      sub: "Ticket médio cresceu 9% no mês", time: "ontem", action: "sellers" },
    { id: 6, type: "alert",  icon: "sectors",   title: "Hidráulica caiu 6% no trimestre",
      sub: "Reavaliar mix de produtos", time: "2 dias", action: "sectors" },
    { id: 7, type: "goal",   icon: "recurring", title: "Top 5% concentra 38% do LTV",
      sub: "Acionar plano de fidelização", time: "3 dias", action: "recurring" },
  ];

  if (!open) return null;

  return (
    <>
      <div className="m-sheet-overlay" onClick={onClose}/>
      <div className="m-notifs">
        <div className="m-notifs-head">
          <div>
            <h3 style={{ margin: 0, fontSize: 16, fontWeight: 700 }}>Notificações</h3>
            <div className="muted" style={{ fontSize: 11, marginTop: 2 }}>{items.length} sinais detectados</div>
          </div>
          <button className="m-icon-btn" onClick={onClose}><Icon name="close" size={15}/></button>
        </div>
        <div className="m-notifs-filter">
          <button className="seg-btn active">Todas</button>
          <button className="seg-btn">Alertas</button>
          <button className="seg-btn">Metas</button>
          <button className="seg-btn">Oportunidades</button>
        </div>
        <div className="m-notifs-list">
          {items.map(it => (
            <button key={it.id} className={`m-notif-row notif-${it.type}`} onClick={() => onNavigate(it.action)}>
              <div className="notif-icon"><Icon name={it.icon} size={14}/></div>
              <div className="m-notif-meta">
                <div className="m-notif-title">{it.title}</div>
                <div className="m-notif-sub">{it.sub}</div>
                <div className="m-notif-time">{it.time}</div>
              </div>
            </button>
          ))}
        </div>
        <button className="m-sheet-signout" style={{ color: "var(--text-muted)", borderColor: "var(--border)", marginTop: 8 }} onClick={onClose}>
          Marcar todas como lidas
        </button>
      </div>
    </>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// MOBILE PROFILE SHEET (bottom sheet with admin links)
// ─────────────────────────────────────────────────────────────────────────────
function MobileProfileSheet({ open, onClose, onNavigate, dark, onToggleTheme, onSwitchToDesktop }) {
  if (!open) return null;
  const items = [
    { label: "Meu perfil", icon: "user", action: null },
    { label: "Notificações", icon: "bell", action: null },
    { label: "Administração", icon: "admin", action: "admin", highlight: true },
    { label: "Imprimir PDF da tela", icon: "printer", action: () => window.print() },
    { label: dark ? "Tema claro" : "Tema escuro", icon: dark ? "sun" : "moon", action: "theme" },
    { label: "Voltar à versão desktop", icon: "overview", action: "desktop" },
  ];
  return (
    <>
      <div className="m-sheet-overlay" onClick={onClose}/>
      <div className="m-sheet">
        <div className="m-sheet-handle"/>
        <div className="m-sheet-header">
          <div className="avatar lg">FS</div>
          <div>
            <div className="m-sheet-name">Felipe Sergio</div>
            <div className="m-sheet-email">felipe.sergio@cefeq.com.br</div>
            <div className="pm-role-pill" style={{ marginTop: 6 }}>CEO</div>
          </div>
        </div>
        <div className="m-sheet-list">
          {items.map((it, i) => (
            <button key={i} className={`m-sheet-row ${it.highlight ? "highlight" : ""}`}
              onClick={() => {
                if (it.action === "theme") { onToggleTheme(); }
                else if (it.action === "desktop") { onSwitchToDesktop && onSwitchToDesktop(); onClose(); }
                else if (it.action) { onNavigate(it.action); onClose(); }
              }}>
              <div className="m-sheet-icon"><Icon name={it.icon} size={16}/></div>
              <span>{it.label}</span>
              <Icon name="chevron" size={12} style={{ marginLeft: "auto", opacity: 0.4 }}/>
            </button>
          ))}
        </div>
        <button className="m-sheet-signout" onClick={() => { onNavigate("login"); onClose(); }}>
          <Icon name="logout" size={14}/> Sair da conta
        </button>
      </div>
    </>
  );
}

Object.assign(window, {
  DREScreen, CashflowScreen, IntegrationsTab, StoresTab,
  NotificationsDrawer, BottomNav, MobileShell, MobileMoreMenu, Waterfall, CashflowChart,
  MobileProfileSheet, MobileNotifsPanel, FilterDialog,
});
