/* Marketing · Plano de Comunicação 2026 — ecrã principal.
   Usa MktKpi, MktTimeline, MktCalendar de screen_marketing_plano_parts.jsx
   e dados de screen_marketing_data.js. */

const MktPlanoScreen = ({ onOpenChat }) => {
  const [tab, setTab] = React.useState('calendar'); // calendar | timeline | channel | funnel
  const [hiddenChannels, setHiddenChannels] = React.useState([]);
  const [showLabels, setShowLabels] = React.useState(true);
  const [openedDay, setOpenedDay] = React.useState(null);

  const CH = window.MKT_CHANNELS;
  const toggleChannel = (id) => {
    setHiddenChannels(h => h.includes(id) ? h.filter(x => x !== id) : [...h, id]);
  };

  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1fr 320px', gap: 0, height: '100%', minHeight: 0, overflow: 'hidden' }}>
      {/* Main column */}
      <div className="scrollbar" style={{ overflowY: 'auto', minHeight: 0, padding: '20px 24px 80px' }}>
        {/* Header */}
        <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 16, marginBottom: 18 }}>
          <div>
            <div style={{ fontSize: 11, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', letterSpacing: '0.08em' }}>MARKETING · PLANO EDITORIAL</div>
            <h2 className="font-display" style={{ margin: '6px 0 4px', fontSize: 28, fontWeight: 500, letterSpacing: '-0.01em' }}>
              Plano de Comunicação <span style={{ color: 'var(--text-muted)' }}>· 2026</span>
            </h2>
            <div style={{ fontSize: 12, color: 'var(--text-muted)' }}>109 conteúdos planeados · 6 canais · Fonte: ClickUp</div>
          </div>
          <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
            <div style={{
              display: 'inline-flex', alignItems: 'center', gap: 8, padding: '5px 12px',
              borderRadius: 999, fontSize: 11, fontFamily: 'var(--font-mono)',
              background: 'color-mix(in oklch, var(--success) 14%, transparent)',
              color: 'var(--success)',
              border: '1px solid color-mix(in oklch, var(--success) 30%, transparent)',
            }}>
              <span style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--success)' }} />
              8 publicados · 101 planeados
            </div>
            <button className="btn btn-sm"><Icon name="refresh" size={13} />Sync ClickUp</button>
            <button className="btn btn-sm btn-primary"><Icon name="plus" size={13} />Nova tarefa</button>
          </div>
        </div>

        {/* Tabs */}
        <div style={{ display: 'inline-flex', gap: 0, background: 'var(--surface-muted)', padding: 3, borderRadius: 8, border: '1px solid var(--border)', marginBottom: 16 }}>
          {[
            { id: 'calendar', label: 'Calendário' },
            { id: 'timeline', label: 'Timeline anual' },
            { id: 'channel',  label: 'Por canal' },
            { id: 'funnel',   label: 'Por funil' },
          ].map(t => (
            <button key={t.id} onClick={() => setTab(t.id)} style={{
              padding: '5px 14px', borderRadius: 6, fontSize: 12,
              fontFamily: 'var(--font-display)', fontWeight: 600, letterSpacing: '0.02em',
              background: tab === t.id ? 'var(--bg-elev)' : 'transparent',
              color: tab === t.id ? 'var(--text)' : 'var(--text-muted)',
              boxShadow: tab === t.id ? 'var(--shadow-sm)' : 'none',
            }}>{t.label}</button>
          ))}
        </div>

        {/* FAIXA 1 — KPIs */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 12, marginBottom: 20 }}>
          <MktKpi label="Total conteúdos" value="109" sub="6 canais · 11 meses" />
          <MktKpi label="Publicados"       value="8" sub="7% · tudo Fevereiro" trend={<div style={{ fontSize: 10, fontFamily: 'var(--font-mono)', color: 'var(--success)', marginTop: 4 }}>● on-track</div>} />
          <MktKpi label="Planeados"        value="101" sub="93% · Mar → Dez" />
          <MktKpi label="Canais activos"   value="6" sub="LI · SM · EM · MA · WB · —" />
          <MktKpi label="Funil dominante"  value="Awareness" sub="41% + Consideration 32%" />
        </div>

        {/* FAIXA 2 — Timeline anual (hero) */}
        <div className="card" style={{ padding: 16, marginBottom: 20 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 14 }}>
            <div>
              <div className="font-display" style={{ fontSize: 14, fontWeight: 600 }}>Distribuição mensal · 2026</div>
              <div style={{ fontSize: 11, color: 'var(--text-muted)', marginTop: 2 }}>Barras empilhadas por canal · Abril é pico (20 tarefas, 11 Meta Ads)</div>
            </div>
            <label style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 11, color: 'var(--text-muted)' }}>
              <input type="checkbox" checked={showLabels} onChange={e => setShowLabels(e.target.checked)} />
              Mostrar valores
            </label>
          </div>
          <MktTimeline months={window.MKT_MONTHS} showLabels={showLabels} hiddenChannels={hiddenChannels} />
          {/* Legenda canais (também serve de toggle) */}
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginTop: 16, paddingTop: 12, borderTop: '1px solid var(--border)' }}>
            <span style={{ fontSize: 10, color: 'var(--text-dim)', fontFamily: 'var(--font-display)', fontWeight: 600, letterSpacing: '0.08em', alignSelf: 'center' }}>CANAIS ·</span>
            {CH.map(c => {
              const hidden = hiddenChannels.includes(c.id);
              return (
                <button key={c.id} onClick={() => toggleChannel(c.id)}
                  style={{
                    display: 'inline-flex', alignItems: 'center', gap: 6,
                    padding: '3px 10px', borderRadius: 999,
                    border: '1px solid var(--border)',
                    background: hidden ? 'transparent' : `${c.color}18`,
                    color: hidden ? 'var(--text-dim)' : 'var(--text)',
                    fontSize: 11, opacity: hidden ? 0.5 : 1,
                  }}>
                  <span style={{ width: 8, height: 8, borderRadius: 2, background: c.color }} />
                  {c.label}
                </button>
              );
            })}
          </div>
        </div>

        {/* FAIXA 3 — Calendário mensal (só visível na tab calendar) */}
        {tab === 'calendar' && (
          <div className="card" style={{ padding: 16, marginBottom: 20 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 14 }}>
              <div>
                <div className="font-display" style={{ fontSize: 14, fontWeight: 600 }}>Calendário editorial · Abril 2026 <span style={{ color: 'var(--accent-500)', fontSize: 11, marginLeft: 8 }}>⭐ mês actual · pico do ano</span></div>
                <div style={{ fontSize: 11, color: 'var(--text-muted)', marginTop: 2 }}>20 tarefas · 8 Social · 11 Meta Ads · 1 Email · 1 LinkedIn</div>
              </div>
              <div style={{ display: 'flex', gap: 4 }}>
                <button className="btn btn-xs" disabled style={{ opacity: 0.6 }}><Icon name="chevron" size={10} style={{ transform: 'rotate(90deg)' }} />Mar</button>
                <button className="btn btn-xs" style={{ background: 'var(--brand-900)', color: '#fff', borderColor: 'var(--brand-900)' }}>Abril 2026</button>
                <button className="btn btn-xs" disabled style={{ opacity: 0.6 }}>Mai<Icon name="chevron" size={10} style={{ transform: 'rotate(-90deg)' }} /></button>
                <button className="btn btn-xs btn-ghost">Hoje</button>
              </div>
            </div>
            <MktCalendar hiddenChannels={hiddenChannels} onOpenDay={(day, tasks) => setOpenedDay({ day, tasks })} />
          </div>
        )}

        {tab === 'channel' && (
          <div className="card" style={{ padding: 16, marginBottom: 20 }}>
            <div className="font-display" style={{ fontSize: 14, fontWeight: 600, marginBottom: 14 }}>Distribuição por canal · ano completo</div>
            {CH.map(c => {
              const total = window.MKT_MONTHS.reduce((s, m) => s + (m.channels[c.id] || 0), 0);
              const maxTotal = Math.max(...CH.map(cc => window.MKT_MONTHS.reduce((s, m) => s + (m.channels[cc.id] || 0), 0)));
              return (
                <div key={c.id} style={{ display: 'grid', gridTemplateColumns: '140px 1fr 60px', gap: 12, alignItems: 'center', padding: '6px 0', borderBottom: '1px solid var(--border)' }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                    <span style={{ width: 10, height: 10, borderRadius: 2, background: c.color }} />
                    <span style={{ fontSize: 12 }}>{c.label}</span>
                  </div>
                  <div style={{ height: 14, background: 'var(--bg-sunken)', borderRadius: 3, overflow: 'hidden' }}>
                    <div style={{ height: '100%', width: `${(total / maxTotal) * 100}%`, background: c.color, borderRadius: 3 }} />
                  </div>
                  <span className="font-mono" style={{ fontSize: 12, textAlign: 'right', fontWeight: 600 }}>{total}</span>
                </div>
              );
            })}
          </div>
        )}

        {tab === 'funnel' && (
          <div className="card" style={{ padding: 16, marginBottom: 20 }}>
            <div className="font-display" style={{ fontSize: 14, fontWeight: 600, marginBottom: 14 }}>Distribuição por etapa de funil</div>
            <div style={{ display: 'flex', height: 40, borderRadius: 8, overflow: 'hidden' }}>
              {window.MKT_FUNNEL.map(f => (
                <div key={f.id} title={`${f.label}: ${Math.round(f.pct * 109)}`} style={{
                  flex: f.pct, background: f.color, display: 'grid', placeItems: 'center',
                  color: '#fff', fontFamily: 'var(--font-display)', fontSize: 12, fontWeight: 600,
                }}>
                  {f.label} · {Math.round(f.pct * 100)}%
                </div>
              ))}
            </div>
            <div style={{ marginTop: 12, fontSize: 11, color: 'var(--text-muted)' }}>73% do plano vive no topo do funil (Awareness + Consideration) — coerente com B2B longo-ciclo.</div>
          </div>
        )}

        {tab === 'timeline' && (
          <div style={{ fontSize: 12, color: 'var(--text-muted)', padding: 16 }}>Vista expandida da timeline — usa o card hero acima com toggle de canais.</div>
        )}

        {/* FAIXA 4 — Dores + Objectivos */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
          <div className="card" style={{ padding: 16 }}>
            <div className="font-display" style={{ fontSize: 14, fontWeight: 600, marginBottom: 4 }}>Top dores trabalhadas no plano</div>
            <div style={{ fontSize: 11, color: 'var(--text-muted)', marginBottom: 12 }}>Mapeadas nas 109 tarefas</div>
            {window.MKT_PAINS.map((p, i) => (
              <div key={i} style={{ display: 'grid', gridTemplateColumns: '1fr 60px 40px', gap: 10, alignItems: 'center', padding: '6px 0', borderBottom: i < 5 ? '1px solid var(--border)' : 'none' }}>
                <span style={{ fontSize: 12 }}>{i + 1}. {p.label}</span>
                <div style={{ height: 6, background: 'var(--bg-sunken)', borderRadius: 3, overflow: 'hidden' }}>
                  <div style={{ height: '100%', width: `${p.pct * 100 * 3.2}%`, background: 'var(--danger)', opacity: 0.8 }} />
                </div>
                <span className="font-mono" style={{ fontSize: 11, textAlign: 'right' }}>{p.n} <span style={{ color: 'var(--text-dim)' }}>({Math.round(p.pct * 100)}%)</span></span>
              </div>
            ))}
          </div>
          <div className="card" style={{ padding: 16 }}>
            <div className="font-display" style={{ fontSize: 14, fontWeight: 600, marginBottom: 4 }}>Top objectivos estratégicos</div>
            <div style={{ fontSize: 11, color: 'var(--text-muted)', marginBottom: 12 }}>Para onde puxam os conteúdos</div>
            {window.MKT_OBJECTIVES.map((o, i) => (
              <div key={i} style={{ display: 'grid', gridTemplateColumns: '1fr 60px 40px', gap: 10, alignItems: 'center', padding: '6px 0', borderBottom: i < 5 ? '1px solid var(--border)' : 'none' }}>
                <span style={{ fontSize: 12 }}>{i + 1}. {o.label}</span>
                <div style={{ height: 6, background: 'var(--bg-sunken)', borderRadius: 3, overflow: 'hidden' }}>
                  <div style={{ height: '100%', width: `${o.pct * 100 * 2.5}%`, background: 'var(--success)', opacity: 0.85 }} />
                </div>
                <span className="font-mono" style={{ fontSize: 11, textAlign: 'right' }}>{o.n} <span style={{ color: 'var(--text-dim)' }}>({Math.round(o.pct * 100)}%)</span></span>
              </div>
            ))}
          </div>
        </div>

        {/* Footer */}
        <div style={{ marginTop: 24, padding: '12px 0', borderTop: '1px solid var(--border)', display: 'flex', justifyContent: 'space-between', fontSize: 10, fontFamily: 'var(--font-mono)', color: 'var(--text-dim)' }}>
          <span>Sync ClickUp · há 12 min · 109 tarefas</span>
          <span>Próximo board meeting: 6 Mai · Notas: 0</span>
        </div>
      </div>

      {/* Right panel — Digi AI Content Trace */}
      <MktContentTrace onOpenChat={onOpenChat} />

      {/* Day drill-down modal */}
      {openedDay && <MktDayModal day={openedDay.day} tasks={openedDay.tasks} onClose={() => setOpenedDay(null)} />}
    </div>
  );
};

// ====================== Right panel ======================
const MktContentTrace = ({ onOpenChat }) => {
  const CH = Object.fromEntries(window.MKT_CHANNELS.map(c => [c.id, c]));
  return (
    <aside className="scrollbar" style={{
      overflowY: 'auto', minHeight: 0,
      background: 'var(--bg-elev)', borderLeft: '1px solid var(--border)',
      display: 'flex', flexDirection: 'column', gap: 14, padding: 16,
    }}>
      <div>
        <div style={{ fontSize: 10, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', letterSpacing: '0.08em' }}>DIGI AI · CONTENT TRACE</div>
        <div className="font-display" style={{ fontSize: 14, fontWeight: 600, marginTop: 2 }}>O que está a pensar</div>
      </div>

      <div className="ai-surface" style={{ padding: 12, borderRadius: 8, fontSize: 11.5, lineHeight: 1.5 }}>
        Plano 2026 concentrado em <strong>LinkedIn (31)</strong> + <strong>Social (28)</strong> — coerente com B2B Mimaki/Decal/BIOND. Pico de <strong>Abril</strong> (20 conteúdos, 11 Meta Ads) precisa de acompanhamento de budget e creative variations.
        <div style={{ marginTop: 8, padding: 8, background: 'color-mix(in oklch, var(--warning) 12%, transparent)', borderRadius: 5, fontSize: 11, color: 'var(--warning-deep, var(--warning))' }}>
          ⚠ Decal / AllDecor / Digidelta Store com <strong>Meta Ads bloqueado</strong> (fatura pendente) — pode comprometer 4 dos 11 anúncios de Abril.
        </div>
      </div>

      {/* Próximas 7 publicações */}
      <div>
        <div style={{ fontSize: 10, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', marginBottom: 8, letterSpacing: '0.06em' }}>PRÓXIMAS 7 PUBLICAÇÕES</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
          {window.MKT_NEXT.map((p, i) => {
            const c = CH[p.ch];
            return (
              <div key={i} style={{
                padding: '7px 9px', background: 'var(--bg-sunken)', borderRadius: 5,
                borderLeft: `3px solid ${c.color}`,
              }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 8, marginBottom: 3 }}>
                  <span className="font-mono" style={{ fontSize: 9.5, color: 'var(--text-dim)' }}>{i + 1}. {p.date}</span>
                  <span className="font-mono" style={{ fontSize: 9, color: c.color, fontWeight: 700 }}>{c.code}</span>
                </div>
                <div style={{ fontSize: 11, lineHeight: 1.35, color: 'var(--text)' }}>{p.title}</div>
                <div style={{ fontSize: 9.5, fontFamily: 'var(--font-mono)', color: 'var(--text-muted)', marginTop: 2 }}>{p.funnel}</div>
              </div>
            );
          })}
        </div>
      </div>

      {/* CTAs */}
      <div>
        <div style={{ fontSize: 10, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', marginBottom: 8, letterSpacing: '0.06em' }}>CTAs MAIS USADOS</div>
        {window.MKT_CTAS.map((c, i) => (
          <div key={i} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '4px 0', borderBottom: i < 4 ? '1px solid var(--border)' : 'none' }}>
            <span style={{ fontSize: 11, color: c.warn ? 'var(--warning)' : 'var(--text)' }}>{c.label}</span>
            <span className="font-mono" style={{ fontSize: 10, color: 'var(--text-muted)' }}>{c.n} ({Math.round(c.pct * 100)}%)</span>
          </div>
        ))}
      </div>

      {/* Alertas */}
      <div>
        <div style={{ fontSize: 10, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', marginBottom: 8, letterSpacing: '0.06em' }}>ALERTAS</div>
        {[
          '19 tarefas sem CTA atribuído',
          '19 tarefas sem segmento definido',
          '19 tarefas sem etapa funil definida',
          '14 tarefas sem status editorial',
        ].map((a, i) => (
          <div key={i} style={{ padding: '5px 8px', marginBottom: 3, background: 'color-mix(in oklch, var(--warning) 10%, transparent)', borderRadius: 4, fontSize: 11, color: 'var(--text)' }}>
            ⚠ {a}
          </div>
        ))}
        <div style={{ fontSize: 10.5, color: 'var(--text-muted)', fontStyle: 'italic', marginTop: 6, lineHeight: 1.4 }}>→ Sugerir limpeza de dados antes de Maio</div>
      </div>

      {/* SP / FRAMEs */}
      <div>
        <div style={{ fontSize: 10, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', marginBottom: 6, letterSpacing: '0.06em' }}>SP / FRAMEs</div>
        {[
          ['SP_COLAB_MKT',    'v3.0',       'ok'],
          ['FRAME-CONTENT',   '[pendente]', 'pending'],
          ['FRAME-EDITORIAL', '[pendente]', 'pending'],
        ].map(([n, v, s]) => (
          <div key={n} style={{
            padding: '5px 8px', marginBottom: 3,
            fontFamily: 'var(--font-mono)', fontSize: 10,
            background: 'var(--bg-sunken)', borderRadius: 4,
            display: 'flex', justifyContent: 'space-between',
            color: s === 'ok' ? 'var(--text)' : 'var(--text-muted)',
          }}>
            <span>{n}</span><span style={{ color: s === 'ok' ? 'var(--success)' : 'var(--warning)' }}>{v}</span>
          </div>
        ))}
      </div>

      {/* Próxima acção sugerida */}
      <div style={{ padding: 12, background: 'color-mix(in oklch, var(--ai-500) 10%, transparent)', border: '1px solid color-mix(in oklch, var(--ai-500) 24%, transparent)', borderRadius: 8 }}>
        <div style={{ fontSize: 10, color: 'var(--ai-500)', fontFamily: 'var(--font-mono)', letterSpacing: '0.06em', marginBottom: 6 }}>PRÓXIMA ACÇÃO SUGERIDA</div>
        <div style={{ fontSize: 11.5, lineHeight: 1.45, marginBottom: 10, fontStyle: 'italic', color: 'var(--text)' }}>
          "Que conteúdos de Abril ainda estão por produzir?"
        </div>
        <button className="btn btn-xs btn-ai" style={{ width: '100%', justifyContent: 'center' }} onClick={onOpenChat}>
          <Icon name="sparkle" size={11} />Perguntar Digi
        </button>
      </div>
    </aside>
  );
};

// ====================== Day modal ======================
const MktDayModal = ({ day, tasks, onClose }) => {
  const CH = Object.fromEntries(window.MKT_CHANNELS.map(c => [c.id, c]));
  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.5)',
      display: 'grid', placeItems: 'center', zIndex: 200,
    }}>
      <div onClick={e => e.stopPropagation()} style={{
        background: 'var(--bg-elev)', borderRadius: 12, width: 560,
        maxHeight: '80vh', overflowY: 'auto',
        padding: 24, boxShadow: 'var(--shadow-lg)',
      }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 14 }}>
          <div>
            <div style={{ fontSize: 10, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', letterSpacing: '0.08em' }}>CALENDÁRIO · ABRIL 2026</div>
            <h3 className="font-display" style={{ margin: '4px 0 0', fontSize: 22 }}>Dia {day} · {tasks.length} tarefas</h3>
          </div>
          <button onClick={onClose} className="btn btn-xs btn-ghost"><Icon name="close" size={12} /></button>
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {tasks.map((t, i) => {
            const c = CH[t.ch];
            return (
              <div key={i} style={{ padding: 12, border: '1px solid var(--border)', borderLeft: `3px solid ${c.color}`, borderRadius: 6, background: 'var(--bg)' }}>
                <div style={{ display: 'flex', gap: 8, alignItems: 'center', marginBottom: 6 }}>
                  <span style={{ padding: '1px 6px', borderRadius: 3, background: `${c.color}1f`, color: c.color, fontFamily: 'var(--font-mono)', fontSize: 9, fontWeight: 700 }}>{c.label}</span>
                  <span style={{ padding: '1px 6px', borderRadius: 3, background: 'var(--bg-sunken)', fontSize: 9, fontFamily: 'var(--font-mono)' }}>{t.funnel}</span>
                  <span style={{ padding: '1px 6px', borderRadius: 3, background: 'var(--bg-sunken)', fontSize: 9, fontFamily: 'var(--font-mono)' }}>{t.brand}</span>
                </div>
                <div style={{ fontSize: 13, fontWeight: 500, marginBottom: 4 }}>{t.title}</div>
                <div style={{ fontSize: 11, color: 'var(--text-muted)', display: 'flex', gap: 10 }}>
                  <span>CTA: <strong style={{ color: 'var(--text)' }}>{t.cta}</strong></span>
                  <span>Dor: {t.pain}</span>
                  <span>Obj: {t.obj}</span>
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
};

window.MktPlanoScreen = MktPlanoScreen;
