/* Marketing · Estratégia
   Modo "Todas" → matrix (cada marca = linha; pilares = colunas)
   Modo single-brand → canvas: positioning + personas + channel donut + competitors + OKRs */

// ============================================================================
// Donut chart (channel mix) — para single-brand
// ============================================================================
const ChannelDonut = ({ channels }) => {
  const total = channels.reduce((a, c) => a + c[1], 0);
  let cumAngle = -90;
  const R = 60, r = 38, cx = 80, cy = 80;
  const arcs = channels.map(([label, pct, leads, color]) => {
    const angle = (pct / total) * 360;
    const start = cumAngle;
    const end = start + angle;
    const startRad = (start * Math.PI) / 180;
    const endRad = (end * Math.PI) / 180;
    const x1 = cx + R * Math.cos(startRad);
    const y1 = cy + R * Math.sin(startRad);
    const x2 = cx + R * Math.cos(endRad);
    const y2 = cy + R * Math.sin(endRad);
    const x3 = cx + r * Math.cos(endRad);
    const y3 = cy + r * Math.sin(endRad);
    const x4 = cx + r * Math.cos(startRad);
    const y4 = cy + r * Math.sin(startRad);
    const large = angle > 180 ? 1 : 0;
    const path = `M ${x1} ${y1} A ${R} ${R} 0 ${large} 1 ${x2} ${y2} L ${x3} ${y3} A ${r} ${r} 0 ${large} 0 ${x4} ${y4} Z`;
    cumAngle = end;
    return { label, pct, leads, color, path };
  });

  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
      <svg width="160" height="160" viewBox="0 0 160 160" style={{ flexShrink: 0 }}>
        {arcs.map((a, i) => <path key={i} d={a.path} fill={a.color} />)}
        <text x={cx} y={cy - 4} textAnchor="middle" fontSize="11" fill="var(--text-dim)" fontFamily="var(--font-mono)">CANAIS</text>
        <text x={cx} y={cy + 12} textAnchor="middle" fontSize="18" fontWeight="700" fill="var(--text)" fontFamily="var(--font-display)">{channels.length}</text>
      </svg>
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: 6 }}>
        {arcs.map((a, i) => (
          <div key={i} style={{ display: 'grid', gridTemplateColumns: '12px 1fr 50px 50px', gap: 8, alignItems: 'center' }}>
            <span style={{ width: 10, height: 10, borderRadius: 2, background: a.color }} />
            <span style={{ fontSize: 12, fontWeight: 500 }}>{a.label}</span>
            <span className="font-mono" style={{ fontSize: 11, color: 'var(--text-muted)', textAlign: 'right' }}>{a.pct}%</span>
            <span className="font-mono" style={{ fontSize: 11, fontWeight: 600, textAlign: 'right' }}>{a.leads}</span>
          </div>
        ))}
      </div>
    </div>
  );
};

// ============================================================================
// Estratégia · Matrix (Todas) — 7 brands × 5 pilares
// ============================================================================
const EstrategiaMatrix = ({ onPickBrand }) => {
  const brands = (window.MKT_BRANDS || []).filter(b => b.id !== 'todas');
  const personasMap = window.MKT_BRAND_PERSONAS || {};
  const channelsMap = window.MKT_BRAND_CHANNELS || {};
  const okrsMap = window.MKT_BRAND_OKRS || {};

  const summarisePersona = (id) => {
    const p = personasMap[id] || [];
    if (!p.length) return '—';
    return p.map(x => x.empresa).join(' · ');
  };
  const channelMixSummary = (id) => {
    const c = channelsMap[id] || [];
    if (!c.length) return '—';
    return c.slice(0, 2).map(x => `${x[0]} ${x[1]}%`).join(' · ');
  };
  const okrShort = (id) => {
    const o = okrsMap[id]?.[0];
    if (!o) return '—';
    return o.obj;
  };
  const pricing = {
    mimaki:    'Premium · €18k–€95k',
    biond:     'Mid-premium · ESG margem',
    decal:     'Volume · €0.30–€0.90/m²',
    sensek:    '"Premium acessível" · €4k–€12k',
    alldecor:  'Mid · custo m² competitivo',
    digidelta: 'N/A · institucional',
    store:     'Self-service · sem desconto',
  };

  return (
    <div style={{
      background: 'var(--bg-elev)',
      border: '1px solid var(--border)',
      borderRadius: 10,
      overflow: 'hidden',
    }}>
      <div style={{ padding: '12px 16px', borderBottom: '1px solid var(--border)', display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
        <div className="font-display" style={{ fontSize: 14, fontWeight: 600 }}>Matriz estratégica · 7 marcas × 5 pilares</div>
        <div style={{ fontSize: 10.5, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)' }}>Click numa marca para ver canvas detalhado</div>
      </div>

      <div style={{ overflowX: 'auto' }}>
        <table style={{ width: '100%', minWidth: 1100, borderCollapse: 'collapse', fontSize: 12 }}>
          <thead>
            <tr style={{ background: 'var(--bg-sunken)' }}>
              <th style={{ padding: '10px 14px', textAlign: 'left', fontSize: 10, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', letterSpacing: '0.08em', borderRight: '1px solid var(--border)', position: 'sticky', left: 0, background: 'var(--bg-sunken)', minWidth: 130 }}>MARCA</th>
              <th style={{ padding: '10px 14px', textAlign: 'left', fontSize: 10, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', letterSpacing: '0.08em', borderRight: '1px solid var(--border)', minWidth: 220 }}>POSICIONAMENTO</th>
              <th style={{ padding: '10px 14px', textAlign: 'left', fontSize: 10, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', letterSpacing: '0.08em', borderRight: '1px solid var(--border)', minWidth: 200 }}>TARGET</th>
              <th style={{ padding: '10px 14px', textAlign: 'left', fontSize: 10, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', letterSpacing: '0.08em', borderRight: '1px solid var(--border)', minWidth: 140 }}>PRICING</th>
              <th style={{ padding: '10px 14px', textAlign: 'left', fontSize: 10, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', letterSpacing: '0.08em', borderRight: '1px solid var(--border)', minWidth: 180 }}>CHANNEL MIX</th>
              <th style={{ padding: '10px 14px', textAlign: 'left', fontSize: 10, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', letterSpacing: '0.08em', minWidth: 220 }}>OKR 2026</th>
            </tr>
          </thead>
          <tbody>
            {brands.map((b, i) => (
              <tr key={b.id} style={{
                borderTop: '1px solid var(--border)',
                cursor: 'pointer',
                transition: 'background 0.12s',
              }}
              onClick={() => onPickBrand(b.id)}
              onMouseEnter={e => e.currentTarget.style.background = 'var(--bg-hover)'}
              onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
                <td style={{ padding: '14px', borderRight: '1px solid var(--border)', position: 'sticky', left: 0, background: 'inherit', verticalAlign: 'top' }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 }}>
                    <span style={{ width: 12, height: 12, borderRadius: 3, background: b.cor, flexShrink: 0 }} />
                    <span className="font-display" style={{ fontSize: 13.5, fontWeight: 600 }}>{b.nome}</span>
                  </div>
                  <div style={{ fontSize: 10.5, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)' }}>{b.tagline}</div>
                </td>
                <td style={{ padding: '14px', borderRight: '1px solid var(--border)', verticalAlign: 'top', fontStyle: 'italic', color: 'var(--text-muted)', lineHeight: 1.5 }}>"{b.pos}"</td>
                <td style={{ padding: '14px', borderRight: '1px solid var(--border)', verticalAlign: 'top', lineHeight: 1.5, color: 'var(--text-muted)' }}>
                  {(b.target || []).slice(0, 3).map((t, j) => (
                    <div key={j} style={{ paddingLeft: 10, position: 'relative' }}>
                      <span style={{ position: 'absolute', left: 0, top: 8, width: 4, height: 4, borderRadius: '50%', background: b.cor }} />
                      {t}
                    </div>
                  ))}
                </td>
                <td style={{ padding: '14px', borderRight: '1px solid var(--border)', verticalAlign: 'top', fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--text-muted)' }}>
                  {pricing[b.id]}
                </td>
                <td style={{ padding: '14px', borderRight: '1px solid var(--border)', verticalAlign: 'top', color: 'var(--text-muted)', lineHeight: 1.5 }}>
                  {channelMixSummary(b.id)}
                </td>
                <td style={{ padding: '14px', verticalAlign: 'top', color: 'var(--text)', lineHeight: 1.4 }}>
                  <strong style={{ fontSize: 12.5 }}>{okrShort(b.id)}</strong>
                  {okrsMap[b.id]?.[0]?.krs?.[0] && (
                    <div style={{ fontSize: 10.5, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', marginTop: 4 }}>{okrsMap[b.id][0].krs[0]}</div>
                  )}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
};

// ============================================================================
// Estratégia · Canvas (single brand)
// ============================================================================
const EstrategiaCanvas = ({ brand, brandObj }) => {
  const personas = (window.MKT_BRAND_PERSONAS || {})[brand] || [];
  const channels = (window.MKT_BRAND_CHANNELS || {})[brand] || [];
  const okrs = (window.MKT_BRAND_OKRS || {})[brand] || [];
  const competitors = (window.MKT_BRAND_COMPETITORS || {})[brand] || [];

  const ameacaColor = { forte: 'var(--danger)', medio: 'var(--warning)', baixo: 'var(--success)' };
  const ameacaLabel = { forte: 'Ameaça forte', medio: 'Ameaça moderada', baixo: 'Ameaça baixa' };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
      {/* Positioning hero */}
      <div className="card" style={{
        padding: 24,
        borderLeft: `4px solid ${brandObj.cor}`,
      }}>
        <div style={{ fontSize: 10, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', letterSpacing: '0.08em' }}>POSICIONAMENTO {brandObj.nome.toUpperCase()}</div>
        <h3 className="font-display" style={{ margin: '6px 0 10px', fontSize: 22, fontWeight: 500, letterSpacing: '-0.01em', lineHeight: 1.3 }}>
          "{brandObj.pos}"
        </h3>
        <p style={{ fontSize: 13, color: 'var(--text-muted)', lineHeight: 1.6, margin: 0, maxWidth: 800 }}>
          {brandObj.descricao}
        </p>
      </div>

      {/* Personas */}
      <div className="card" style={{ padding: 18 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 12 }}>
          <div className="font-display" style={{ fontSize: 14, fontWeight: 600 }}>Personas {brandObj.nome}</div>
          <div style={{ fontSize: 10.5, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)' }}>{personas.length} {personas.length === 1 ? 'persona' : 'personas'}</div>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(260px, 1fr))', gap: 12 }}>
          {personas.map((p, i) => (
            <div key={i} style={{
              padding: 14,
              background: 'var(--bg-sunken)',
              borderRadius: 8,
              border: `1px solid var(--border)`,
              borderTop: `3px solid ${brandObj.cor}`,
            }}>
              <div className="font-display" style={{ fontSize: 13.5, fontWeight: 600, marginBottom: 2 }}>{p.nome}</div>
              <div style={{ fontSize: 10.5, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', marginBottom: 8 }}>{p.empresa}</div>
              <div style={{ fontSize: 11.5, color: 'var(--text-muted)', lineHeight: 1.55, display: 'flex', flexDirection: 'column', gap: 6 }}>
                <div><span style={{ color: 'var(--danger)', fontWeight: 600 }}>Dor:</span> {p.dor}</div>
                <div><span style={{ color: 'var(--success)', fontWeight: 600 }}>Objectivo:</span> {p.objectivo}</div>
                <div style={{ fontSize: 10.5, fontFamily: 'var(--font-mono)', color: 'var(--text-dim)' }}>↳ {p.canais}</div>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* Channel mix + Competitive landscape side by side */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
        <div className="card" style={{ padding: 18 }}>
          <div className="font-display" style={{ fontSize: 14, fontWeight: 600, marginBottom: 14 }}>Channel mix · 2025</div>
          <ChannelDonut channels={channels} />
        </div>

        <div className="card" style={{ padding: 18 }}>
          <div className="font-display" style={{ fontSize: 14, fontWeight: 600, marginBottom: 12 }}>Competitive landscape</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {competitors.map(([nome, desc, ameaca], i) => (
              <div key={i} style={{
                padding: '10px 12px',
                background: 'var(--bg-sunken)',
                borderRadius: 6,
                borderLeft: `3px solid ${ameacaColor[ameaca]}`,
              }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 2 }}>
                  <span className="font-display" style={{ fontSize: 13, fontWeight: 600 }}>{nome}</span>
                  <span style={{
                    fontSize: 9.5, padding: '2px 6px', borderRadius: 3,
                    background: `color-mix(in oklch, ${ameacaColor[ameaca]} 15%, transparent)`,
                    color: ameacaColor[ameaca],
                    fontFamily: 'var(--font-mono)', letterSpacing: '0.04em', fontWeight: 600,
                  }}>{ameacaLabel[ameaca]}</span>
                </div>
                <div style={{ fontSize: 11.5, color: 'var(--text-muted)', lineHeight: 1.4 }}>{desc}</div>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* OKRs 2026 */}
      <div className="card" style={{ padding: 18 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 14 }}>
          <div className="font-display" style={{ fontSize: 14, fontWeight: 600 }}>OKRs 2026 · {brandObj.nome}</div>
          <div style={{ fontSize: 10.5, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)' }}>{okrs.length} objectivo{okrs.length === 1 ? '' : 's'}</div>
        </div>
        {okrs.map((o, i) => (
          <div key={i} style={{ padding: '14px', background: `color-mix(in oklch, ${brandObj.cor} 6%, var(--bg-sunken))`, borderRadius: 8, border: `1px solid color-mix(in oklch, ${brandObj.cor} 18%, var(--border))` }}>
            <div className="font-display" style={{ fontSize: 16, fontWeight: 600, marginBottom: 10, color: 'var(--text)' }}>
              <span style={{ fontSize: 11, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', letterSpacing: '0.08em', marginRight: 8 }}>OBJ</span>
              {o.obj}
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(180px, 1fr))', gap: 8 }}>
              {o.krs.map((kr, j) => (
                <div key={j} style={{ padding: '8px 10px', background: 'var(--bg-elev)', borderRadius: 6, fontSize: 12, color: 'var(--text)', display: 'flex', alignItems: 'flex-start', gap: 6 }}>
                  <span style={{ color: brandObj.cor, fontWeight: 700, fontFamily: 'var(--font-mono)', fontSize: 10, flexShrink: 0, marginTop: 1 }}>KR{j+1}</span>
                  <span style={{ lineHeight: 1.4 }}>{kr}</span>
                </div>
              ))}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
};

// ============================================================================
// MAIN
// ============================================================================
const MktEstrategia = () => {
  const { brand, brandObj, isAll, setBrand } = window.useMktBrand();

  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 · ESTRATÉGIA {!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 }}>
        Estratégia
        {!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>
        )}
      </h2>
      <div style={{ fontSize: 12, color: 'var(--text-muted)', marginBottom: 18 }}>
        {isAll
          ? 'Posicionamento, target, pricing, canais e OKRs 2026 das 7 marcas. Click numa linha para abrir o canvas detalhado.'
          : `Canvas estratégico · personas, channel mix, concorrência e OKRs 2026.`}
      </div>

      {isAll
        ? <EstrategiaMatrix onPickBrand={setBrand} />
        : <EstrategiaCanvas brand={brand} brandObj={brandObj} />}
    </div>
  );
};

window.MktEstrategia = MktEstrategia;
