// Blocos de relatório do Financeiro. Mesmos blocos para qualquer organização (dados da organização ativa) e, só para a
// equipe interna da Vértice (organização VERTICE + commercial_intelligence.view), blocos de prospecção: funil de vendas,
// potencial de faturamento e faturamento informado dos prospects. Tudo calculado dos registros carregados
// (window.VxFinance); sem dado, mostra estado vazio. A fronteira de segurança é o banco (RLS), não esta tela.
const FIN_BLUE = 'var(--vx-blue-500)', FIN_SKY = 'var(--vx-sky-400)';
const finMoney = v => Number(v || 0).toLocaleString('pt-BR', { style: 'currency', currency: 'BRL', maximumFractionDigits: 0 });
const finMonthLabel = m => ['Jan', 'Fev', 'Mar', 'Abr', 'Mai', 'Jun', 'Jul', 'Ago', 'Set', 'Out', 'Nov', 'Dez'][Number(m.slice(5, 7)) - 1] + '/' + m.slice(2, 4);

// Colunas agrupadas por mês: cada série é { key, label, color, dash }.
function FinColumns({ months, series, ariaLabel }) {
  const W = 640, H = 220, left = 8, bottom = 28, top = 10, n = months.length;
  const max = Math.max(1, ...months.flatMap(m => series.map(s => m[s.key] || 0)));
  const band = (W - left) / Math.max(1, n), bw = Math.min(28, (band - 12) / series.length);
  return (
    <svg viewBox={`0 0 ${W} ${H}`} role="img" aria-label={ariaLabel} style={{ width: '100%', height: 'auto', display: 'block' }} fontFamily="Geist Mono, monospace" fontSize="12" fill="var(--text-muted)">
      <g stroke="var(--overlay-07)" strokeDasharray="4 6">{[0, 1, 2, 3].map(i => { const y = top + (H - top - bottom) * (i / 3); return <line key={i} x1={left} y1={y} x2={W} y2={y} />; })}</g>
      {months.map((m, i) => {
        const x0 = left + band * i + (band - bw * series.length) / 2;
        return (
          <g key={m.month}>
            {series.map((s, j) => {
              const v = m[s.key] || 0, h = (H - top - bottom) * (v / max);
              return <rect key={s.key} x={x0 + bw * j} y={H - bottom - h} width={bw - 2} height={Math.max(h, v > 0 ? 2 : 0)} rx="3" style={{ fill: s.color }} opacity={s.dim ? 0.55 : 1}><title>{s.label + ' · ' + finMonthLabel(m.month) + ': ' + finMoney(v)}</title></rect>;
            })}
            <text x={left + band * i + band / 2} y={H - 8} textAnchor="middle">{finMonthLabel(m.month)}</text>
          </g>
        );
      })}
    </svg>
  );
}

function FinLegend({ items }) {
  return <div style={{ display: 'flex', flexWrap: 'wrap', gap: 16, fontSize: 13, color: 'var(--text-secondary)' }}>
    {items.map(([label, color, dim]) => <span key={label} style={{ display: 'flex', alignItems: 'center', gap: 8 }}><span style={{ width: 14, height: 8, borderRadius: 3, background: color, opacity: dim ? 0.55 : 1 }} />{label}</span>)}
  </div>;
}

// Barras horizontais com rótulo e valor; `value` define o comprimento.
function FinBars({ rows, format }) {
  const max = Math.max(1, ...rows.map(r => r.value));
  return <div style={{ display: 'grid', gap: 12 }}>
    {rows.map(r => <div key={r.key} style={{ display: 'grid', gridTemplateColumns: 'minmax(96px, 168px) 1fr minmax(64px, auto)', gap: 12, alignItems: 'center', fontSize: 13 }}>
      <span style={{ color: 'var(--text-secondary)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }} title={r.label}>{r.label}</span>
      <span style={{ height: 8, borderRadius: 4, background: 'var(--overlay-07)', overflow: 'hidden' }}><span style={{ display: 'block', height: '100%', width: (100 * r.value / max) + '%', background: FIN_BLUE, borderRadius: 4 }} /></span>
      <span style={{ fontFamily: 'Geist Mono, monospace', textAlign: 'right' }}>{format ? format(r) : r.value}</span>
    </div>)}
  </div>;
}

function FinanceInsights({ rows, contracts, org }) {
  const { Card, CardHeader, KpiCard, EmptyState, Badge } = window.VRticeDesignSystem_d763eb;
  const { can } = useAccess();
  const F = window.VxFinance, V = window.VxSalesIntelligence;
  const today = new Date().toISOString().slice(0, 10);
  const internal = !!(org && org.kind === 'VERTICE' && can('commercial_intelligence.view'));
  const hasRows = rows.length > 0;

  const series = F.monthlySeries(rows, today, 6);
  const fc = F.forecast(rows, today, 6);
  const costs = F.costsByContract(rows, contracts || []).filter(r => r.despesa > 0);

  const [acc] = useRemote(async () => {
    if (!internal || !org) return null;
    const { data, error } = await window.VxAuth.db().from('commercial_accounts').select('id,stage,potential_value').eq('organization_id', org.id).limit(5000);
    if (error) throw error;
    const list = data || [];
    const rev = list.length ? await V.revenueByAccount(list.map(a => a.id)) : {};
    return { list, rev };
  }, [internal, org && org.id]);

  const empty = (title, text) => <EmptyState variant="block" icon="ph-chart-bar" title={title}>{text}</EmptyState>;
  const sub = (a, b) => hasRows ? a : b;

  const cards = [
    <Card key="evol" variant="panel" gap={20}>
      <CardHeader size="sm" title="Evolução mensal" subtitle="Receitas e despesas por mês de vencimento (últimos 6 meses)" />
      {hasRows ? <><FinColumns months={series.months} ariaLabel="Receitas e despesas por mês" series={[
        { key: 'receitaPaga', label: 'Receita paga', color: FIN_BLUE }, { key: 'receitaAberta', label: 'Receita em aberto', color: FIN_BLUE, dim: true },
        { key: 'despesaPaga', label: 'Despesa paga', color: FIN_SKY }, { key: 'despesaAberta', label: 'Despesa em aberto', color: FIN_SKY, dim: true }]} />
        <FinLegend items={[['Receita paga', FIN_BLUE], ['Receita em aberto', FIN_BLUE, true], ['Despesa paga', FIN_SKY], ['Despesa em aberto', FIN_SKY, true]]} />
        {series.undated > 0 && <span style={{ fontSize: 13, color: 'var(--text-muted)' }}>{series.undated} lançamento(s) sem vencimento não entram no gráfico.</span>}</>
        : empty('Sem lançamentos ainda', 'Cadastre lançamentos para ver a evolução mensal.')}
    </Card>,
    <Card key="prev" variant="panel" gap={20}>
      <CardHeader size="sm" title="Previsão de faturamento" subtitle="Receitas em aberto, pelo mês de vencimento (próximos 6 meses)" />
      {hasRows && (fc.total > 0 || fc.overdue > 0 || fc.beyond > 0) ? <>
        <FinColumns months={fc.months.map(m => ({ month: m.month, previsto: m.amount }))} ariaLabel="Receitas em aberto por mês de vencimento" series={[{ key: 'previsto', label: 'A receber', color: FIN_BLUE }]} />
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(160px, 1fr))', gap: 12 }}>
          <KpiCard compact label="A receber na janela" value={finMoney(fc.total)} caption="vencimento a partir de hoje" />
          <KpiCard compact label="Vencido em aberto" value={finMoney(fc.overdue)} caption="vencimento anterior a hoje" />
          <KpiCard compact label="Além de 6 meses" value={finMoney(fc.beyond)} caption="fora da janela" />
        </div>
        {fc.undated > 0 && <span style={{ fontSize: 13, color: 'var(--text-muted)' }}>{fc.undated} receita(s) em aberto sem vencimento não entram na previsão.</span>}</>
        : empty('Nada a receber em aberto', sub('Não há receitas em aberto com vencimento informado.', 'Cadastre receitas com vencimento para ver a previsão.'))}
    </Card>,
    <Card key="custo" variant="panel" gap={20}>
      <CardHeader size="sm" title="Custos por contrato" subtitle="Despesas lançadas, agrupadas pelo contrato vinculado" />
      {costs.length ? <FinBars rows={costs.map(r => ({ key: String(r.contractId), label: r.label, value: r.despesa, receita: r.receita, resultado: r.resultado }))}
        format={r => finMoney(r.value)} /> : empty('Sem custos lançados', 'Lance despesas vinculadas a um contrato para ver os custos por contrato.')}
      {costs.length > 0 && <span style={{ fontSize: 13, color: 'var(--text-muted)' }}>Resultado por contrato (receitas − despesas): {costs.map(r => r.label + ' ' + finMoney(r.resultado)).join(' · ')}</span>}
    </Card>,
  ];

  let internalCards = null;
  if (internal) {
    const STAGES = V.STAGES, PROB = V.PROB;
    const d = acc.data;
    const fun = d ? F.funnel(d.list, STAGES) : null, pot = d ? F.potential(d.list, STAGES, PROB) : null, rev = d ? F.prospectRevenue(d.rev) : null;
    internalCards = acc.error ? [<Card key="err" variant="panel" gap={12}><CardHeader size="sm" title="Visão interna indisponível" subtitle="Não foi possível carregar as contas comerciais" />{empty('Erro ao carregar', String(acc.error))}</Card>] : [
      <Card key="funil" variant="panel" gap={20}>
        <CardHeader size="sm" title="Funil de vendas da Vértice" subtitle="Contas comerciais por estágio" action={<Badge tone="neutral">Uso interno</Badge>} />
        {fun && fun.total ? <><FinBars rows={fun.stages.map(s => ({ key: s.key, label: s.label, value: s.count }))} format={r => String(r.value)} />
          {fun.others > 0 && <span style={{ fontSize: 13, color: 'var(--text-muted)' }}>{fun.others} conta(s) ainda sem estágio no funil (candidatas).</span>}</>
          : empty(acc.loading ? 'Carregando' : 'Sem contas comerciais', 'As contas aparecem aqui quando são promovidas em Comercial.')}
      </Card>,
      <Card key="pot" variant="panel" gap={20}>
        <CardHeader size="sm" title="Potencial de faturamento" subtitle="Soma do potencial informado em cada conta; ponderado pela probabilidade do estágio" action={<Badge tone="neutral">Uso interno</Badge>} />
        {pot && pot.withValue ? <>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(170px, 1fr))', gap: 12 }}>
            <KpiCard compact label="Potencial em aberto" value={finMoney(pot.openValue)} caption="contas fora de Cliente e Perdido" />
            <KpiCard compact label="Ponderado" value={finMoney(pot.openWeighted)} caption="valor × probabilidade do estágio" />
            <KpiCard compact label="Sem valor informado" value={String(pot.withoutValue)} caption="contas não entram na soma" />
          </div>
          <FinBars rows={pot.stages.filter(s => s.informed > 0).map(s => ({ key: s.key, label: s.label, value: s.value }))} format={r => finMoney(r.value)} /></>
          : empty(acc.loading ? 'Carregando' : 'Nenhum potencial informado', 'Informe o potencial de faturamento nas contas para ver a soma e o ponderado.')}
      </Card>,
      <Card key="fat" variant="panel" gap={20}>
        <CardHeader size="sm" title="Faturamento informado dos prospects" subtitle="Soma mensal do que foi informado por fonte própria (uma fonte por conta e mês)" action={<Badge tone="neutral">Uso interno</Badge>} />
        {rev && rev.accountsWithData ? <><FinColumns months={rev.perMonth} ariaLabel="Faturamento informado dos prospects por mês" series={[{ key: 'amount', label: 'Informado', color: FIN_BLUE }]} />
          <span style={{ fontSize: 13, color: 'var(--text-muted)' }}>{rev.accountsWithData} conta(s) com faturamento informado. Meses sem informação ficam vazios; valores públicos do PNCP não são somados aqui.</span></>
          : empty(acc.loading ? 'Carregando' : 'Sem faturamento informado', 'Lance o faturamento mensal de uma conta no CRM para ver a soma aqui.')}
      </Card>,
    ];
  }

  return (
    <div style={{ display: 'grid', gap: 20 }}>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(min(420px, 100%), 1fr))', gap: 20 }}>{cards}</div>
      {internalCards && <>
        <div style={{ fontSize: 12, letterSpacing: '.08em', color: 'var(--text-muted)' }}>VISÃO INTERNA DA VÉRTICE</div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(min(420px, 100%), 1fr))', gap: 20 }}>{internalCards}</div>
      </>}
    </div>
  );
}
window.FinanceInsights = FinanceInsights;
