/* Marketing · Performance 2025
   Modo "Todas" → portfolio: funnel 3-stream + KPIs + leads-por-marca + ranking ROAS
   Modo single-brand → filtrado: funnel marca + KPIs marca + leads-por-campanha + top produtos */

const fmtEur = (n) => {
  if (n == null) return '—';
  if (n >= 1000000) return '€' + (n/1000000).toFixed(2).replace('.', ',') + 'M';
  if (n >= 1000) return '€' + Math.round(n/1000) + 'k';
  return '€' + n;
};
const fmtN = (n) => n == null ? '—' : new Intl.NumberFormat('pt-PT').format(n);

// ============================================================================
// 3-stream convergent funnel (ADS + EMAIL + WEB → LEADS → MQL → SQL → OPs → WINS)
// ============================================================================
const PerfFunnel = ({ data, color, label }) => {
  // Layout: 3 streams entram à esquerda, convergem para um funnel central
  // SVG ~ 720 × 220
  const W = 720, H = 220;
  const cx = W / 2;

  const streams = [
    { key: 'ads',   label: 'Ads',     color: '#dc2626', y: 30 },
    { key: 'email', label: 'Email',   color: '#059669', y: 110 },
    { key: 'web',   label: 'Website', color: '#6b7280', y: 190 },
  ];

  // Stages no centro e à direita
  const stages = [
    { key: 'leads', label: 'Leads', x: 320, w: 80 },
    { key: 'mql',   label: 'MQL',   x: 420, w: 70 },
    { key: 'sql',   label: 'SQL',   x: 510, w: 60 },
    { key: 'ops',   label: 'OPs',   x: 590, w: 60 },
    { key: 'wins',  label: 'Wins',  x: 670, w: 50 },
  ];

  const maxStream = Math.max(data.ads, data.email, data.web);
  const streamHeight = (v) => 12 + (v / maxStream) * 36;

  return (
    <div style={{
      padding: '16px 20px',
      background: 'var(--bg-elev)',
      border: '1px solid var(--border)',
      borderRadius: 10,
    }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
        <div className="font-display" style={{ fontSize: 14, fontWeight: 600 }}>Funnel · {label}</div>
        <div style={{ fontSize: 10, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', letterSpacing: '0.06em' }}>
          ADS + EMAIL + WEB → WINS
        </div>
      </div>
      <svg viewBox={`0 0 ${W} ${H}`} width="100%" style={{ display: 'block' }}>
        {/* Streams entrando */}
        {streams.map((s, i) => {
          const v = data[s.key];
          const h = streamHeight(v);
          return (
            <g key={s.key}>
              {/* Path: from left edge to first stage */}
              <path
                d={`M 0 ${s.y} L 60 ${s.y} L 320 ${110 - h/2 + (i * h/3)} L 320 ${110 + h/2 + ((i-1) * h/3)} L 60 ${s.y + h/2} L 0 ${s.y + h/2} Z`}
                fill={s.color}
                opacity="0.35"
              />
              {/* Pill: ads/email/web label + count */}
              <rect x="6" y={s.y - 12} width="110" height="32" rx="6" fill="var(--bg-sunken)" stroke={s.color} strokeOpacity="0.4" />
              <circle cx="20" cy={s.y + 4} r="3.5" fill={s.color} />
              <text x="32" y={s.y + 1} fontSize="10" fill="var(--text-dim)" fontFamily="var(--font-mono)" letterSpacing="0.04em">{s.label.toUpperCase()}</text>
              <text x="32" y={s.y + 14} fontSize="13" fontWeight="600" fill="var(--text)" fontFamily="var(--font-display)">{fmtN(v)}</text>
            </g>
          );
        })}

        {/* Stages — funnel narrowing */}
        {stages.map((st, i) => {
          const v = data[st.key];
          const prev = i === 0 ? (data.ads + data.email + data.web) : data[stages[i-1].key];
          const ratio = prev > 0 ? v / prev : 1;
          const h = 30 + 80 * (v / data.leads);
          return (
            <g key={st.key}>
              <rect
                x={st.x} y={110 - h/2}
                width={st.w} height={h}
                rx="6"
                fill={i === stages.length - 1 ? color : `color-mix(in oklch, ${color} ${20 + i * 10}%, var(--bg-sunken))`}
                stroke={i === stages.length - 1 ? color : 'none'}
                strokeWidth="1"
              />
              <text x={st.x + st.w/2} y={110 - h/2 - 6} textAnchor="middle"
                fontSize="9.5" fill="var(--text-dim)" fontFamily="var(--font-mono)" letterSpacing="0.06em">{st.label.toUpperCase()}</text>
              <text x={st.x + st.w/2} y={110 + 4} textAnchor="middle"
                fontSize="15" fontWeight="700" fill={i === stages.length - 1 ? '#fff' : 'var(--text)'} fontFamily="var(--font-display)">{fmtN(v)}</text>
              {i > 0 && (
                <text x={st.x + st.w/2} y={110 + h/2 + 14} textAnchor="middle"
                  fontSize="9" fill="var(--text-dim)" fontFamily="var(--font-mono)">{Math.round(ratio * 100)}%</text>
              )}
            </g>
          );
        })}
      </svg>
    </div>
  );
};

// ============================================================================
// KPIs strip (5 cards)
// ============================================================================
const PerfKpis = ({ kpis }) => (
  <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 10 }}>
    {kpis.map((k, i) => (
      <div key={i} style={{
        padding: '14px 16px',
        background: 'var(--bg-elev)',
        border: '1px solid var(--border)',
        borderRadius: 10,
        position: 'relative',
        overflow: 'hidden',
      }}>
        {k.accentColor && (
          <span style={{
            position: 'absolute', top: 0, left: 0, bottom: 0,
            width: 3, background: k.accentColor,
          }} />
        )}
        <div style={{ fontSize: 9.5, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', letterSpacing: '0.08em', textTransform: 'uppercase' }}>{k.label}</div>
        <div className="font-display" style={{ fontSize: 24, fontWeight: 600, lineHeight: 1.05, margin: '4px 0 4px', letterSpacing: '-0.015em' }}>{k.value}</div>
        <div style={{ fontSize: 11, color: k.tone === 'success' ? 'var(--success)' : k.tone === 'danger' ? 'var(--danger)' : 'var(--text-muted)' }}>{k.sub}</div>
      </div>
    ))}
  </div>
);

// ============================================================================
// "Leads por marca" stacked bar (Todas only) — 7 brands stack horizontalmente
// ============================================================================
const LeadsPorMarcaCard = ({ onPickBrand }) => {
  const brands = (window.MKT_BRANDS || []).filter(b => b.id !== 'todas');
  const numbers = window.MKT_BRAND_NUMBERS || {};
  const total = brands.reduce((a, b) => a + (numbers[b.id]?.leads || 0), 0);

  return (
    <div style={{
      padding: '16px 18px',
      background: 'var(--bg-elev)',
      border: '1px solid var(--border)',
      borderRadius: 10,
    }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 8 }}>
        <div className="font-display" style={{ fontSize: 14, fontWeight: 600 }}>Leads por marca · 2025</div>
        <div style={{ fontSize: 10, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)' }}>Total {fmtN(total)}</div>
      </div>

      {/* Stacked horizontal bar */}
      <div style={{
        display: 'flex', height: 36, borderRadius: 6, overflow: 'hidden',
        border: '1px solid var(--border)', marginBottom: 12,
      }}>
        {brands.map(b => {
          const v = numbers[b.id]?.leads || 0;
          const pct = (v / total) * 100;
          return (
            <button
              key={b.id}
              onClick={() => onPickBrand(b.id)}
              title={`${b.nome}: ${v} leads (${pct.toFixed(1)}%)`}
              style={{
                width: `${pct}%`, height: '100%',
                background: b.cor, border: 'none', cursor: 'pointer',
                transition: 'opacity 0.15s', position: 'relative',
              }}
              onMouseEnter={e => e.currentTarget.style.opacity = '0.85'}
              onMouseLeave={e => e.currentTarget.style.opacity = '1'}
            >
              {pct > 8 && (
                <span style={{
                  position: 'absolute', inset: 0,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  fontSize: 10.5, fontWeight: 600, color: '#fff',
                  fontFamily: 'var(--font-display)',
                  letterSpacing: '0.02em',
                  textShadow: '0 1px 2px rgba(0,0,0,0.3)',
                }}>{b.nome}</span>
              )}
            </button>
          );
        })}
      </div>

      {/* Legend */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: '4px 16px' }}>
        {brands.map(b => {
          const v = numbers[b.id]?.leads || 0;
          const pct = (v / total) * 100;
          return (
            <button key={b.id} onClick={() => onPickBrand(b.id)} style={{
              display: 'flex', alignItems: 'center', gap: 8, padding: '4px 0',
              border: 'none', background: 'transparent', cursor: 'pointer', textAlign: 'left',
            }}>
              <span style={{ width: 8, height: 8, borderRadius: '50%', background: b.cor, flexShrink: 0 }} />
              <span style={{ fontSize: 12, flex: 1 }}>{b.nome}</span>
              <span className="font-mono" style={{ fontSize: 11, color: 'var(--text-muted)' }}>{v} · {pct.toFixed(1)}%</span>
            </button>
          );
        })}
      </div>
    </div>
  );
};

// ============================================================================
// Top marcas por ROAS (ranking) — Todas only
// ============================================================================
const RankingROAS = ({ onPickBrand }) => {
  const brands = (window.MKT_BRANDS || []).filter(b => b.id !== 'todas');
  const numbers = window.MKT_BRAND_NUMBERS || {};
  const ranked = brands
    .map(b => ({ ...b, roas: numbers[b.id]?.roas || 0, fat: numbers[b.id]?.faturacao || 0 }))
    .sort((a, b) => b.roas - a.roas);
  const maxRoas = ranked[0]?.roas || 1;

  return (
    <div style={{
      padding: '16px 18px',
      background: 'var(--bg-elev)',
      border: '1px solid var(--border)',
      borderRadius: 10,
    }}>
      <div className="font-display" style={{ fontSize: 14, fontWeight: 600, marginBottom: 12 }}>Top marcas por ROAS</div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
        {ranked.map((b, i) => (
          <button key={b.id} onClick={() => onPickBrand(b.id)} style={{
            display: 'grid', gridTemplateColumns: '24px 1fr 60px 60px', gap: 10,
            alignItems: 'center', padding: '6px 8px', borderRadius: 6,
            border: 'none', background: 'transparent', cursor: 'pointer', textAlign: 'left',
            transition: 'background 0.12s',
          }}
          onMouseEnter={e => e.currentTarget.style.background = 'var(--bg-hover)'}
          onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
            <span style={{ fontSize: 11, fontFamily: 'var(--font-mono)', color: 'var(--text-dim)', fontWeight: 700 }}>{String(i+1).padStart(2, '0')}</span>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, minWidth: 0 }}>
              <span style={{ width: 8, height: 8, borderRadius: '50%', background: b.cor, flexShrink: 0 }} />
              <span style={{ fontSize: 12.5, fontWeight: 500, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{b.nome}</span>
            </div>
            <div style={{ height: 8, background: 'var(--bg-sunken)', borderRadius: 3, overflow: 'hidden' }}>
              <div style={{ height: '100%', width: `${(b.roas / maxRoas) * 100}%`, background: b.cor, borderRadius: 3 }} />
            </div>
            <span className="font-mono" style={{ fontSize: 12, fontWeight: 600, textAlign: 'right' }}>{b.roas.toFixed(1)}×</span>
          </button>
        ))}
      </div>
      <div style={{ fontSize: 10.5, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', marginTop: 8, paddingTop: 8, borderTop: '1px solid var(--border)' }}>
        ROAS = Faturação / Investimento Ads · 2025
      </div>
    </div>
  );
};

// ============================================================================
// Single-brand: Leads por campanha
// ============================================================================
const LeadsPorCampanha = ({ brandId, color }) => {
  const camps = (window.MKT_BRAND_CAMPAIGNS || {})[brandId] || [];
  if (!camps.length) return null;
  const max = Math.max(...camps.map(c => c.leads));
  return (
    <div style={{
      padding: '16px 18px',
      background: 'var(--bg-elev)',
      border: '1px solid var(--border)',
      borderRadius: 10,
    }}>
      <div className="font-display" style={{ fontSize: 14, fontWeight: 600, marginBottom: 12 }}>Leads por campanha</div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        {camps.map((c, i) => (
          <div key={i} style={{ display: 'grid', gridTemplateColumns: '1fr 100px 60px 60px', gap: 10, alignItems: 'center', padding: '4px 0', borderBottom: i < camps.length - 1 ? '1px solid var(--border-subtle)' : 'none' }}>
            <div style={{ minWidth: 0 }}>
              <div style={{ fontSize: 12.5, fontWeight: 500, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{c.nome}</div>
              <div style={{ fontSize: 10.5, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)' }}>{c.canal}</div>
            </div>
            <div style={{ height: 8, background: 'var(--bg-sunken)', borderRadius: 3, overflow: 'hidden' }}>
              <div style={{ height: '100%', width: `${(c.leads / max) * 100}%`, background: color, borderRadius: 3 }} />
            </div>
            <span className="font-mono" style={{ fontSize: 12, fontWeight: 600, textAlign: 'right' }}>{c.leads}</span>
            <span className="font-mono" style={{ fontSize: 11, color: c.roas > 0 ? 'var(--success)' : 'var(--text-dim)', textAlign: 'right' }}>
              {c.roas > 0 ? `${c.roas.toFixed(1)}×` : c.status === 'organic' ? 'orgânico' : '—'}
            </span>
          </div>
        ))}
      </div>
    </div>
  );
};

// ============================================================================
// Single-brand: Top 5 produtos
// ============================================================================
const TopProdutos = ({ brandId, color, brandNome }) => {
  const prods = (window.MKT_BRAND_PRODUCTS || {})[brandId] || [];
  if (!prods.length) return null;
  const max = Math.max(...prods.map(p => p.leads));
  return (
    <div style={{
      padding: '16px 18px',
      background: 'var(--bg-elev)',
      border: '1px solid var(--border)',
      borderRadius: 10,
    }}>
      <div className="font-display" style={{ fontSize: 14, fontWeight: 600, marginBottom: 12 }}>Top produtos {brandNome} por leads</div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
        {prods.slice(0, 5).map((p, i) => (
          <div key={i} style={{ display: 'grid', gridTemplateColumns: '24px 1fr 60px 80px', gap: 10, alignItems: 'center', padding: '4px 6px' }}>
            <span style={{ fontSize: 11, fontFamily: 'var(--font-mono)', color: 'var(--text-dim)', fontWeight: 700 }}>{String(i+1).padStart(2, '0')}</span>
            <span style={{ fontSize: 12.5, fontWeight: 500 }}>{p.nome}</span>
            <div style={{ height: 8, background: 'var(--bg-sunken)', borderRadius: 3, overflow: 'hidden' }}>
              <div style={{ height: '100%', width: `${(p.leads / max) * 100}%`, background: color, borderRadius: 3 }} />
            </div>
            <span className="font-mono" style={{ fontSize: 12, fontWeight: 600, textAlign: 'right' }}>{p.leads} leads</span>
          </div>
        ))}
      </div>
      <div style={{ fontSize: 10.5, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', marginTop: 10, paddingTop: 8, borderTop: '1px solid var(--border)' }}>
        Ticket médio do top: {fmtEur(prods.slice(0, 5).reduce((a, p) => a + (p.ticket || 0), 0) / 5)}
      </div>
    </div>
  );
};

// ============================================================================
// MAIN
// ============================================================================
const MktPerformance = ({ onOpenChat }) => {
  const { brand, brandObj, isAll, setBrand } = window.useMktBrand();
  const numbers = window.MKT_BRAND_NUMBERS || {};
  const funnel = (window.MKT_BRAND_FUNNEL || {})[brand];

  // KPIs portfolio
  const kpisAll = [
    { label: 'Leads', value: '975', sub: '+18% vs 2024', tone: 'success' },
    { label: 'OPs', value: '458', sub: '47% conversão lead→OP', tone: null },
    { label: 'Wins', value: '25', sub: '5,5% de OPs convertidas', tone: null },
    { label: 'Faturação', value: '€802k', sub: 'Ticket médio €32k', tone: null },
    { label: 'ROAS médio', value: '78×', sub: 'Mimaki puxa o valor', tone: 'success', accentColor: 'var(--success)' },
  ];

  // KPIs single-brand
  const kpisBrand = brand !== 'todas' && numbers[brand] ? [
    { label: 'Leads', value: fmtN(numbers[brand].leads), sub: brandObj.tagline, tone: null, accentColor: brandObj.cor },
    { label: 'OPs', value: fmtN(numbers[brand].ops), sub: `${Math.round((numbers[brand].ops / numbers[brand].leads) * 100)}% conversão`, tone: null },
    { label: 'Wins', value: fmtN(numbers[brand].wins), sub: numbers[brand].ops > 0 ? `${Math.round((numbers[brand].wins / numbers[brand].ops) * 100)}% de OPs` : '—', tone: null },
    { label: 'Faturação', value: fmtEur(numbers[brand].faturacao), sub: numbers[brand].wins > 0 ? `Ticket médio ${fmtEur(numbers[brand].faturacao / numbers[brand].wins)}` : '—', tone: null },
    { label: 'CPL · ROAS', value: `€${numbers[brand].cpl.toFixed(2)}`, sub: numbers[brand].roas > 0 ? `${numbers[brand].roas.toFixed(1)}× ROAS` : 'Sem ROAS (institucional)', tone: numbers[brand].roas > 50 ? 'success' : null, accentColor: numbers[brand].roas > 50 ? 'var(--success)' : null },
  ] : [];

  return (
    <div className="scrollbar" style={{ padding: '20px 24px 80px', height: '100%', overflowY: 'auto' }}>
      <div style={{ fontSize: 11, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', letterSpacing: '0.08em' }}>
        MARKETING · PERFORMANCE 2025 {!isAll && <>· <span style={{ color: brandObj.cor }}>{brandObj.nome.toUpperCase()}</span></>}
      </div>
      <h2 className="font-display" style={{ margin: '6px 0 4px', fontSize: 28, fontWeight: 500, letterSpacing: '-0.01em', display: 'flex', alignItems: 'center', gap: 10 }}>
        Performance
        {!isAll && (
          <span style={{
            fontSize: 14, padding: '4px 10px', borderRadius: 6,
            background: `color-mix(in oklch, ${brandObj.cor} 18%, transparent)`,
            color: brandObj.cor, fontWeight: 600, letterSpacing: '0.02em',
          }}>{brandObj.nome}</span>
        )}
        <span style={{ color: 'var(--text-muted)', fontSize: 22 }}>· 2025</span>
      </h2>
      <div style={{ fontSize: 12, color: 'var(--text-muted)', marginBottom: 18 }}>
        {isAll
          ? `Vista consolidada das 7 marcas · 12 campanhas activas · ROAS médio 78× (Mimaki puxa o valor)`
          : `${brandObj.descricao}`}
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
        <PerfKpis kpis={isAll ? kpisAll : kpisBrand} />

        <PerfFunnel
          data={funnel}
          color={isAll ? 'var(--brand-900)' : brandObj.cor}
          label={isAll ? 'Portfolio · 2025' : `${brandObj.nome} · 2025`}
        />

        <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 14 }}>
          {isAll ? (
            <>
              <LeadsPorMarcaCard onPickBrand={setBrand} />
              <RankingROAS onPickBrand={setBrand} />
            </>
          ) : (
            <>
              <LeadsPorCampanha brandId={brand} color={brandObj.cor} />
              <TopProdutos brandId={brand} color={brandObj.cor} brandNome={brandObj.nome} />
            </>
          )}
        </div>

        {/* Digi insight */}
        <div className="ai-surface" style={{ padding: 16, borderRadius: 10, fontSize: 13, lineHeight: 1.6 }}>
          <span className="ai-chip"><span className="ai-dot" />Digi · Marketing</span>
          {isAll ? (
            <p style={{ margin: '10px 0 0' }}>
              Mimaki gerou <strong>{Math.round(412/975*100)}%</strong> dos leads e Mimaki+Decal+BIOND somam <strong>76%</strong>. Concentração saudável. <strong style={{ color: 'var(--warning)' }}>Sensek</strong> com 2,5% dos leads e CPL €33 — desproporcional, recomendo plano awareness 2026 ou pause total. <strong>Decal</strong> com ROAS 88× é a marca mais eficiente em capital — vale duplicar investimento Q1.
            </p>
          ) : (
            <p style={{ margin: '10px 0 0' }}>
              Para <strong style={{ color: brandObj.cor }}>{brandObj.nome}</strong>: {numbers[brand]?.roas > 50
                ? `ROAS ${numbers[brand].roas.toFixed(1)}× confirma aposta. CPL €${numbers[brand].cpl.toFixed(2)} dentro do esperado para o canal dominante. Recomendo manter mix 2026.`
                : numbers[brand]?.roas > 0
                  ? `ROAS ${numbers[brand].roas.toFixed(1)}× abaixo da média Digidelta (78×). Auditar criativos e reduzir gasto em Meta antes de Q1 2026.`
                  : `Marca institucional — métricas comerciais não aplicam. Focar em employer brand e share-of-voice.`}
            </p>
          )}
        </div>
      </div>
    </div>
  );
};

window.MktPerformance = MktPerformance;
