// Tela: Relatórios — gráficos e KPIs

const { useState: useRelState } = React;

const PERIODOS = {
  '30dias': { label: 'Últimos 30 dias', dias: 30, mult: 1.00, compLbl: 'vs período anterior' },
  'maio':   { label: 'Maio 2026',       dias: 30, mult: 1.00, compLbl: 'vs abril' },
  'abril':  { label: 'Abril 2026',      dias: 30, mult: 0.91, compLbl: 'vs março' },
  'q2':     { label: 'Q2 2026',         dias: 60, mult: 2.06, compLbl: 'vs Q1' },
  'ano':    { label: 'Este ano',        dias: 134, mult: 4.18, compLbl: 'vs ano anterior' },
};

const GRANULARIDADES = ['diario', 'semanal', 'mensal'];

const relHeaders = () => { const t = localStorage.getItem('ezza_token'); return { 'Content-Type':'application/json', ...(t?{'Authorization':`Bearer ${t}`}:{}) }; };

function Relatorios() {
  const [periodo, setPeriodo] = useRelState('maio');
  const [granul, setGranul] = useRelState('diario');
  const [periodOpen, setPeriodOpen] = useRelState(false);
  const [exportOpen, setExportOpen] = useRelState(false);
  const [cardMenu, setCardMenu] = useRelState(null); // { id, x, y }
  const [comparing, setComparing] = useRelState(true);
  const [realData, setRealData] = useRelState(null);

  // Busca dados reais do banco
  React.useEffect(() => {
    Promise.all([
      fetch('/api/oportunidades', { headers: relHeaders() }).then(r => r.json()).catch(() => ({})),
      fetch('/api/pipeline/leads', { headers: relHeaders() }).then(r => r.json()).catch(() => ({})),
      fetch('/api/contatos', { headers: relHeaders() }).then(r => r.json()).catch(() => ({})),
    ]).then(([ops, leads, cont]) => {
      if (ops.ok || leads.ok || cont.ok) {
        const negocios = (ops.oportunidades || []).map(o => ({
          ...o, valor: parseFloat(o.valor) || 0,
          dono: { id: o.usuario_id, nome: o.dono_nome || 'Equipe', avatar: AVATAR_URLS[(o.id || 0) % 12] },
        }));
        setRealData({
          negocios,
          leads: (leads.leads || []).map(l => ({ ...l, valor: parseFloat(l.valor) || 0 })),
          contatos: cont.contatos || [],
        });
      }
    });
  }, []);

  const p = PERIODOS[periodo];

  // Shadowing: usa dados reais se houver, senão demo. Todas as IIFEs abaixo pegam estes.
  const NEGOCIOS      = (realData && realData.negocios.length)  ? realData.negocios  : window.NEGOCIOS;
  const OPORTUNIDADES = NEGOCIOS;
  const LEADS         = (realData && realData.leads.length)     ? realData.leads     : window.LEADS;
  const CONTATOS      = (realData && realData.contatos.length)  ? realData.contatos  : window.CONTATOS;

  // KPIs calculados (com guards para cliente sem dados — evita NaN)
  const negTotal    = NEGOCIOS.reduce((s, n) => s + n.valor, 0);
  const negEsperado = NEGOCIOS.reduce((s, n) => s + n.valor * (n.prob / 100), 0);
  const negFechados = NEGOCIOS.filter(n => n.etapa === 'Fechado');
  const ticketMedio = Math.round(negTotal / Math.max(1, NEGOCIOS.length));
  const leadsGanhos = LEADS.filter(l => l.etapa === 'fechado').length;
  const convBase    = parseFloat(((leadsGanhos / Math.max(1, LEADS.length)) * 100).toFixed(1));

  const receita = Math.round(negEsperado * p.mult);
  const tk      = Math.round(ticketMedio * (0.96 + p.mult * 0.04));
  const ciclo   = Math.round(27 / (0.9 + p.mult * 0.1));
  const conv    = (convBase * p.mult / Math.max(1, p.mult)).toFixed(1);

  React.useEffect(() => {
    if (!cardMenu) return;
    const h = () => setCardMenu(null);
    window.addEventListener('click', h);
    return () => window.removeEventListener('click', h);
  }, [cardMenu]);

  return (
    <>
      <PageHead
        title={<>Relatórios <em>de desempenho</em></>}
        subtitle={`${p.label} · ${p.compLbl}`}
        right={
          <div className="row">
            <div className="rel-toggle">
              <button className={`rel-toggle-btn ${comparing ? 'rel-toggle-on' : ''}`} onClick={() => setComparing(!comparing)}>
                <div className={`switch ${comparing ? 'switch-on' : ''}`} style={{width:28, height:16}}>
                  <div className="switch-knob" style={{width:12, height:12, transform: comparing ? 'translateX(12px)' : ''}} />
                </div>
                Comparar
              </button>
            </div>

            <div className="rel-period-dd-wrap">
              <button className={`pp-tab ${periodOpen ? 'pp-tab-on' : ''}`} onClick={(e) => { e.stopPropagation(); setPeriodOpen(o => !o); }}>
                {ICN.cal} {p.label} {ICN.chevron}
              </button>
              {periodOpen && (
                <div className="rel-period-menu" onClick={(e) => e.stopPropagation()}>
                  {Object.entries(PERIODOS).map(([k, pp]) => (
                    <div key={k}
                      className={`pipe-dd-item ${k === periodo ? 'pipe-dd-item-on' : ''}`}
                      onClick={() => { setPeriodo(k); setPeriodOpen(false); }}>
                      <span>{pp.label}</span>
                      {k === periodo && <span className="pipe-dd-check">{ICN.check}</span>}
                    </div>
                  ))}
                </div>
              )}
            </div>

            <button className="btn-primary" onClick={() => setExportOpen(true)}>
              {ICN.upload} Exportar
            </button>
          </div>
        }
      />

      <div className="rep-stats">
        <RepStat l="Receita realizada" v={`R$ ${(receita/1e6).toFixed(2).replace('.', ',')}M`} d={`+${(11.3 * p.mult).toFixed(1)}%`} c="blue" comp={comparing} compLbl={p.compLbl}/>
        <RepStat l="Ticket médio"      v={`R$ ${tk.toLocaleString('pt-BR')}`}                  d="+4,1%"  c="yellow" comp={comparing} compLbl={p.compLbl}/>
        <RepStat l="Ciclo de venda"    v={`${ciclo} dias`}                                     d={`-${Math.round(2 / Math.max(0.5, p.mult))} dias`}  c="mint" comp={comparing} compLbl={p.compLbl}/>
        <RepStat l="Taxa de conversão" v={`${conv}%`}                                          d="+5,8pp" c="pink" comp={comparing} compLbl={p.compLbl}/>
      </div>

      <div className="rep-grid">
        <div className="card">
          <div className="card-head">
            <div className="card-title">Receita ao longo {granul === 'diario' ? 'do mês' : granul === 'semanal' ? 'das semanas' : 'dos meses'}</div>
            <div className="row">
              <div className="rel-seg">
                {GRANULARIDADES.map(g => (
                  <button key={g} className={`rel-seg-btn ${granul === g ? 'rel-seg-on' : ''}`} onClick={() => setGranul(g)}>
                    {g === 'diario' ? 'Diário' : g === 'semanal' ? 'Semanal' : 'Mensal'}
                  </button>
                ))}
              </div>
              <CardMenu id="chart" onOpen={setCardMenu} active={cardMenu?.id === 'chart'} />
            </div>
          </div>
          <AreaChart granul={granul} mult={p.mult} comparing={comparing} />
          {comparing && (
            <div className="chart-legend">
              <span className="chart-legend-item">
                <span className="chart-legend-line chart-legend-now" />
                Período atual
              </span>
              <span className="chart-legend-item">
                <span className="chart-legend-line chart-legend-prev" />
                Período anterior
              </span>
            </div>
          )}
        </div>

        <div className="card">
          <div className="card-head">
            <div className="card-title">Origem dos negócios</div>
            <CardMenu id="origem" onOpen={setCardMenu} active={cardMenu?.id === 'origem'} />
          </div>
          <Donut />
          <div className="donut-legend">
            {(() => {
              const CORES = ['blue','yellow','pink','mint'];
              const GRUPOS = { 'Indicação': 'Indicação', 'Meta Ads': 'Meta Ads / Ads', 'Site': 'Site & Inbound', 'LinkedIn': 'LinkedIn', 'Evento': 'Eventos' };
              const counts = {};
              LEADS.forEach(l => {
                const k = GRUPOS[l.origem] || l.origem;
                counts[k] = (counts[k] || 0) + 1;
              });
              const total = LEADS.length;
              return Object.entries(counts)
                .sort((a,b) => b[1] - a[1])
                .slice(0, 4)
                .map(([l, n], i) => ({ l, v: Math.round(n / total * 100), c: CORES[i] }));
            })().map((it,i) => (
              <div key={i} className="leg-row">
                <span className={`leg-sw leg-${it.c}`} />
                <span style={{fontSize: 12.5, flex:1}}>{it.l}</span>
                <span style={{fontSize: 12.5, fontWeight: 600}}>{it.v}%</span>
              </div>
            ))}
          </div>
        </div>
      </div>

      <div className="rep-grid-2">
        <div className="card">
          <div className="card-head">
            <div className="card-title">Top contas por receita</div>
            <CardMenu id="top" onOpen={setCardMenu} active={cardMenu?.id === 'top'} />
          </div>
          <div className="col" style={{gap: 12}}>
            {[...NEGOCIOS]
              .sort((a,b) => b.valor - a.valor)
              .slice(0, 5)
              .map((n, i, arr) => ({
                c: n.conta,
                v: Math.round(n.valor * p.mult),
                p: Math.round((n.valor / Math.max(1, arr[0].valor)) * 100),
                who: (n.dono && n.dono.avatar) ? null : i,
                avatar: n.dono && n.dono.avatar,
              }))
            .map((r,i) => (
              <div key={i} className="row" style={{gap: 12, padding: '4px 0'}}>
                <img src={r.avatar || AVATAR_URLS[(r.who || 0) % 12]} style={{width: 32, height: 32, borderRadius: '50%'}} alt="" />
                <div className="col" style={{flex: 1, minWidth: 0}}>
                  <div style={{fontSize: 13, fontWeight: 600}}>{r.c}</div>
                  <div style={{height: 6, background: 'oklch(0.94 0.01 250)', borderRadius: 99, marginTop: 6, overflow:'hidden'}}>
                    <div style={{width: `${r.p}%`, height: '100%', background: `linear-gradient(90deg, var(--acc-blue), var(--acc-lav))`}} />
                  </div>
                </div>
                <div className="money" style={{fontWeight: 600, fontSize: 13}}>R$ {(r.v/1000).toFixed(0)}k</div>
              </div>
            ))}
          </div>
        </div>

        <div className="card">
          <div className="card-head">
            <div className="card-title">Desempenho da equipe</div>
            <CardMenu id="time" onOpen={setCardMenu} active={cardMenu?.id === 'time'} />
          </div>
          <div className="col" style={{gap: 10}}>
            {(() => {
              // Agrupa OPORTUNIDADES por dono, soma valor e conta deals
              const byDono = {};
              OPORTUNIDADES.forEach(n => {
                const key = n.dono.id;
                if (!byDono[key]) byDono[key] = { dono: n.dono, valor: 0, deals: 0 };
                byDono[key].valor += n.valor;
                byDono[key].deals += 1;
              });
              const rows = Object.values(byDono).sort((a,b) => b.valor - a.valor).slice(0, 5);
              const topValor = rows[0]?.valor || 1;
              return rows.map((r, i) => {
                const hit = Math.round((r.valor / topValor) * 132); // 132% = top performer benchmark
                const avatarIdx = CONTATOS.findIndex(c => c.id === r.dono.id);
                return (
                  <div key={i} className="row" style={{gap: 12, padding: '6px 4px', borderBottom: '1px solid oklch(0.93 0.01 255)'}}>
                    <img src={r.dono.avatar} style={{width: 32, height: 32, borderRadius: '50%'}} alt="" />
                    <div className="col" style={{flex: 1}}>
                      <div style={{fontSize: 13, fontWeight: 600}}>{r.dono.nome.split(' ').slice(0,2).join(' ')}</div>
                      <div className="muted" style={{fontSize: 11.5}}>{r.deals} negócio{r.deals !== 1 ? 's' : ''} · R$ {(r.valor/1000).toFixed(0)}k</div>
                    </div>
                    <span className={`pill ${hit >= 100 ? 'pill-mint' : 'pill-yellow'}`}>{hit}% da meta</span>
                  </div>
                );
              });
            })()}
          </div>
        </div>
      </div>

      {exportOpen && <ExportModal onClose={() => setExportOpen(false)} periodLabel={p.label} />}

      <style>{`
        .rep-stats { display: grid; grid-template-columns: repeat(4, 1fr); gap: 14px; margin-bottom: 14px; }
        .rep-stat { padding: 18px 20px !important; }
        .rep-val { font-size: 28px; font-weight: 700; letter-spacing: -0.025em; margin: 6px 0 10px; }
        .rep-grid { display: grid; grid-template-columns: 1.6fr 1fr; gap: 14px; margin-bottom: 14px; }
        .rep-grid-2 { display: grid; grid-template-columns: 1.4fr 1fr; gap: 14px; }
        .donut-legend { display: flex; flex-direction: column; gap: 8px; margin-top: 14px; }
        .leg-row { display: flex; align-items: center; gap: 10px; }
        .leg-sw { width: 12px; height: 12px; border-radius: 4px; }
        .leg-blue { background: var(--acc-blue); }
        .leg-yellow { background: var(--acc-yellow); }
        .leg-pink { background: var(--acc-pink); }
        .leg-mint { background: var(--acc-mint); }

        .rel-toggle { display: flex; align-items: center; }
        .rel-toggle-btn {
          display: inline-flex; align-items: center; gap: 8px;
          background: oklch(0.97 0.01 250 / 0.7);
          border: 0.5px solid oklch(1 0 0 / 0.8);
          border-radius: 999px;
          padding: 8px 14px 8px 8px;
          font-family: inherit; font-size: 12px; font-weight: 500;
          color: var(--ink-soft);
          cursor: default;
        }
        .rel-toggle-on { color: var(--ink); background: white; }

        .rel-period-dd-wrap { position: relative; }
        .rel-period-menu {
          position: absolute; top: calc(100% + 6px); right: 0;
          min-width: 200px;
          background: white;
          border: 0.5px solid oklch(0.92 0.01 250);
          border-radius: 14px;
          box-shadow: 0 16px 40px -12px rgba(20,30,60,.22);
          padding: 6px;
          z-index: 50;
          animation: fadein .15s ease;
        }

        .rel-seg {
          display: inline-flex; gap: 2px;
          padding: 3px;
          background: oklch(0.95 0.01 250);
          border-radius: 999px;
        }
        .rel-seg-btn {
          background: transparent;
          border: 0;
          border-radius: 999px;
          padding: 6px 12px;
          font-family: inherit;
          font-size: 11.5px;
          font-weight: 600;
          color: var(--ink-muted);
          cursor: default;
        }
        .rel-seg-on { background: var(--black); color: white; }

        .chart-legend {
          display: inline-flex; align-items: center; gap: 18px;
          margin-top: 10px;
          padding: 8px 14px;
          background: oklch(0.97 0.01 250);
          border-radius: 999px;
          width: fit-content;
        }
        .chart-legend-item { display: inline-flex; align-items: center; gap: 8px; font-size: 11.5px; color: var(--ink-soft); font-weight: 500; }
        .chart-legend-line { width: 18px; height: 2px; border-radius: 2px; display: inline-block; }
        .chart-legend-now { background: oklch(0.55 0.18 250); }
        .chart-legend-prev {
          background: transparent;
          border-top: 2px dashed oklch(0.78 0.05 250);
          height: 0;
          margin-top: 1px;
        }
      `}</style>
    </>
  );
}

function RepStat({ l, v, d, c, comp, compLbl }) {
  return (
    <div className="card rep-stat">
      <div className="muted" style={{fontSize: 12}}>{l}</div>
      <div className="rep-val money">{v}</div>
      <div className="row" style={{gap: 6}}>
        <span className={`pill pill-${c}`}>{d}</span>
        {comp && <span className="muted" style={{fontSize: 10.5}}>{compLbl}</span>}
      </div>
    </div>
  );
}

function CardMenu({ id, onOpen, active }) {
  const toast = useToast();
  const csvWidgetExport = () => {
    const rows = [['Conta','Valor','Etapa','Prob%'], ...OPORTUNIDADES.map(n=>[n.conta, n.valor, n.etapa, n.prob])];
    const csv = '﻿' + rows.map(r => r.map(c=>`"${c}"`).join(',')).join('\n');
    const a = Object.assign(document.createElement('a'), { href: URL.createObjectURL(new Blob([csv], {type:'text/csv;charset=utf-8'})), download: `relatorio-${id}.csv` });
    a.click(); URL.revokeObjectURL(a.href);
    toast('CSV do widget baixado ✓');
    onOpen(null);
  };
  const shareWidget = () => {
    navigator.clipboard?.writeText(`https://app.ezza.com.br/relatorios/widget/${id}`).catch(()=>{});
    toast('Link do widget copiado ✓');
    onOpen(null);
  };
  const items = [
    { ic: ICN.upload,  label: 'Exportar CSV',              onClick: csvWidgetExport },
    { ic: ICN.download,label: 'Baixar PDF',                onClick: () => { toast('PDF do widget gerado ✓'); onOpen(null); } },
    { ic: ICN.refresh, label: 'Atualizar dados',           onClick: () => { toast('Dados atualizados ✓');    onOpen(null); } },
    { ic: ICN.cal,     label: 'Comparar com outro período',onClick: () => { toast('Selecione o período acima ↗'); onOpen(null); } },
    { ic: ICN.share,   label: 'Compartilhar widget',       onClick: shareWidget },
    { ic: ICN.settings,label: 'Configurar widget',         onClick: () => { toast('Configurações do widget em breve'); onOpen(null); } },
  ];
  return (
    <div style={{position:'relative'}}>
      <div className="mini-btn" onClick={(e) => { e.stopPropagation(); onOpen(active ? null : { id }); }}>{ICN.more}</div>
      {active && (
        <div className="card-menu" onClick={(e) => e.stopPropagation()}>
          {items.map((it, i) => (
            <div key={i} className="card-menu-item" onClick={it.onClick}>
              <span className="muted" style={{display:'inline-flex'}}>{it.ic}</span>
              <span>{it.label}</span>
            </div>
          ))}
        </div>
      )}
      <style>{`
        .card-menu {
          position: absolute; right: 0; top: calc(100% + 6px);
          min-width: 220px;
          background: white;
          border: 0.5px solid oklch(0.92 0.01 250);
          border-radius: 14px;
          box-shadow: 0 16px 40px -12px rgba(20,30,60,.22);
          padding: 6px;
          z-index: 40;
          animation: fadein .15s ease;
        }
        .card-menu-item {
          display: flex; align-items: center; gap: 10px;
          padding: 8px 12px;
          border-radius: 10px;
          font-size: 12.5px;
          cursor: default;
        }
        .card-menu-item:hover { background: oklch(0.96 0.012 250); }
      `}</style>
    </div>
  );
}

function ExportModal({ onClose, periodLabel }) {
  const [fmt, setFmt] = useRelState('pdf');
  const [scope, setScope] = useRelState('todos');
  const [emails, setEmails] = useRelState(true);
  const toast = useToast();

  const buildRows = () => {
    const negTotal   = NEGOCIOS.reduce((s,n) => s + n.valor, 0);
    const negEsp     = NEGOCIOS.reduce((s,n) => s + n.valor*(n.prob/100), 0);
    const tkMedio    = Math.round(negTotal / NEGOCIOS.length);
    const ganhos     = LEADS.filter(l => l.etapa === 'fechado').length;
    const convPct    = ((ganhos / LEADS.length)*100).toFixed(1);
    return [
      ['Métrica',              'Valor',                                   'Período'],
      ['Receita esperada',     `R$ ${Math.round(negEsp).toLocaleString('pt-BR')}`, periodLabel],
      ['Pipeline total',       `R$ ${negTotal.toLocaleString('pt-BR')}`,           periodLabel],
      ['Ticket médio',         `R$ ${tkMedio.toLocaleString('pt-BR')}`,            periodLabel],
      ['Taxa de conversão',    `${convPct}%`,                             periodLabel],
      ['Leads totais',         String(LEADS.length),                      periodLabel],
      ['Leads ganhos',         String(ganhos),                            periodLabel],
      ['Oportunidades ativas', String(NEGOCIOS.filter(n=>n.etapa!=='Fechado').length), periodLabel],
      ...NEGOCIOS.sort((a,b)=>b.valor-a.valor).map(n => [n.conta, `R$ ${n.valor.toLocaleString('pt-BR')}`, n.etapa]),
    ];
  };

  const handleExport = () => {
    const rows = buildRows();
    const fname = `ezza-relatorio-${periodLabel.replace(/\s+/g,'-').toLowerCase()}`;

    if (fmt === 'csv') {
      const csv = rows.map(r => r.map(c => `"${c}"`).join(',')).join('\n');
      const blob = new Blob(['﻿' + csv], { type: 'text/csv;charset=utf-8;' });
      const a = Object.assign(document.createElement('a'), { href: URL.createObjectURL(blob), download: fname + '.csv' });
      a.click(); URL.revokeObjectURL(a.href);
      toast('✅ CSV exportado!');

    } else if (fmt === 'xlsx') {
      // Tabela HTML que Excel/Sheets abre nativamente como .xls
      const trs = rows.map((r, i) =>
        `<tr>${r.map(c => i === 0 ? `<th style="background:#1a1f3c;color:white;padding:8px 12px;font-weight:bold">${c}</th>` : `<td style="padding:6px 12px;border-bottom:1px solid #eee">${c}</td>`).join('')}</tr>`
      ).join('');
      const html = `<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><meta charset="utf-8"><style>table{border-collapse:collapse;font-family:Arial,sans-serif;font-size:12px}th,td{border:1px solid #ddd}</style></head><body><h2 style="font-family:Arial">Ezza CRM — Relatório ${periodLabel}</h2><table>${trs}</table></body></html>`;
      const blob = new Blob(['﻿' + html], { type: 'application/vnd.ms-excel;charset=utf-8;' });
      const a = Object.assign(document.createElement('a'), { href: URL.createObjectURL(blob), download: fname + '.xls' });
      a.click(); URL.revokeObjectURL(a.href);
      toast('✅ Excel exportado!');

    } else if (fmt === 'pdf') {
      // Abre janela de impressão com layout limpo → "Salvar como PDF"
      const trs = rows.map((r, i) =>
        `<tr>${r.map(c => i === 0 ? `<th>${c}</th>` : `<td>${c}</td>`).join('')}</tr>`
      ).join('');
      const html = `<!DOCTYPE html><html><head><meta charset="utf-8"><title>Ezza CRM — ${periodLabel}</title><style>
        body{font-family:Arial,sans-serif;padding:32px;color:#111}
        h1{font-size:20px;margin-bottom:4px}p{color:#666;font-size:13px;margin-bottom:24px}
        table{width:100%;border-collapse:collapse;font-size:12px}
        th{background:#1a1f3c;color:white;padding:8px 12px;text-align:left}
        td{padding:7px 12px;border-bottom:1px solid #eee}
        tr:nth-child(even) td{background:#f7f8fc}
        @media print{body{padding:0}}
      </style></head><body>
        <h1>Relatório de Desempenho — ${periodLabel}</h1>
        <p>Gerado em ${new Date().toLocaleDateString('pt-BR')} via Ezza CRM</p>
        <table>${trs}</table>
      </body></html>`;
      const w = window.open('', '_blank', 'width=800,height=600');
      w.document.write(html);
      w.document.close();
      w.onload = () => { w.focus(); w.print(); };
      toast('📄 Abrindo visualização para impressão / PDF…');
    }
    onClose();
  };

  return (
    <div className="modal-wrap" onClick={onClose}>
      <div className="card modal-card" onClick={(e) => e.stopPropagation()} style={{width: 520}}>
        <div className="modal-head">
          <div>
            <div className="modal-title">Exportar <em>relatório</em></div>
            <div className="modal-sub muted">{periodLabel}</div>
          </div>
          <div className="mini-btn" onClick={onClose}>{ICN.x}</div>
        </div>

        <div className="field-lbl" style={{marginBottom: 10}}>Formato</div>
        <div className="exp-grid">
          {[
            { id: 'pdf',  label: 'PDF',   sub: 'Apresentação com gráficos', size: '~2 MB',  ic: '📄' },
            { id: 'csv',  label: 'CSV',   sub: 'Dados brutos por linha',     size: '~24 KB', ic: '📊' },
            { id: 'xlsx', label: 'Excel', sub: 'Planilha com fórmulas',      size: '~180 KB',ic: '📈' },
          ].map(f => (
            <div key={f.id} className={`exp-card ${fmt === f.id ? 'exp-card-on' : ''}`} onClick={() => setFmt(f.id)}>
              <div className="exp-ic">{f.ic}</div>
              <div className="exp-lbl">{f.label}</div>
              <div className="exp-sub muted">{f.sub}</div>
              <div className="exp-size">{f.size}</div>
            </div>
          ))}
        </div>

        <div className="field-lbl" style={{marginTop: 18, marginBottom: 8}}>O que incluir</div>
        <div className="col" style={{gap: 4}}>
          {[
            { id: 'todos',  label: 'Relatório completo',        hint: 'Todos os widgets desta tela' },
            { id: 'kpis',   label: 'Apenas KPIs do topo',       hint: 'Receita, ticket médio, ciclo e conversão' },
            { id: 'detal',  label: 'Detalhado com transações',  hint: 'Inclui anexo com lista de negócios' },
          ].map(s => (
            <label key={s.id} className="exp-radio" onClick={() => setScope(s.id)}>
              <div className={`exp-radio-circle ${scope === s.id ? 'exp-radio-on' : ''}`}>
                {scope === s.id && <span />}
              </div>
              <div className="col" style={{flex:1}}>
                <div style={{fontSize: 13, fontWeight: 600}}>{s.label}</div>
                <div className="muted" style={{fontSize: 11.5}}>{s.hint}</div>
              </div>
            </label>
          ))}
        </div>

        <div className="exp-mail">
          <div className="col" style={{flex:1}}>
            <div style={{fontSize: 13, fontWeight: 600}}>Enviar por e-mail também</div>
            <div className="muted" style={{fontSize: 11.5, marginTop: 2}}>Para: leticia.andrade@ezza.com.br</div>
          </div>
          <button className={`switch ${emails ? 'switch-on' : ''}`} onClick={() => setEmails(!emails)}><div className="switch-knob"/></button>
        </div>

        <div className="modal-actions">
          <button className="btn-ghost" onClick={onClose}>Cancelar</button>
          <button className="btn-primary" onClick={handleExport}>
            {ICN.download} Gerar {fmt.toUpperCase()}
          </button>
        </div>
      </div>

      <style>{`
        .exp-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; }
        .exp-card {
          padding: 14px 12px;
          border-radius: 14px;
          background: oklch(0.97 0.01 250);
          border: 1.5px solid transparent;
          cursor: default;
          transition: border-color .15s, background .15s;
          text-align: left;
        }
        .exp-card:hover { background: oklch(0.95 0.012 250); }
        .exp-card-on { border-color: oklch(0.55 0.16 250); background: oklch(0.97 0.05 250); }
        .exp-ic { font-size: 22px; margin-bottom: 8px; }
        .exp-lbl { font-size: 14px; font-weight: 700; }
        .exp-sub { font-size: 11px; margin-top: 2px; line-height: 1.3; }
        .exp-size { font-size: 10px; color: var(--ink-faint); margin-top: 6px; font-family: var(--font-mono); }

        .exp-radio { display: flex; gap: 12px; padding: 10px; border-radius: 12px; cursor: default; }
        .exp-radio:hover { background: oklch(0.97 0.01 250); }
        .exp-radio-circle { width: 18px; height: 18px; border-radius: 50%; border: 1.5px solid oklch(0.80 0.01 250); margin-top: 2px; flex-shrink: 0; display: grid; place-items: center; }
        .exp-radio-on { border-color: oklch(0.55 0.16 250); }
        .exp-radio-on > span { width: 8px; height: 8px; border-radius: 50%; background: oklch(0.55 0.16 250); display: block; }

        .exp-mail { display: flex; align-items: center; gap: 12px; margin-top: 14px; padding: 12px 14px; background: oklch(0.96 0.012 250); border-radius: 14px; }
      `}</style>
    </div>
  );
}

function AreaChart({ granul = 'diario', mult = 1, comparing = false }) {
  // Different data shapes per granularidade
  let pts;
  if (granul === 'diario') {
    pts = Array.from({length: 30}, (_, i) => {
      const v = 50 + 35 * Math.sin(i/4) + 18 * Math.cos(i/2.4) + (i * 1.5);
      return { y: v * mult };
    });
  } else if (granul === 'semanal') {
    pts = Array.from({length: 12}, (_, i) => {
      const v = 220 + 80 * Math.sin(i/2.2) + 40 * Math.cos(i/1.4) + (i * 8);
      return { y: v * mult };
    });
  } else { // mensal
    pts = Array.from({length: 12}, (_, i) => {
      const v = 980 + 220 * Math.sin(i/2.6) + 140 * Math.cos(i/1.6) + (i * 36);
      return { y: v * mult };
    });
  }
  // optional comparison series (previous period, dimmer)
  const pts2 = comparing ? pts.map((p, i) => ({ y: p.y * (0.78 + 0.15 * Math.sin(i/3)) })) : null;

  const W = 720, H = 320;
  const PAD_T = 32, PAD_B = 40, PAD_L = 44, PAD_R = 28;
  const all = pts2 ? [...pts, ...pts2] : pts;
  const ys = all.map(p => p.y);
  const range = Math.max(...ys) - Math.min(...ys);
  const minY = Math.min(...ys) - range * 0.18, maxY = Math.max(...ys) + range * 0.12;
  const sx = i => PAD_L + (i / (pts.length - 1)) * (W - PAD_L - PAD_R);
  const sy = v => H - PAD_B - ((v - minY) / (maxY - minY)) * (H - PAD_T - PAD_B);

  const smoothPath = (pts) => {
    if (pts.length < 2) return '';
    let d = `M ${sx(0)},${sy(pts[0].y)}`;
    for (let i = 0; i < pts.length - 1; i++) {
      const p0 = pts[i - 1] || pts[i];
      const p1 = pts[i];
      const p2 = pts[i + 1];
      const p3 = pts[i + 2] || p2;
      const cp1x = sx(i) + (sx(i+1) - (i > 0 ? sx(i-1) : sx(i))) / 6;
      const cp1y = sy(p1.y) + (sy(p2.y) - sy(p0.y)) / 6;
      const cp2x = sx(i+1) - ((i+2 < pts.length ? sx(i+2) : sx(i+1)) - sx(i)) / 6;
      const cp2y = sy(p2.y) - (sy(p3.y) - sy(p1.y)) / 6;
      d += ` C ${cp1x},${cp1y} ${cp2x},${cp2y} ${sx(i+1)},${sy(p2.y)}`;
    }
    return d;
  };

  const line = smoothPath(pts);
  const area = `${line} L ${sx(pts.length - 1)},${H - PAD_B} L ${sx(0)},${H - PAD_B} Z`;
  const line2 = pts2 ? smoothPath(pts2) : null;

  const last = pts[pts.length - 1];
  const yTicks = [0.25, 0.5, 0.75, 1];
  const xLabels = granul === 'diario'
    ? [{ i: 0, t: '01' }, { i: 7, t: '08' }, { i: 14, t: '15' }, { i: 21, t: '22' }, { i: 29, t: '30' }]
    : granul === 'semanal'
    ? [{ i: 0, t: 'S1' }, { i: 3, t: 'S4' }, { i: 6, t: 'S7' }, { i: 9, t: 'S10' }, { i: 11, t: 'S12' }]
    : [{ i: 0, t: 'Jan' }, { i: 3, t: 'Abr' }, { i: 6, t: 'Jul' }, { i: 9, t: 'Out' }, { i: 11, t: 'Dez' }];

  return (
    <svg viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="none" style={{width: '100%', height: 'auto', display:'block', minHeight: 220, maxHeight: 360}}>
      <defs>
        <linearGradient id="ar" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%"   stopColor="oklch(0.55 0.16 250)" stopOpacity="0.45"/>
          <stop offset="50%"  stopColor="oklch(0.55 0.16 250)" stopOpacity="0.14"/>
          <stop offset="100%" stopColor="oklch(0.55 0.16 250)" stopOpacity="0"/>
        </linearGradient>
        <linearGradient id="ar-line" x1="0" y1="0" x2="1" y2="0">
          <stop offset="0%" stopColor="oklch(0.55 0.18 250)"/>
          <stop offset="100%" stopColor="oklch(0.55 0.18 295)"/>
        </linearGradient>
      </defs>

      {yTicks.map(p => {
        const y = PAD_T + p * (H - PAD_T - PAD_B);
        const value = Math.round(maxY - (maxY - minY) * p);
        return (
          <g key={p}>
            <line x1={PAD_L} x2={W - PAD_R} y1={y} y2={y} stroke="oklch(0.94 0.01 255)" strokeDasharray="4 5"/>
            <text x={PAD_L - 6} y={y + 3} fontSize="9.5" fill="oklch(0.70 0.012 255)" textAnchor="end" fontFamily="ui-monospace, monospace">R${value < 1000 ? value + 'k' : (value/1000).toFixed(1) + 'M'}</text>
          </g>
        );
      })}

      {line2 && (
        <path d={line2} fill="none" stroke="oklch(0.78 0.05 250)" strokeWidth="2" strokeDasharray="6 5" strokeLinejoin="round" strokeLinecap="round" opacity="0.7"/>
      )}
      <path d={area} fill="url(#ar)"/>
      <path d={line} fill="none" stroke="url(#ar-line)" strokeWidth="2.5" strokeLinejoin="round" strokeLinecap="round"/>

      {(() => {
        const step = granul === 'diario' ? 5 : granul === 'semanal' ? 3 : 3;
        return pts.filter((_, i) => i % step === 0 || i === pts.length - 1).map((p, i, arr) => {
          const idx = pts.indexOf(p);
          const isLast = idx === pts.length - 1;
          return (
            <g key={idx}>
              <circle cx={sx(idx)} cy={sy(p.y)} r={isLast ? 7 : 4.5} fill="white" stroke="oklch(0.45 0.18 250)" strokeWidth="2.5"/>
              {isLast && (
                <>
                  <circle cx={sx(idx)} cy={sy(p.y)} r="3" fill="oklch(0.45 0.18 250)"/>
                  <g transform={`translate(${sx(idx) - 60}, ${sy(p.y) - 38})`}>
                    <rect width="56" height="26" rx="7" fill="oklch(0.20 0.01 255)" />
                    <text x="28" y="17" fontSize="11" fill="white" textAnchor="middle" fontWeight="700">R${Math.round(p.y)}k</text>
                  </g>
                </>
              )}
            </g>
          );
        });
      })()}

      {xLabels.map((x,k) => (
        <text key={k} x={sx(x.i)} y={H - 12} fontSize="9.5" fill="oklch(0.55 0.012 255)" textAnchor="middle">{x.t}</text>
      ))}

      {comparing && (
        <g transform={`translate(${W - PAD_R - 70}, ${H - 22})`}>
          {/* placeholder kept empty — legend moved to HTML below chart */}
        </g>
      )}
    </svg>
  );
}

function Donut() {
  const data = [
    { v: 42, c: 'var(--acc-blue)' },
    { v: 28, c: 'var(--acc-yellow)' },
    { v: 18, c: 'var(--acc-pink)' },
    { v: 12, c: 'var(--acc-mint)' },
  ];
  const total = data.reduce((s,d) => s+d.v, 0);
  const C = 100, R = 70;
  const SW = 28;
  let acc = 0;
  return (
    <svg viewBox={`0 0 ${C*2} ${C*2}`} style={{width: 240, height: 240, display: 'block', margin: '8px auto 0'}}>
      {data.map((d,i) => {
        const frac = d.v / total;
        const start = acc; acc += frac;
        const a1 = start * Math.PI * 2 - Math.PI/2;
        const a2 = acc * Math.PI * 2 - Math.PI/2;
        const x1 = C + R * Math.cos(a1), y1 = C + R * Math.sin(a1);
        const x2 = C + R * Math.cos(a2), y2 = C + R * Math.sin(a2);
        const large = frac > 0.5 ? 1 : 0;
        return (
          <path key={i}
            d={`M ${x1} ${y1} A ${R} ${R} 0 ${large} 1 ${x2} ${y2}`}
            stroke={d.c} strokeWidth={SW} fill="none" strokeLinecap="butt"/>
        );
      })}
      <text x={C} y={C-4} fontSize="14" fontWeight="700" textAnchor="middle" fill="oklch(0.20 0.01 255)">76</text>
      <text x={C} y={C+14} fontSize="10" textAnchor="middle" fill="oklch(0.55 0.01 255)">negócios</text>
    </svg>
  );
}

window.Relatorios = Relatorios;
