/* Marketing · Plano de Comunicação 2026
   Calendário editorial + timeline anual + análise estratégica.
   Dados em screen_marketing_data.js (window.MKT_*). */

// ====================== KPI strip ======================
const MktKpi = ({ label, value, sub, trend }) => (
  <div style={{
    padding: 16, border: '1px solid var(--border)', borderRadius: 10,
    background: 'var(--bg-elev)',
    display: 'flex', flexDirection: 'column', gap: 4,
  }}>
    <div style={{ fontSize: 10, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', letterSpacing: '0.08em', textTransform: 'uppercase' }}>{label}</div>
    <div className="font-display" style={{ fontSize: 28, fontWeight: 600, letterSpacing: '-0.01em', lineHeight: 1 }}>{value}</div>
    {sub && <div style={{ fontSize: 11, color: 'var(--text-muted)', marginTop: 2 }}>{sub}</div>}
    {trend}
  </div>
);

// ====================== Stacked bar ======================
const StackedBar = ({ channels, total, maxTotal, showLabels }) => {
  const CH = window.MKT_CHANNELS;
  const pctScale = (total / maxTotal) * 100;
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 10, minWidth: 0 }}>
      <div style={{
        height: 22, width: `${pctScale}%`, minWidth: 40,
        display: 'flex', borderRadius: 4, overflow: 'hidden',
        boxShadow: 'inset 0 0 0 1px color-mix(in oklch, var(--text) 6%, transparent)',
      }}>
        {CH.map(c => {
          const n = channels[c.id] || 0;
          if (!n) return null;
          return (
            <div key={c.id}
              title={`${c.label}: ${n}`}
              style={{
                width: `${(n / total) * 100}%`,
                background: c.color,
                display: 'grid', placeItems: 'center',
                fontSize: 9, fontFamily: 'var(--font-mono)', fontWeight: 700,
                color: '#fff', minWidth: n >= 2 ? 18 : 'auto',
              }}>
              {showLabels && n >= 2 ? n : ''}
            </div>
          );
        })}
      </div>
      <span className="font-mono" style={{ fontSize: 11, color: 'var(--text-muted)', whiteSpace: 'nowrap' }}>
        {total}
      </span>
    </div>
  );
};

// ====================== Timeline anual ======================
const MktTimeline = ({ months, showLabels, hiddenChannels }) => {
  const max = Math.max(...months.map(m => m.total));
  const active = (m) => {
    const filtered = { ...m.channels };
    hiddenChannels.forEach(h => delete filtered[h]);
    const total = Object.values(filtered).reduce((a, b) => a + b, 0);
    return { channels: filtered, total };
  };
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
      {months.map(m => {
        const a = active(m);
        const isCurrent = m.status === 'current';
        return (
          <div key={m.m} style={{
            display: 'grid', gridTemplateColumns: '44px 1fr',
            alignItems: 'center', gap: 12,
            padding: '5px 8px', borderRadius: 6,
            background: isCurrent ? 'color-mix(in oklch, var(--brand-900) 8%, transparent)' : 'transparent',
            position: 'relative',
          }}>
            {isCurrent && (
              <span style={{
                position: 'absolute', left: -2, top: 4, bottom: 4, width: 3,
                background: 'var(--success)', borderRadius: 2,
                boxShadow: '0 0 0 3px color-mix(in oklch, var(--success) 18%, transparent)',
                animation: 'ai-shimmer 2s ease-in-out infinite',
              }} />
            )}
            <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-start' }}>
              <span className="font-display" style={{ fontSize: 12, fontWeight: 600, color: isCurrent ? 'var(--brand-900)' : 'var(--text)' }}>{m.m}</span>
              {m.peak && <span style={{ fontSize: 8.5, fontFamily: 'var(--font-mono)', color: 'var(--accent-500)', letterSpacing: '0.05em' }}>⭐ PICO</span>}
            </div>
            <StackedBar channels={a.channels} total={a.total} maxTotal={max} showLabels={showLabels} />
          </div>
        );
      })}
    </div>
  );
};

// ====================== Calendário mensal ======================
const CalendarCell = ({ day, tasks, isPeak, hiddenChannels, onOpen }) => {
  const filtered = (tasks || []).filter(t => !hiddenChannels.includes(t.ch));
  const visible = filtered.slice(0, 3);
  const overflow = filtered.length - visible.length;
  const CH = Object.fromEntries(window.MKT_CHANNELS.map(c => [c.id, c]));
  return (
    <div
      onClick={() => filtered.length && onOpen(day, filtered)}
      style={{
        minHeight: 92,
        padding: '6px 7px',
        border: '1px solid var(--border)',
        borderRadius: 6,
        background: !day ? 'var(--bg-sunken)' : 'var(--bg-elev)',
        opacity: !day ? 0.35 : 1,
        cursor: filtered.length ? 'pointer' : 'default',
        display: 'flex', flexDirection: 'column', gap: 4,
        position: 'relative',
        transition: 'transform 0.12s, box-shadow 0.12s',
      }}
      onMouseEnter={e => { if (filtered.length) { e.currentTarget.style.boxShadow = 'var(--shadow-md)'; e.currentTarget.style.transform = 'translateY(-1px)'; } }}
      onMouseLeave={e => { e.currentTarget.style.boxShadow = 'none'; e.currentTarget.style.transform = 'none'; }}
    >
      {day && (
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <span className="font-mono" style={{
            fontSize: 11, fontWeight: 600,
            color: isPeak ? 'var(--brand-900)' : 'var(--text-muted)',
          }}>{day}</span>
          {filtered.length > 0 && (
            <span style={{ fontSize: 9, fontFamily: 'var(--font-mono)', color: 'var(--text-dim)' }}>{filtered.length}</span>
          )}
        </div>
      )}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
        {visible.map((t, i) => {
          const c = CH[t.ch];
          return (
            <div key={i} title={`${t.title} · ${t.cta} · ${t.funnel}`} style={{
              display: 'flex', alignItems: 'center', gap: 4,
              padding: '2px 6px',
              background: `${c.color}1a`,
              borderLeft: `2px solid ${c.color}`,
              borderRadius: 3,
              fontSize: 9.5, lineHeight: 1.2,
              color: 'var(--text)',
              whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
            }}>
              <span style={{ fontFamily: 'var(--font-mono)', fontSize: 9, color: c.color, fontWeight: 700, flexShrink: 0 }}>{c.code}</span>
              <span style={{ overflow: 'hidden', textOverflow: 'ellipsis' }}>{t.title.replace(/^[^·]+· /, '')}</span>
            </div>
          );
        })}
        {overflow > 0 && (
          <div style={{ fontSize: 9, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', paddingLeft: 4 }}>+{overflow} more</div>
        )}
      </div>
    </div>
  );
};

const MktCalendar = ({ hiddenChannels, onOpenDay }) => {
  // Abril 2026: 1 = Qua. Grid 7-cols começa segunda.
  // Pré-fill: Mon 30/3, Tue 31/3 vazios ou usam tasks day=1 (Wed).
  // Mapa tasks por dia
  const byDay = Object.fromEntries(window.MKT_APRIL.map(d => [d.day, d.tasks]));
  // Dias (null = fora do mês)
  const cells = [
    // Semana 1
    null, null, 1, 2, 3, 4, 5,
    // Semana 2
    6, 7, 8, 9, 10, 11, 12,
    // Semana 3
    13, 14, 15, 16, 17, 18, 19,
    // Semana 4
    20, 21, 22, 23, 24, 25, 26,
    // Semana 5
    27, 28, 29, 30, null, null, null,
  ];
  const dow = ['Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'Sáb', 'Dom'];
  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gap: 6, marginBottom: 6 }}>
        {dow.map(d => (
          <div key={d} style={{
            fontSize: 10, fontFamily: 'var(--font-display)', fontWeight: 600,
            letterSpacing: '0.08em', textTransform: 'uppercase',
            color: 'var(--text-dim)', textAlign: 'center', padding: '4px 0',
          }}>{d}</div>
        ))}
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gap: 6 }}>
        {cells.map((day, i) => (
          <CalendarCell
            key={i} day={day} tasks={day ? byDay[day] : null}
            isPeak={day === 1 || day === 15 || day === 30}
            hiddenChannels={hiddenChannels}
            onOpen={onOpenDay}
          />
        ))}
      </div>
    </div>
  );
};

window.MktKpi = MktKpi;
window.MktTimeline = MktTimeline;
window.MktCalendar = MktCalendar;
