/* Sub-ecrã Resultados — faturado total e anual contra o investimento em media. */

function fatFetch(url) {
  return fetch(url, { headers: { 'Content-Type': 'application/json' } }).then(async (res) => {
    const body = await res.json().catch(() => ({}));
    if (!res.ok) throw new Error(body.error || `HTTP ${res.status}`);
    return body;
  });
}

function fatEur(v) {
  return window.resFmtEur ? window.resFmtEur(v) : (v == null ? '—' : String(Math.round(Number(v) || 0)));
}
function fatN(v) {
  return Math.round(Number(v) || 0).toLocaleString('pt-PT');
}
function fatRoas(v) {
  if (v == null || !Number.isFinite(Number(v))) return '—';
  return Number(v).toLocaleString('pt-PT', { minimumFractionDigits: 1, maximumFractionDigits: 1 }) + '×';
}

const FAT_COR = { faturado: '#3859D0', investimento: '#F59E0B' };

function FatTotal({ total, anos }) {
  const comSpend = (anos || []).filter(a => a.investimento > 0);
  const faturadoComSpend = comSpend.reduce((s, a) => s + (Number(a.faturado) || 0), 0);
  const roas = total.investimento > 0 ? faturadoComSpend / total.investimento : null;
  const anosSpend = comSpend.map(a => a.ano).join(' e ');
  const max = Math.max(total.faturado, total.investimento, 1);
  const barra = (valor, cor) => (
    <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 8 }}>
      <div style={{ flex: 1, height: 14, borderRadius: 99, background: 'var(--bg)', overflow: 'hidden' }}>
        <div style={{ width: `${Math.max(2, (valor / max) * 100)}%`, height: '100%', background: cor, borderRadius: 99 }} />
      </div>
      <div style={{ width: 110, textAlign: 'right', fontWeight: 650, color: 'var(--text)' }}>{fatEur(valor)}</div>
    </div>
  );
  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: 10, marginBottom: 16 }}>
      <div style={{ padding: 16, border: '1px solid var(--border)', borderRadius: 10, background: 'var(--bg-elev)' }}>
        <div style={{ fontSize: 10, letterSpacing: '.05em', color: 'var(--text-dim)', fontFamily: 'var(--font-mono)' }}>FATURADO TOTAL</div>
        <div className="font-display" style={{ fontSize: 28, fontWeight: 650, marginTop: 6 }}>{fatEur(total.faturado)}</div>
        <div style={{ fontSize: 12, color: 'var(--text-muted)', marginTop: 4 }}>{fatN(total.wins)} wins · {fatN(total.wins_fatura)} com fatura no lugar de 0 ou 1 €</div>
        {barra(total.faturado, FAT_COR.faturado)}
      </div>
      <div style={{ padding: 16, border: '1px solid var(--border)', borderRadius: 10, background: 'var(--bg-elev)' }}>
        <div style={{ fontSize: 10, letterSpacing: '.05em', color: 'var(--text-dim)', fontFamily: 'var(--font-mono)' }}>INVESTIMENTO TOTAL</div>
        <div className="font-display" style={{ fontSize: 28, fontWeight: 650, marginTop: 6 }}>{fatEur(total.investimento)}</div>
        <div style={{ fontSize: 12, color: 'var(--text-muted)', marginTop: 4 }}>Spend de media registado no portal</div>
        {barra(total.investimento, FAT_COR.investimento)}
      </div>
      <div style={{ padding: 16, border: '1px solid var(--border)', borderRadius: 10, background: 'var(--bg-elev)' }}>
        <div style={{ fontSize: 10, letterSpacing: '.05em', color: 'var(--text-dim)', fontFamily: 'var(--font-mono)' }}>RETORNO</div>
        <div className="font-display" style={{ fontSize: 28, fontWeight: 650, marginTop: 6 }}>{fatRoas(roas)}</div>
        <div style={{ fontSize: 12, color: 'var(--text-muted)', marginTop: 4 }}>{anosSpend ? `Faturado de ${anosSpend} sobre o spend desses anos. Os outros anos entram no faturado e ficam de fora deste retorno.` : 'Ainda não há spend registado para fechar o retorno.'}</div>
      </div>
    </div>
  );
}

function FatAnual({ anos }) {
  const max = Math.max(1, ...anos.map(a => Math.max(a.faturado, a.investimento)));
  const H = 200;
  const groupW = 64;
  const W = Math.max(640, anos.length * groupW + 48);
  const base = 28;
  const plotH = H - base - 8;
  const y = (v) => plotH - (v / max) * plotH;
  const ticks = [0, 0.5, 1].map(p => ({ p, valor: max * p }));
  return (
    <div style={{ border: '1px solid var(--border)', borderRadius: 10, background: 'var(--bg-elev)', padding: 16, marginBottom: 16 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', gap: 12, flexWrap: 'wrap', marginBottom: 8 }}>
        <div className="font-display" style={{ fontSize: 14, fontWeight: 650 }}>Faturado e investimento por ano</div>
        <div style={{ display: 'flex', gap: 14, fontSize: 12, color: 'var(--text-muted)' }}>
          <span><span style={{ display: 'inline-block', width: 10, height: 10, borderRadius: 2, background: FAT_COR.faturado, marginRight: 6 }} />Faturado</span>
          <span><span style={{ display: 'inline-block', width: 10, height: 10, borderRadius: 2, background: FAT_COR.investimento, marginRight: 6 }} />Investimento</span>
        </div>
      </div>
      <div style={{ overflowX: 'auto' }}>
        <svg viewBox={`0 0 ${W} ${H}`} width={W} height={H} role="img" aria-label="Faturado e investimento por ano">
          {ticks.map(t => (
            <g key={t.p}>
              <line x1="36" x2={W - 8} y1={8 + y(t.valor)} y2={8 + y(t.valor)} stroke="var(--border)" strokeDasharray={t.p === 0 ? '' : '3 3'} />
            </g>
          ))}
          {anos.map((a, i) => {
            const x = 44 + i * groupW;
            const hf = Math.max(a.faturado > 0 ? 2 : 0, plotH - y(a.faturado));
            const hi = Math.max(a.investimento > 0 ? 2 : 0, plotH - y(a.investimento));
            return (
              <g key={a.ano}>
                <rect x={x} y={8 + y(a.faturado)} width="18" height={hf} rx="3" fill={FAT_COR.faturado}>
                  <title>{`${a.ano} faturado ${fatEur(a.faturado)}`}</title>
                </rect>
                <rect x={x + 22} y={8 + y(a.investimento)} width="18" height={hi} rx="3" fill={FAT_COR.investimento}>
                  <title>{`${a.ano} investimento ${fatEur(a.investimento)}`}</title>
                </rect>
                <text x={x + 20} y={H - 8} textAnchor="middle" fontSize="11" fill="var(--text-muted)">{a.ano}</text>
              </g>
            );
          })}
        </svg>
      </div>
    </div>
  );
}

function FatTabela({ anos }) {
  const th = { textAlign: 'right', padding: '8px 10px', fontSize: 10, color: 'var(--text-dim)', borderBottom: '1px solid var(--border)', fontFamily: 'var(--font-mono)' };
  const td = { textAlign: 'right', padding: '8px 10px', borderBottom: '1px solid var(--border)', fontSize: 13 };
  return (
    <div style={{ border: '1px solid var(--border)', borderRadius: 10, background: 'var(--bg-elev)', overflow: 'auto' }}>
      <table style={{ width: '100%', borderCollapse: 'collapse' }}>
        <thead>
          <tr>
            <th style={{ ...th, textAlign: 'left' }}>Ano</th>
            <th style={th}>Faturado</th>
            <th style={th}>Investimento</th>
            <th style={th}>Retorno</th>
            <th style={th}>Wins</th>
          </tr>
        </thead>
        <tbody>
          {anos.map(a => (
            <tr key={a.ano}>
              <td style={{ ...td, textAlign: 'left', fontWeight: 650 }}>{a.ano}</td>
              <td style={td}>{fatEur(a.faturado)}</td>
              <td style={td}>{fatEur(a.investimento)}</td>
              <td style={td}>{fatRoas(a.roas)}</td>
              <td style={td}>{fatN(a.wins)}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

function MktResultadosFaturadoScreen({ setSub }) {
  const bp = window.useBreakpoint ? window.useBreakpoint() : { isMobile: false };
  const [data, setData] = React.useState(null);
  const [err, setErr] = React.useState('');
  const [loading, setLoading] = React.useState(true);
  window.useMktZoneLoading && window.useMktZoneLoading(loading && !data);
  React.useEffect(() => {
    let vivo = true;
    fatFetch('/api/marketing/resultados/v2/faturado')
      .then(d => { if (vivo) setData(d); })
      .catch(e => { if (vivo) setErr(e.message); })
      .finally(() => { if (vivo) setLoading(false); });
    return () => { vivo = false; };
  }, []);
  const Trilho = window.ResTrilho;
  const Menu = window.ResMenuAccoes;
  const menu = [
    { id: 'resultados', label: 'Resultados', sub: 'Funil, objectivos e campanhas', onClick: () => setSub && setSub('resultados') },
    { id: 'faturado', label: 'Faturado e investimento', sub: 'Total e série anual', checked: true },
    { id: 'analise', label: 'Análise da Digi AI', sub: 'Leitura, BP e campanhas a fazer', onClick: () => setSub && setSub('resultados-analise') },
    { id: 'mimaki', label: 'Report Mimaki', sub: 'Pipeline das equipas Mimaki em ranks Mimaki', onClick: () => setSub && setSub('resultados-mimaki') },
  ];
  const anos = data?.anos || [];
  const total = data?.total;
  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%', minHeight: 0, background: 'var(--bg)' }}>
      <div style={{ background: 'var(--bg-elev)', borderBottom: '1px solid var(--border)', padding: bp.isMobile ? '16px 16px 14px' : '20px 40px 16px', flexShrink: 0 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', gap: 12, alignItems: 'flex-start' }}>
          <div>
            <div style={{ fontSize: 11, fontWeight: 600, letterSpacing: '0.07em', color: 'var(--text-muted)', textTransform: 'uppercase', marginBottom: 6, fontFamily: 'var(--font-mono)' }}>Marketing · Resultados</div>
            <h1 style={{ margin: 0, fontSize: 21, fontWeight: 700, color: 'var(--text)', fontFamily: 'var(--font-display)' }}>Faturado e investimento</h1>
          </div>
          {Menu ? <Menu icone items={menu} /> : null}
        </div>
      </div>
      <div className="scrollbar" style={{ overflowY: 'auto', flex: 1, minHeight: 0, padding: bp.isMobile ? '18px 16px 64px' : '28px 40px 64px' }}>
        {Trilho && <Trilho segmentos={[{ label: 'Resultados', onClick: () => setSub && setSub('resultados') }, { label: 'Faturado e investimento' }]} />}
        {err && <div style={{ color: 'var(--danger)', fontSize: 13, marginBottom: 12 }}>{err}</div>}
        {loading && !data && <div style={{ color: 'var(--text-muted)', fontSize: 13 }}>A consolidar…</div>}
        {total && (
          <>
            <FatTotal total={total} anos={anos} />
            <FatAnual anos={anos} />
            <FatTabela anos={anos} />
            <div style={{ marginTop: 12, fontSize: 12, color: 'var(--text-muted)', lineHeight: 1.5 }}>
              O ano é o ano de início da win. O faturado usa o valor do Gestor quando é superior a 1 € e, nas wins Decal e Mimaki a 0 ou 1 €, a fatura dos 12 meses seguintes. O investimento é o spend de media desse ano civil. Espanha, Andorra e Mimaki Contact ficam de fora do faturado.
            </div>
          </>
        )}
      </div>
    </div>
  );
}

window.MktResultadosFaturadoScreen = MktResultadosFaturadoScreen;
