/* Análise de campanhas Meta. Sub-módulo de Marketing.
   Abre a partir da Activação ou da barra lateral. Cada corrida fica em activacao_analise_meta. */

const AN_AREA = { setup: 'Setup', copy: 'Copy', criativo: 'Criativo' };
const AN_PRIO = { p0: 'Agora', p1: 'Seguinte', p2: 'Depois' };
const AN_LIGHT = {
  verde: { color: '#166534', bg: '#DCFCE7' },
  amarelo: { color: '#92400E', bg: '#FEF3C7' },
  vermelho: { color: '#B91C1C', bg: '#FEE2E2' },
};
const AN_LIGACAO = { criativo: 'Abrir criativo', publico: 'Abrir público', formulario: 'Abrir formulário', orcamento: 'Abrir orçamento' };

function anParseHash() {
  const params = new URLSearchParams(String(window.location.hash || '').replace(/^#/, ''));
  return {
    camp: params.get('analise') || null,
    correr: params.get('correr') === '1',
    registo: params.get('registo') || null,
  };
}

function anWriteHash({ camp, correr, registo }, { replace } = {}) {
  const params = new URLSearchParams(String(window.location.hash || '').replace(/^#/, ''));
  params.set('screen', 'marketing');
  params.set('sub', 'analise-campanhas');
  if (camp) params.set('analise', camp); else params.delete('analise');
  if (correr) params.set('correr', '1'); else params.delete('correr');
  if (registo) params.set('registo', registo); else params.delete('registo');
  params.delete('camp');
  params.delete('canal');
  params.delete('tab');
  const next = params.toString();
  if (replace) {
    const url = `${window.location.pathname}${window.location.search}#${next}`;
    window.history.replaceState(null, '', url);
    return;
  }
  window.location.hash = next;
}

function anClearOwnHash() {
  const params = new URLSearchParams(String(window.location.hash || '').replace(/^#/, ''));
  if (!params.has('analise') && !params.has('correr') && !params.has('registo')) return;
  if (params.get('sub') === 'analise-campanhas') return;
  params.delete('analise');
  params.delete('correr');
  params.delete('registo');
  const next = params.toString();
  const url = `${window.location.pathname}${window.location.search}${next ? `#${next}` : ''}`;
  window.history.replaceState(null, '', url);
}

function anIrSetup(campId, tab) {
  const params = new URLSearchParams(String(window.location.hash || '').replace(/^#/, ''));
  params.set('screen', 'marketing');
  params.set('sub', 'publicacao');
  params.set('camp', campId);
  params.set('canal', 'meta_ads');
  if (tab) params.set('tab', tab); else params.delete('tab');
  params.delete('analise');
  params.delete('correr');
  params.delete('registo');
  window.location.hash = params.toString();
}

function anIrCriativo(campId) {
  if (window.mktNavToSub) window.mktNavToSub('conteudos');
  setTimeout(() => { if (window.mktProducaoOpenCampanha) window.mktProducaoOpenCampanha(campId); }, 200);
}

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

function anQuando(iso) {
  if (!iso) return '';
  const d = new Date(iso);
  if (Number.isNaN(d.getTime())) return '';
  return d.toLocaleString('pt-PT', { day: '2-digit', month: 'short', hour: '2-digit', minute: '2-digit' });
}

const AnBarra = ({ label, real, alvo, sub, light }) => {
  const r = Number(real) || 0;
  const a = Number(alvo) || 0;
  const pct = a > 0 ? Math.max(r > 0 ? 3 : 0, Math.min(100, Math.round((r / a) * 100))) : 0;
  const tom = AN_LIGHT[light] || { color: '#3859D0', bg: '#e8eef8' };
  const realTxt = Number.isFinite(Number(real)) ? Number(real).toLocaleString('pt-PT', { maximumFractionDigits: 1 }) : '—';
  const alvoTxt = Number.isFinite(Number(alvo)) ? Number(alvo).toLocaleString('pt-PT', { maximumFractionDigits: 0 }) : '—';
  return (
    <div style={{ marginBottom: 12 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', gap: 12, fontSize: 12, marginBottom: 4 }}>
        <span style={{ color: 'var(--text-muted)' }}>{label}</span>
        <span style={{ fontWeight: 700, color: tom.color, fontVariantNumeric: 'tabular-nums' }}>
          {realTxt}<span style={{ fontWeight: 500, color: '#6b7fa3' }}> / {alvoTxt}</span>
        </span>
      </div>
      <div style={{ height: 6, borderRadius: 99, background: '#eef2f8', overflow: 'hidden' }}>
        <div style={{ width: `${pct}%`, height: '100%', background: tom.color, borderRadius: 99 }} />
      </div>
      {sub && <div style={{ fontSize: 11, color: '#6b7fa3', marginTop: 3 }}>{sub}</div>}
    </div>
  );
};

function anBarras(sem) {
  const etapas = sem?.etapas || [];
  const barras = [];
  if (sem?.entrega) {
    barras.push({
      key: 'gasto', label: 'Gasto à data', real: sem.entrega.spend_eur, alvo: sem.entrega.esperado_eur, light: 'vermelho',
      sub: `${Math.round(sem.investimento_eur || 0)} € na janela · ritmo ${sem.entrega.ritmo_pct}%`,
    });
  } else if (sem?.investimento_eur != null && sem?.spend_eur != null) {
    barras.push({
      key: 'gasto', label: 'Gasto', real: sem.spend_eur, alvo: sem.investimento_eur, light: 'amarelo',
      sub: 'face ao investimento da janela',
    });
  }
  if (sem?.leads_meta && sem.leads_meta.esperado != null) {
    barras.push({
      key: 'leads_meta', label: 'Leads Meta à data', real: sem.leads_meta.real ?? 0, alvo: sem.leads_meta.esperado, light: sem.leads_meta.light,
      sub: sem.leads_meta.objectivo ? `objectivo da janela ${sem.leads_meta.objectivo}` : null,
    });
  }
  etapas.filter(e => e.key !== 'leads' || !sem?.leads_meta).forEach(e => {
    barras.push({
      key: e.key, label: `${e.label || e.key} à data`, real: e.real,
      alvo: e.esperado != null ? e.esperado : e.objectivo, light: e.light,
      sub: e.esperado != null && e.objectivo ? `objectivo da janela ${Number(e.objectivo).toLocaleString('pt-PT')}` : null,
    });
  });
  return barras;
}

const AnLista = ({ campanhas, onAbrir }) => (
  <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
    {campanhas.map(c => {
      const tom = AN_LIGHT[c.leads_light] || null;
      return (
        <button
          key={c.campanha_id}
          type="button"
          onClick={() => onAbrir(c)}
          style={{
            textAlign: 'left', background: 'var(--bg-elev, #fff)', border: '1px solid var(--border, #dde3ef)',
            borderRadius: 12, padding: '14px 16px', cursor: 'pointer', fontFamily: 'inherit', color: 'inherit',
          }}
        >
          <div style={{ display: 'flex', justifyContent: 'space-between', gap: 12, alignItems: 'baseline' }}>
            <div style={{ minWidth: 0 }}>
              <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: '0.06em', color: '#3859D0', fontFamily: 'var(--font-mono)', textTransform: 'uppercase' }}>
                {(c.brand_name || c.brand_slug || 'Meta Ads')}
                {String(c.draft_status || '').toUpperCase() === 'ACTIVE' ? ' · no ar' : ''}
              </div>
              <div style={{ fontSize: 16, fontWeight: 700, color: 'var(--text, #283252)', marginTop: 2 }}>{c.titulo || 'Campanha'}</div>
            </div>
            <span style={{ fontSize: 12, color: '#3859D0', fontWeight: 700, flexShrink: 0 }}>{c.analise_id ? 'Abrir →' : 'Analisar →'}</span>
          </div>
          <div style={{ fontSize: 13, color: 'var(--text-muted)', marginTop: 8, lineHeight: 1.4 }}>
            {c.leitura || 'Ainda sem análise gravada.'}
          </div>
          <div style={{ display: 'flex', gap: 10, marginTop: 8, fontSize: 11, color: '#6b7fa3', flexWrap: 'wrap' }}>
            {c.criado_em && <span>{anQuando(c.criado_em)}</span>}
            {c.leads_real != null && c.leads_esperado != null && (
              <span style={{ color: tom?.color || '#6b7fa3', fontWeight: 700 }}>
                {c.leads_real} leads Meta / {c.leads_esperado} esperados
              </span>
            )}
          </div>
        </button>
      );
    })}
  </div>
);

const AnDetalhe = ({ hash, onBack }) => {
  const [data, setData] = React.useState(null);
  const [hist, setHist] = React.useState([]);
  const [erro, setErro] = React.useState(null);
  const [loading, setLoading] = React.useState(true);

  React.useEffect(() => {
    let alive = true;
    setLoading(true);
    setErro(null);
    const url = (!hash.correr && hash.registo)
      ? `/api/marketing/activacao/analises-meta/${encodeURIComponent(hash.registo)}`
      : `/api/marketing/activacao/campanha/${encodeURIComponent(hash.camp)}/analise-meta`;
    anFetch(url)
      .then(d => {
        if (!alive) return;
        setData(d);
        if (hash.correr && d.registo_id) anWriteHash({ camp: hash.camp, registo: d.registo_id }, { replace: true });
      })
      .catch(e => { if (alive) setErro(e.message); })
      .finally(() => { if (alive) setLoading(false); });
    return () => { alive = false; };
  }, [hash.camp, hash.correr, hash.registo]);

  React.useEffect(() => {
    let alive = true;
    anFetch(`/api/marketing/activacao/campanha/${encodeURIComponent(hash.camp)}/analises-meta`)
      .then(d => { if (alive) setHist(d.analises || []); })
      .catch(() => {});
    return () => { alive = false; };
  }, [hash.camp, data?.registo_id]);

  const sem = data?.semaforo || {};
  const melhorias = data?.melhorias || [];
  const barras = anBarras(sem);
  const ligar = (ligacao) => {
    if (ligacao === 'criativo') anIrCriativo(hash.camp);
    else if (ligacao === 'publico') anIrSetup(hash.camp, 'publicos');
    else if (ligacao === 'formulario') anIrSetup(hash.camp, 'form');
    else if (ligacao === 'orcamento') anIrSetup(hash.camp, 'orcamento');
  };

  return (
    <>
      <div style={{ background: '#fff', borderBottom: '1px solid #ECEFF5', padding: '16px 40px 16px', flexShrink: 0 }}>
        <button type="button" onClick={onBack} style={{ border: 0, background: 'none', color: '#3859D0', fontWeight: 650, fontSize: 12, cursor: 'pointer', padding: 0, marginBottom: 8 }}>
          ← Campanhas
        </button>
        <div style={{ fontSize: 11, fontWeight: 600, letterSpacing: '0.07em', color: '#94A4C4', textTransform: 'uppercase', marginBottom: 6, fontFamily: 'var(--font-mono)' }}>
          MARKETING · ANÁLISE DE CAMPANHAS
        </div>
        <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 16 }}>
          <div style={{ minWidth: 0 }}>
            <h1 style={{ margin: 0, fontSize: 21, fontWeight: 700, color: '#283252', fontFamily: 'var(--font-display)', letterSpacing: '-0.01em' }}>
              {data?.titulo || (loading ? 'A analisar…' : 'Campanha')}
            </h1>
            <div style={{ fontSize: 12, color: '#94A4C4', marginTop: 6 }}>
              {(data?.brand_nome || data?.brand_slug || 'Meta Ads')}
              {data?.criado_em ? ` · ${anQuando(data.criado_em)}` : ''}
              {data?.modelo ? ` · ${data.modelo}` : ''}
            </div>
          </div>
          <button
            type="button"
            className="btn btn-sm"
            disabled={loading}
            onClick={() => anWriteHash({ camp: hash.camp, correr: true })}
            style={{ fontSize: 12 }}
          >Actualizar análise</button>
        </div>
      </div>
      <div className="scrollbar" style={{ flex: 1, minHeight: 0, overflowY: 'auto', padding: '24px 40px 48px', background: 'var(--bg, #f8fafc)' }}>
        {loading && <div style={{ color: 'var(--text-muted)', fontSize: 13 }}>A ler a campanha e os objectivos da Aprovação…</div>}
        {erro && <div style={{ color: '#B91C1C', fontSize: 13 }}>{erro}</div>}
        {data && !loading && (
          <div className="an-grid" style={{ display: 'grid', gridTemplateColumns: 'minmax(0, 1.4fr) minmax(260px, 0.8fr)', gap: 20, alignItems: 'start' }}>
            <div>
              {!sem.congelado && (
                <div style={{ fontSize: 12, color: '#92400E', background: '#FEF3C7', borderRadius: 8, padding: '8px 10px', marginBottom: 12 }}>
                  Os objectivos não foram fechados na Aprovação. A leitura usa os números da Meta e os intervalos de boa performance.
                </div>
              )}
              {data.leitura && <p style={{ margin: '0 0 16px', fontSize: 15, lineHeight: 1.5, color: '#112954' }}>{data.leitura}</p>}
              {melhorias.map((m, i) => {
                const prio = AN_PRIO[m.prioridade] || m.prioridade;
                const prioTom = m.prioridade === 'p0' ? AN_LIGHT.vermelho : m.prioridade === 'p1' ? AN_LIGHT.amarelo : { color: '#4a5e7a', bg: '#f1f5f9' };
                return (
                  <div key={i} style={{ background: '#fff', border: '1px solid #e6ebf4', borderRadius: 12, padding: '14px 14px 12px', marginBottom: 8 }}>
                    <div style={{ display: 'flex', gap: 6, alignItems: 'center', marginBottom: 6 }}>
                      <span style={{ fontSize: 10, fontWeight: 700, fontFamily: 'var(--font-mono)', color: prioTom.color, background: prioTom.bg, borderRadius: 4, padding: '2px 6px' }}>{prio}</span>
                      <span style={{ fontSize: 10, fontWeight: 700, letterSpacing: '0.04em', color: '#3859D0', fontFamily: 'var(--font-mono)' }}>{AN_AREA[m.area] || m.area}</span>
                    </div>
                    <div style={{ fontSize: 15, fontWeight: 650, color: '#112954', lineHeight: 1.35 }}>{m.o_que_mudar}</div>
                    {m.porque && <div style={{ fontSize: 13, color: '#4a5e7a', marginTop: 4, lineHeight: 1.45 }}>{m.porque}</div>}
                    {m.ligacao && AN_LIGACAO[m.ligacao] && (
                      <button type="button" onClick={() => ligar(m.ligacao)} style={{ marginTop: 8, border: 0, background: 'none', color: '#3859D0', fontWeight: 650, fontSize: 12, cursor: 'pointer', padding: 0 }}>
                        {AN_LIGACAO[m.ligacao]} →
                      </button>
                    )}
                  </div>
                );
              })}
              {!melhorias.length && <div style={{ fontSize: 13, color: '#4a5e7a' }}>Sem correcções automáticas para esta campanha.</div>}
              <div style={{ marginTop: 12, fontSize: 11, color: '#94A4C4', lineHeight: 1.4 }}>
                Sugestão. Esta análise não altera a campanha na Meta. Fica gravada para o histórico dos agentes.
                {data.nota ? ` ${data.nota}` : ''}
              </div>
            </div>
            <div>
              {barras.length > 0 && (
                <div style={{ background: '#fff', border: '1px solid #e6ebf4', borderRadius: 12, padding: '14px 14px 6px', marginBottom: 12 }}>
                  <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.06em', color: '#94A4C4', fontFamily: 'var(--font-mono)', marginBottom: 12 }}>FACE AO ESPERADO À DATA</div>
                  {barras.map(b => <AnBarra key={b.key} {...b} />)}
                </div>
              )}
              {hist.length > 1 && (
                <div style={{ background: '#fff', border: '1px solid #e6ebf4', borderRadius: 12, padding: '14px' }}>
                  <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.06em', color: '#94A4C4', fontFamily: 'var(--font-mono)', marginBottom: 8 }}>ANÁLISES ANTERIORES</div>
                  {hist.map(h => (
                    <button
                      key={h.id}
                      type="button"
                      onClick={() => anWriteHash({ camp: hash.camp, registo: h.id })}
                      style={{
                        display: 'block', width: '100%', textAlign: 'left', border: 0, borderTop: '1px solid #eef2f8',
                        background: h.id === data.registo_id ? '#f8fafc' : '#fff', cursor: 'pointer', padding: '8px 0', fontFamily: 'inherit',
                      }}
                    >
                      <div style={{ fontSize: 11, color: '#6b7fa3' }}>{anQuando(h.criado_em)}</div>
                      <div style={{ fontSize: 12, color: '#112954', marginTop: 2, lineHeight: 1.35 }}>{h.leitura}</div>
                    </button>
                  ))}
                </div>
              )}
            </div>
          </div>
        )}
      </div>
    </>
  );
};

const MktAnaliseCampanhasScreen = () => {
  const [hash, setHash] = React.useState(anParseHash);
  const [lista, setLista] = React.useState(null);
  const [erro, setErro] = React.useState(null);

  React.useEffect(() => {
    const params = new URLSearchParams(String(window.location.hash || '').replace(/^#/, ''));
    if (params.get('sub') === 'analise-campanhas' && params.get('screen') === 'marketing') return;
    params.set('screen', 'marketing');
    params.set('sub', 'analise-campanhas');
    params.delete('analise');
    params.delete('correr');
    params.delete('registo');
    params.delete('camp');
    params.delete('canal');
    window.location.hash = params.toString();
  }, []);

  React.useEffect(() => {
    const onHash = () => setHash(anParseHash());
    window.addEventListener('hashchange', onHash);
    return () => {
      window.removeEventListener('hashchange', onHash);
      anClearOwnHash();
    };
  }, []);

  React.useEffect(() => {
    if (hash.camp) return;
    let alive = true;
    anFetch('/api/marketing/activacao/analises-meta')
      .then(d => { if (alive) setLista(d.campanhas || []); })
      .catch(e => { if (alive) setErro(e.message); });
    return () => { alive = false; };
  }, [hash.camp]);

  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
      <style>{`@media (max-width: 900px) { .an-grid { grid-template-columns: 1fr !important; } }`}</style>
      {hash.camp
        ? <AnDetalhe hash={hash} onBack={() => anWriteHash({})} />
        : (
          <>
            <div style={{ background: '#fff', borderBottom: '1px solid #ECEFF5', padding: '16px 40px 18px', flexShrink: 0 }}>
              <div style={{ fontSize: 11, fontWeight: 600, letterSpacing: '0.07em', color: '#94A4C4', textTransform: 'uppercase', marginBottom: 6, fontFamily: 'var(--font-mono)' }}>
                MARKETING · ANÁLISE DE CAMPANHAS
              </div>
              <h1 style={{ margin: 0, fontSize: 21, fontWeight: 700, color: '#283252', fontFamily: 'var(--font-display)', letterSpacing: '-0.01em' }}>
                Análise de campanhas
              </h1>
              <div style={{ fontSize: 13, color: '#6b7fa3', marginTop: 6 }}>Campanhas Meta no ar e o histórico das análises gravadas.</div>
            </div>
            <div className="scrollbar" style={{ flex: 1, minHeight: 0, overflowY: 'auto', padding: '24px 40px 48px', background: 'var(--bg, #f8fafc)' }}>
              {erro && <div style={{ color: '#B91C1C', fontSize: 13 }}>{erro}</div>}
              {lista == null && !erro && <div style={{ color: 'var(--text-muted)', fontSize: 13 }}>A carregar campanhas…</div>}
              {lista && lista.length === 0 && <div style={{ color: 'var(--text-muted)', fontSize: 14 }}>Ainda não há campanhas Meta no ar nem análises gravadas.</div>}
              {lista && lista.length > 0 && (
                <AnLista
                  campanhas={lista}
                  onAbrir={c => anWriteHash({ camp: c.campanha_id, registo: c.analise_id || null, correr: !c.analise_id })}
                />
              )}
            </div>
          </>
        )}
    </div>
  );
};

window.MktAnaliseCampanhasScreen = MktAnaliseCampanhasScreen;
