/* global React, Icon, Pill, fmt,
   PROPOSALS, ONBOARDING_STEPS, CROSS_COMPARATIVES, SMART_ALERTS, INBOX,
   CHANNEL_ICONS, ALERT_SEVERITY_META, TEAM,
   BlockCard, Punch, BigStat, brl, brlK */
const { useState: useStateP3, useMemo: useMemoP3, useEffect: useEffectP3 } = React;

/* ============================================================
   SECTION · ONBOARDING · wizard guiado de novo cliente
   ============================================================ */
function SectionOnboarding() {
  const [step, setStep] = useStateP3(0);
  const [data, setData] = useStateP3({});
  const [completed, setCompleted] = useStateP3(false);

  const update = (fieldId, value) => setData(d => ({ ...d, [fieldId]: value }));
  const next = () => setStep(s => Math.min(ONBOARDING_STEPS.length - 1, s + 1));
  const prev = () => setStep(s => Math.max(0, s - 1));

  const currentStep = ONBOARDING_STEPS[step];
  const progress = ((step + 1) / ONBOARDING_STEPS.length) * 100;

  const startOver = () => { setStep(0); setData({}); setCompleted(false); };
  const finish = () => setCompleted(true);

  if (completed) {
    return <OnboardingDone data={data} onStartOver={startOver} />;
  }

  return (
    <div>
      <BlockCard kicker="✨ automação" title="**Novo cliente** em 5 minutos">
        <p style={{ margin: '0 0 18px', fontSize: 14, color: 'var(--text-muted)', maxWidth: 720, lineHeight: 1.6 }}>
          Preencha 5 passos e a Beza cria automaticamente: pasta no Drive, conta mLabs, lista no ClickUp, URL do relatório e notifica o time. Zero trabalho manual.
        </p>

        {/* Progress bar */}
        <div style={{ marginBottom: 24 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
            <span className="t-overline" style={{ color: 'var(--text-faint)' }}>
              Passo {step + 1} de {ONBOARDING_STEPS.length}
            </span>
            <span style={{ fontSize: 13, color: 'var(--accent)', fontWeight: 500 }}>
              {currentStep.label}
            </span>
          </div>
          <div style={{ height: 6, background: 'var(--surface-soft)', borderRadius: 999, overflow: 'hidden', border: '1px solid var(--border)' }}>
            <div style={{
              height: '100%', width: progress + '%',
              background: 'linear-gradient(90deg, var(--beza-purple), var(--beza-deep))',
              borderRadius: 999, transition: 'width var(--t-slow)',
            }} />
          </div>
        </div>

        {/* Stepper visual */}
        <div style={{ display: 'flex', gap: 6, marginBottom: 24, flexWrap: 'wrap' }}>
          {ONBOARDING_STEPS.map((s, i) => {
            const isPast = i < step;
            const isCurrent = i === step;
            return (
              <button key={s.id} onClick={() => setStep(i)} style={{
                appearance: 'none',
                padding: '6px 12px', fontSize: 11,
                borderRadius: 999, fontFamily: 'inherit', cursor: 'pointer',
                border: '1px solid',
                borderColor: isCurrent ? 'var(--accent)' : (isPast ? 'var(--success)' : 'var(--border)'),
                background: isCurrent ? 'var(--accent-soft)' : (isPast ? 'rgba(111,200,120,0.10)' : 'transparent'),
                color: isCurrent ? 'var(--accent)' : (isPast ? 'var(--success)' : 'var(--text-muted)'),
                fontWeight: isCurrent ? 500 : 400,
                display: 'inline-flex', alignItems: 'center', gap: 6,
              }}>
                <span style={{ fontWeight: 600 }}>{isPast ? '✓' : i + 1}</span>
                {s.label}
              </button>
            );
          })}
        </div>

        {/* Form fields */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          {currentStep.fields.map(f => (
            <OnboardingField key={f.id} field={f} value={data[f.id]} onChange={(v) => update(f.id, v)} />
          ))}
        </div>

        {/* Actions */}
        <div style={{
          marginTop: 28, paddingTop: 18, borderTop: '1px solid var(--border)',
          display: 'flex', justifyContent: 'space-between', gap: 12,
        }}>
          <button onClick={prev} disabled={step === 0} style={{
            appearance: 'none', border: '1px solid var(--border-strong)',
            background: 'transparent', color: 'var(--text-muted)',
            padding: '10px 16px', borderRadius: 'var(--r-btn)',
            fontSize: 13, fontFamily: 'inherit', cursor: step === 0 ? 'not-allowed' : 'pointer',
            opacity: step === 0 ? 0.5 : 1,
          }}>← Voltar</button>
          {step < ONBOARDING_STEPS.length - 1 ? (
            <button onClick={next} style={btnAccentSmall}>Próximo →</button>
          ) : (
            <button onClick={finish} style={btnAccentSmall}>✨ Criar cliente automaticamente</button>
          )}
        </div>
      </BlockCard>
    </div>
  );
}

function OnboardingField({ field, value, onChange }) {
  const labelEl = (
    <span style={{ fontSize: 11, color: 'var(--text-faint)', letterSpacing: '0.04em', textTransform: 'uppercase' }}>
      {field.label}{field.required && ' *'}
    </span>
  );

  if (field.type === 'select') {
    return (
      <label style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
        {labelEl}
        <select value={value || ''} onChange={(e) => onChange(e.target.value)} style={inputStyle}>
          <option value="">Selecione...</option>
          {field.options.map(o => <option key={o} value={o}>{o}</option>)}
        </select>
      </label>
    );
  }
  if (field.type === 'toggle') {
    const checked = value != null ? value : field.default;
    return (
      <label style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        padding: '12px 14px',
        background: 'var(--surface)',
        border: '1px solid var(--border)',
        borderRadius: 'var(--r-btn)',
        cursor: 'pointer',
      }}>
        <span style={{ fontSize: 13, color: 'var(--text)', fontWeight: 500 }}>{field.label}</span>
        <button type="button" onClick={() => onChange(!checked)} style={{
          appearance: 'none', border: 'none',
          width: 40, height: 22, borderRadius: 999,
          background: checked ? 'var(--accent)' : 'var(--border-strong)',
          position: 'relative', cursor: 'pointer',
          transition: 'background var(--t-fast)',
        }}>
          <span style={{
            position: 'absolute', top: 2, left: checked ? 20 : 2,
            width: 18, height: 18, borderRadius: '50%',
            background: '#fff',
            transition: 'left var(--t-fast)',
          }} />
        </button>
      </label>
    );
  }
  if (field.type === 'checkboxes') {
    const current = value || [];
    const toggle = (id) => {
      onChange(current.includes(id) ? current.filter(x => x !== id) : [...current, id]);
    };
    return (
      <div>
        {labelEl}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: 8, marginTop: 8 }}>
          {field.options.map(o => {
            const active = current.includes(o.id);
            return (
              <button key={o.id} type="button" onClick={() => toggle(o.id)} style={{
                appearance: 'none', textAlign: 'left',
                padding: '10px 14px',
                background: active ? 'var(--accent-soft)' : 'var(--surface)',
                border: '1px solid', borderColor: active ? 'var(--accent)' : 'var(--border)',
                color: active ? 'var(--accent)' : 'var(--text)',
                borderRadius: 'var(--r-btn)',
                fontSize: 13, fontFamily: 'inherit', cursor: 'pointer',
                fontWeight: active ? 500 : 400,
                display: 'flex', alignItems: 'center', gap: 8,
              }}>
                <span style={{
                  width: 16, height: 16, borderRadius: 4,
                  background: active ? 'var(--accent)' : 'transparent',
                  border: '1.5px solid', borderColor: active ? 'var(--accent)' : 'var(--border-strong)',
                  color: '#fff', fontSize: 10, fontWeight: 700,
                  display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                }}>{active ? '✓' : ''}</span>
                {o.label}
              </button>
            );
          })}
        </div>
      </div>
    );
  }

  const Tag = field.multiline ? 'textarea' : 'input';
  return (
    <label style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
      {labelEl}
      <Tag
        type={field.multiline ? undefined : (field.type || 'text')}
        value={value || ''}
        onChange={(e) => onChange(e.target.value)}
        placeholder={field.placeholder}
        rows={field.multiline ? 3 : undefined}
        style={{ ...inputStyle, minHeight: field.multiline ? 72 : undefined, resize: field.multiline ? 'vertical' : undefined }}
      />
    </label>
  );
}

const inputStyle = {
  appearance: 'none',
  border: '1px solid var(--border-strong)',
  background: 'var(--surface)', color: 'var(--text)',
  padding: '9px 12px', borderRadius: 'var(--r-btn)',
  fontFamily: 'inherit', fontSize: 13, outline: 'none',
};

const btnAccentSmall = {
  appearance: 'none', border: '1px solid var(--accent)',
  background: 'var(--accent)', color: '#fff',
  padding: '10px 18px', borderRadius: 'var(--r-btn)',
  fontSize: 13, fontFamily: 'inherit', fontWeight: 500, cursor: 'pointer',
};

function OnboardingDone({ data, onStartOver }) {
  const steps = [
    { label: 'Ficha criada no CRM',                          icon: '✓', done: true },
    { label: 'Pasta criada no Drive da Beza',                icon: '✓', done: true },
    { label: 'Conta conectada no mLabs',                     icon: '✓', done: true },
    { label: 'Lista criada no ClickUp · 24 tarefas geradas', icon: '✓', done: true },
    { label: 'URL do relatório provisionada',                icon: '✓', done: true },
    { label: 'Entregas adicionadas no calendário de maio',   icon: '✓', done: true },
    { label: 'Time notificado no Slack',                     icon: '✓', done: true },
  ];

  return (
    <BlockCard>
      <div style={{ textAlign: 'center', padding: 'var(--space-5) 0' }}>
        <div style={{
          width: 64, height: 64, borderRadius: '50%',
          background: 'linear-gradient(135deg, var(--success), #4FA858)',
          color: '#fff', fontSize: 28,
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
          marginBottom: 16, boxShadow: '0 8px 24px rgba(111,200,120,0.30)',
        }}>✓</div>
        <h3 className="t-h2" style={{ margin: '0 0 8px' }}>
          <span className="t-light">Bem-vindo, </span>
          <span className="punch">{data.brand || 'novo cliente'}</span>
          <span className="t-light">.</span>
        </h3>
        <p style={{ margin: '0 auto', fontSize: 14, color: 'var(--text-muted)', maxWidth: 480, lineHeight: 1.6 }}>
          Onboarding executado. Tudo já está pronto pro time começar a produzir.
        </p>
      </div>

      <div style={{ maxWidth: 520, margin: '0 auto', display: 'flex', flexDirection: 'column', gap: 8 }}>
        {steps.map((s, i) => (
          <div key={i} style={{
            padding: '10px 14px',
            background: 'rgba(111,200,120,0.06)',
            border: '1px solid rgba(111,200,120,0.30)',
            borderRadius: 'var(--r-btn)',
            display: 'flex', alignItems: 'center', gap: 12,
            fontSize: 13,
          }}>
            <span style={{
              width: 22, height: 22, borderRadius: '50%',
              background: 'var(--success)', color: '#fff',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontSize: 11, fontWeight: 700,
            }}>{s.icon}</span>
            <span style={{ color: 'var(--text)' }}>{s.label}</span>
          </div>
        ))}
      </div>

      <div style={{ marginTop: 28, textAlign: 'center', display: 'flex', justifyContent: 'center', gap: 12, flexWrap: 'wrap' }}>
        <button style={btnAccentSmall}>Abrir ficha do {data.brand || 'cliente'} →</button>
        <button onClick={onStartOver} style={{ ...btnAccentSmall, background: 'transparent', color: 'var(--text-muted)', borderColor: 'var(--border-strong)' }}>
          + Adicionar outro
        </button>
      </div>
    </BlockCard>
  );
}

/* ============================================================
   SECTION · COMPARATIVOS · cross-client intelligence
   ============================================================ */
function SectionComparativos() {
  return (
    <div>
      <BlockCard kicker="cross-carteira" title="**Top performers** da Beza">
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))', gap: 12 }}>
          {CROSS_COMPARATIVES.topPerformers.map((tp, i) => (
            <div key={i} style={{
              padding: 16,
              background: 'var(--surface)',
              border: '1px solid var(--border)',
              borderLeft: '3px solid var(--accent)',
              borderRadius: 'var(--r-card)',
            }}>
              <div className="t-overline" style={{ color: 'var(--text-faint)', marginBottom: 6 }}>{tp.metric}</div>
              <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: 12, marginBottom: 4 }}>
                <span style={{ fontSize: 15, fontWeight: 500, color: 'var(--text)' }}>{tp.client}</span>
                <span className="num" style={{ fontSize: 20, fontWeight: 500, color: 'var(--accent)' }}>{tp.value}</span>
              </div>
              <div style={{ fontSize: 11, color: 'var(--text-faint)' }}>{tp.context}</div>
            </div>
          ))}
        </div>
      </BlockCard>

      <BlockCard kicker="por formato" title="Qual **formato** rende mais">
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {CROSS_COMPARATIVES.byFormat.map(f => {
            const maxReach = Math.max(...CROSS_COMPARATIVES.byFormat.map(x => x.avgReach));
            const pct = (f.avgReach / maxReach) * 100;
            return (
              <div key={f.format} style={{
                padding: '14px 16px',
                background: 'var(--surface)',
                border: '1px solid var(--border)',
                borderRadius: 'var(--r-btn)',
                display: 'grid', gridTemplateColumns: '180px 1fr 100px 140px', gap: 16, alignItems: 'center',
              }}>
                <span style={{ fontSize: 14, fontWeight: 500, color: 'var(--text)' }}>{f.format}</span>
                <div style={{ height: 10, background: 'var(--surface-soft)', borderRadius: 999, overflow: 'hidden', border: '1px solid var(--border)' }}>
                  <div style={{ height: '100%', width: pct + '%', background: 'linear-gradient(90deg, var(--accent), var(--beza-deep))', borderRadius: 999 }} />
                </div>
                <span className="num" style={{ fontSize: 14, fontWeight: 500, color: 'var(--text)', textAlign: 'right' }}>
                  {fmt.k(f.avgReach)} avg
                </span>
                <span style={{ fontSize: 11, color: 'var(--accent)', textAlign: 'right' }}>
                  líder: {f.leader.split(' ')[0]}
                </span>
              </div>
            );
          })}
        </div>
      </BlockCard>

      <BlockCard kicker="por segmento" title="Onde a Beza **performa melhor**">
        <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 14 }}>
          <thead>
            <tr style={{ background: 'var(--surface-soft)' }}>
              <th style={comparTh}>Segmento</th>
              <th style={{ ...comparTh, textAlign: 'center' }}>Clientes</th>
              <th style={{ ...comparTh, textAlign: 'right' }}>Alcance médio</th>
              <th style={{ ...comparTh, textAlign: 'right' }}>Eng. médio</th>
              <th style={{ ...comparTh, textAlign: 'right' }}>MRR</th>
              <th style={{ ...comparTh, textAlign: 'right' }}>Crescimento</th>
            </tr>
          </thead>
          <tbody>
            {CROSS_COMPARATIVES.bySegment.map(s => (
              <tr key={s.segment} style={{ borderTop: '1px solid var(--border)' }}>
                <td style={{ ...comparTd, fontWeight: 500 }}>{s.segment}</td>
                <td style={{ ...comparTd, textAlign: 'center', color: 'var(--text-muted)' }}>{s.clients}</td>
                <td style={{ ...comparTd, textAlign: 'right', fontVariantNumeric: 'tabular-nums', fontWeight: 500 }}>{fmt.k(s.avgReach)}</td>
                <td style={{ ...comparTd, textAlign: 'right', fontVariantNumeric: 'tabular-nums' }}>{fmt.dec(s.avgEngagement, 1)}%</td>
                <td style={{ ...comparTd, textAlign: 'right', fontVariantNumeric: 'tabular-nums' }}>{brlK(s.mrr)}</td>
                <td style={{ ...comparTd, textAlign: 'right', color: 'var(--success)', fontWeight: 500 }}>+{s.growth}%</td>
              </tr>
            ))}
          </tbody>
        </table>
        <p className="t-caption" style={{ color: 'var(--text-faint)', marginTop: 12, marginBottom: 0 }}>
          O segmento "Conteúdo cristão" tem o maior alcance médio e o crescimento mais rápido. Considerar foco vertical.
        </p>
      </BlockCard>
    </div>
  );
}

const comparTh = { padding: '12px 16px', textAlign: 'left', fontSize: 11, fontWeight: 500, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--text-faint)' };
const comparTd = { padding: '14px 16px', color: 'var(--text)' };

/* ============================================================
   SECTION · INBOX · caixa unificada
   ============================================================ */
function SectionInbox() {
  const [filter, setFilter] = useStateP3('todas');
  const [selectedId, setSelectedId] = useStateP3(INBOX.find(m => !m.read)?.id || INBOX[0].id);

  const filtered = INBOX.filter(m => {
    if (filter === 'nao-lidas') return !m.read;
    if (filter === 'oportunidades') return m.tags.includes('oportunidade') || m.tags.includes('upgrade') || m.tags.includes('negociacao');
    if (filter === 'risco') return m.tags.includes('risco') || m.tags.includes('reducao-escopo');
    if (filter === 'whatsapp') return m.channel === 'whatsapp';
    if (filter === 'email') return m.channel === 'email';
    return true;
  });

  const selected = INBOX.find(m => m.id === selectedId) || filtered[0];
  const tabs = [
    { id: 'todas',         label: 'Todas',          n: INBOX.length },
    { id: 'nao-lidas',     label: 'Não lidas',      n: INBOX.filter(m => !m.read).length },
    { id: 'oportunidades', label: 'Oportunidades',  n: INBOX.filter(m => m.tags.includes('oportunidade') || m.tags.includes('upgrade') || m.tags.includes('negociacao')).length },
    { id: 'risco',         label: 'Em risco',       n: INBOX.filter(m => m.tags.includes('risco') || m.tags.includes('reducao-escopo')).length },
    { id: 'whatsapp',      label: 'WhatsApp',       n: INBOX.filter(m => m.channel === 'whatsapp').length },
    { id: 'email',         label: 'E-mail',         n: INBOX.filter(m => m.channel === 'email').length },
  ];

  return (
    <BlockCard kicker="comunicação · todos os canais" title="**Caixa de entrada** unificada">
      <p style={{ margin: '0 0 18px', fontSize: 14, color: 'var(--text-muted)', maxWidth: 720, lineHeight: 1.6 }}>
        WhatsApp + e-mails + DMs de Instagram em uma fila só. Categorizado por cliente, sinalizado por urgência. Cada cliente vincula automaticamente ao CRM.
      </p>

      <div style={{ display: 'flex', gap: 6, marginBottom: 16, flexWrap: 'wrap' }}>
        {tabs.map(t => {
          const active = filter === t.id;
          return (
            <button key={t.id} onClick={() => setFilter(t.id)} style={{
              appearance: 'none', border: '1px solid',
              borderColor: active ? 'var(--accent)' : 'transparent',
              background: active ? 'var(--accent-soft)' : 'transparent',
              color: active ? 'var(--accent)' : 'var(--text-muted)',
              padding: '6px 12px', fontSize: 12,
              fontWeight: active ? 500 : 400,
              borderRadius: 'var(--r-pill)', cursor: 'pointer',
              fontFamily: 'inherit',
              display: 'inline-flex', alignItems: 'center', gap: 6,
            }}>
              {t.label}
              <span style={{ fontSize: 10, color: 'var(--text-faint)', fontVariantNumeric: 'tabular-nums' }}>{t.n}</span>
            </button>
          );
        })}
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0, 380px) minmax(0, 1fr)', gap: 14, minHeight: 460 }}>
        {/* List */}
        <div style={{
          background: 'var(--surface)', border: '1px solid var(--border)',
          borderRadius: 'var(--r-card)', overflow: 'auto', maxHeight: 560,
        }}>
          {filtered.length === 0 ? (
            <div style={{ padding: 40, textAlign: 'center', color: 'var(--text-faint)', fontSize: 13 }}>Nada por aqui.</div>
          ) : filtered.map(m => {
            const ch = CHANNEL_ICONS[m.channel];
            const isSelected = m.id === (selected && selected.id);
            return (
              <div key={m.id} onClick={() => setSelectedId(m.id)} style={{
                padding: 14,
                borderBottom: '1px solid var(--border)',
                background: isSelected ? 'var(--accent-soft)' : (!m.read ? 'rgba(154,155,229,0.04)' : 'transparent'),
                borderLeft: isSelected ? '3px solid var(--accent)' : '3px solid transparent',
                cursor: 'pointer',
                display: 'flex', gap: 12,
                transition: 'background var(--t-fast)',
              }}>
                <div style={{
                  width: 36, height: 36, borderRadius: '50%',
                  background: m.avatarColor, color: '#fff',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  fontSize: 14, fontWeight: 500, flexShrink: 0,
                  position: 'relative',
                }}>
                  {m.avatar}
                  <span title={ch.label} style={{
                    position: 'absolute', bottom: -2, right: -2,
                    width: 16, height: 16, borderRadius: '50%',
                    background: ch.color, color: '#fff',
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    fontSize: 9, border: '2px solid var(--bg-flat)',
                  }}>{ch.icon}</span>
                </div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 8 }}>
                    <span style={{ fontSize: 13, fontWeight: m.read ? 400 : 500, color: 'var(--text)' }}>
                      {m.contact}
                    </span>
                    <span style={{ fontSize: 10, color: 'var(--text-faint)', whiteSpace: 'nowrap' }}>
                      {m.receivedAt.split(' · ').slice(-1)[0]}
                    </span>
                  </div>
                  <div style={{ fontSize: 11, color: 'var(--accent)', marginBottom: 4 }}>{m.client}</div>
                  <div style={{
                    fontSize: 12, color: m.read ? 'var(--text-muted)' : 'var(--text)',
                    lineHeight: 1.4,
                    overflow: 'hidden', textOverflow: 'ellipsis',
                    display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical',
                    fontWeight: m.read ? 400 : 500,
                  }}>
                    {m.preview}
                  </div>
                  {m.priority === 'alta' && (
                    <span style={{
                      display: 'inline-block', marginTop: 6,
                      fontSize: 9, color: 'var(--error)', fontWeight: 500,
                      letterSpacing: '0.08em', textTransform: 'uppercase',
                      padding: '1px 6px', borderRadius: 999,
                      background: 'rgba(243,77,77,0.10)', border: '1px solid rgba(243,77,77,0.30)',
                    }}>urgente</span>
                  )}
                </div>
              </div>
            );
          })}
        </div>

        {/* Detail */}
        {selected && (
          <div style={{
            background: 'var(--surface)', border: '1px solid var(--border)',
            borderRadius: 'var(--r-card)', padding: 'var(--space-5)',
            display: 'flex', flexDirection: 'column', gap: 16,
          }}>
            <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 12, flexWrap: 'wrap' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
                <div style={{
                  width: 44, height: 44, borderRadius: '50%',
                  background: selected.avatarColor, color: '#fff',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  fontSize: 16, fontWeight: 500,
                }}>{selected.avatar}</div>
                <div>
                  <div style={{ fontSize: 16, fontWeight: 500, color: 'var(--text)' }}>{selected.contact}</div>
                  <div style={{ fontSize: 12, color: 'var(--accent)' }}>{selected.client}</div>
                </div>
              </div>
              <div style={{ display: 'inline-flex', gap: 6, flexWrap: 'wrap' }}>
                <Pill tone="purple">{CHANNEL_ICONS[selected.channel].label}</Pill>
                {selected.tags.map(t => <Pill key={t}>{t}</Pill>)}
              </div>
            </div>

            <div style={{ fontSize: 11, color: 'var(--text-faint)' }}>{selected.receivedAt}</div>

            <div style={{
              padding: 'var(--space-4)',
              background: 'var(--surface-soft)',
              border: '1px solid var(--border)',
              borderRadius: 'var(--r-card)',
              fontSize: 14, color: 'var(--text)', lineHeight: 1.6,
            }}>
              {selected.fullMessage}
            </div>

            <div style={{ paddingTop: 12, borderTop: '1px solid var(--border)', display: 'flex', gap: 10, flexWrap: 'wrap' }}>
              <button style={btnAccentSmall}>↩ Responder no {CHANNEL_ICONS[selected.channel].label}</button>
              <button style={{ ...btnAccentSmall, background: 'transparent', color: 'var(--text-muted)', borderColor: 'var(--border-strong)' }}>
                ✎ Anexar ao CRM
              </button>
              <button style={{ ...btnAccentSmall, background: 'transparent', color: 'var(--text-muted)', borderColor: 'var(--border-strong)' }}>
                ⊕ Criar tarefa
              </button>
            </div>
          </div>
        )}
      </div>
    </BlockCard>
  );
}

/* ============================================================
   SECTION · ALERTAS INTELIGENTES · upgrade da aba alertas
   ============================================================ */
function SectionAlertas() {
  const [filter, setFilter] = useStateP3('all');
  const filtered = filter === 'all' ? SMART_ALERTS : SMART_ALERTS.filter(a => a.severity === filter);
  const counts = {
    all:    SMART_ALERTS.length,
    high:   SMART_ALERTS.filter(a => a.severity === 'high').length,
    medium: SMART_ALERTS.filter(a => a.severity === 'medium').length,
    low:    SMART_ALERTS.filter(a => a.severity === 'low').length,
  };

  return (
    <div>
      <BlockCard kicker="✨ inteligência automática" title="**Alertas** que o sistema detecta sozinho">
        <p style={{ margin: '0 0 18px', fontSize: 14, color: 'var(--text-muted)', maxWidth: 720, lineHeight: 1.6 }}>
          O Claude analisa Pauta + ClickUp + relatórios + comunicação continuamente. Quando detecta um padrão que exige sua atenção, sobe aqui — com sugestão de ação concreta.
        </p>

        <div style={{ display: 'flex', gap: 6, marginBottom: 16, flexWrap: 'wrap' }}>
          {[
            { id: 'all',    label: 'Todos',         color: 'var(--accent)' },
            { id: 'high',   label: 'Urgentes',      color: 'var(--error)' },
            { id: 'medium', label: 'Importantes',   color: 'var(--warning)' },
            { id: 'low',    label: 'Informativos',  color: 'var(--info)' },
          ].map(t => {
            const active = filter === t.id;
            return (
              <button key={t.id} onClick={() => setFilter(t.id)} style={{
                appearance: 'none', border: '1px solid',
                borderColor: active ? t.color : 'var(--border)',
                background: active ? t.color + '15' : 'transparent',
                color: active ? t.color : 'var(--text-muted)',
                padding: '6px 12px', fontSize: 12,
                fontWeight: active ? 500 : 400,
                borderRadius: 'var(--r-pill)', cursor: 'pointer',
                fontFamily: 'inherit',
                display: 'inline-flex', alignItems: 'center', gap: 6,
              }}>
                {t.label}
                <span style={{ fontSize: 10, fontVariantNumeric: 'tabular-nums', opacity: 0.7 }}>{counts[t.id]}</span>
              </button>
            );
          })}
        </div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {filtered.map(a => {
            const meta = ALERT_SEVERITY_META[a.severity];
            return (
              <div key={a.id} style={{
                padding: 'var(--space-4)',
                background: meta.bg,
                border: `1px solid ${meta.color}40`,
                borderLeft: `3px solid ${meta.color}`,
                borderRadius: 'var(--r-card)',
                display: 'grid', gridTemplateColumns: '1fr auto', gap: 16, alignItems: 'flex-start',
              }}>
                <div>
                  <div style={{ display: 'flex', gap: 8, marginBottom: 6, flexWrap: 'wrap' }}>
                    <Pill tone="neutral" style={{ color: meta.color, borderColor: meta.color + '40' }}>{meta.label}</Pill>
                    <Pill>{a.type}</Pill>
                    {a.client && <Pill tone="purple">{a.client}</Pill>}
                    <span style={{ fontSize: 11, color: 'var(--text-faint)' }}>· detectado {a.detectedAt}</span>
                  </div>
                  <h4 style={{ margin: '4px 0 6px', fontSize: 15, fontWeight: 500, color: 'var(--text)', lineHeight: 1.4 }}>
                    {a.title}
                  </h4>
                  <p style={{ margin: 0, fontSize: 13, color: 'var(--text-muted)', lineHeight: 1.5 }}>
                    {a.detail}
                  </p>
                  <div style={{
                    marginTop: 10, padding: '8px 12px',
                    background: 'var(--surface)', border: '1px dashed var(--border-strong)',
                    borderRadius: 'var(--r-btn)',
                    fontSize: 12, color: 'var(--text)', lineHeight: 1.5,
                  }}>
                    <span style={{ color: 'var(--accent)', fontWeight: 500 }}>✨ Sugestão: </span>
                    {a.suggestion}
                  </div>
                </div>
                <button style={{
                  appearance: 'none', border: `1px solid ${meta.color}`,
                  background: meta.color, color: '#fff',
                  padding: '8px 14px', borderRadius: 'var(--r-btn)',
                  fontSize: 12, fontWeight: 500, fontFamily: 'inherit', cursor: 'pointer',
                  whiteSpace: 'nowrap',
                }}>
                  {a.action} →
                </button>
              </div>
            );
          })}
        </div>
      </BlockCard>
    </div>
  );
}

Object.assign(window, { SectionOnboarding, SectionComparativos, SectionInbox, SectionAlertas, SectionTeamPulse });

/* ============================================================
   SECTION · TEAM PULSE · visão do gestor sobre como o time está
   ----
   Lê do localStorage o que cada pessoa respondeu na MorningView
   (mood, intenção do dia) + status atual de foco + notas pessoais.
   ============================================================ */
const MOOD_DETAILS = {
  energia:   { emoji: '⚡', label: 'Cheio de energia',     color: '#6FC878', mgr: 'pode receber demanda extra' },
  foco:      { emoji: '🎯', label: 'Em foco',              color: '#9A9BE5', mgr: 'não interromper · deep work' },
  tranquilo: { emoji: '🌿', label: 'Tranquilo',             color: '#77B8F1', mgr: 'ritmo normal' },
  criativo:  { emoji: '🎨', label: 'Criativo',              color: '#F3AE4D', mgr: 'aproveitar pra brief de carrosseis' },
  cansado:   { emoji: '☕', label: 'Cansado',               color: '#8B89A3', mgr: 'aliviar carga · só essenciais' },
  ansioso:   { emoji: '🌀', label: 'Ansioso',               color: '#C7C6D7', mgr: 'check-in rápido + reorganizar' },
};

function SectionTeamPulse() {
  // 4 membros do time (sem gestores)
  const teamMembers = [
    { id: 'grazi',    name: 'Grazi',    role: 'Planejamento + Copy', color: '#9A9BE5', avatar: 'G' },
    { id: 'reinaldy', name: 'Reinaldy', role: 'Designer',            color: '#77B8F1', avatar: 'R' },
    { id: 'lucas',    name: 'Lucas',    role: 'Vídeo',               color: '#6FC878', avatar: 'L' },
  ];

  // Lê localStorage uma vez
  const moods   = useMemoP3(() => { try { return JSON.parse(localStorage.getItem('beza_morning_mood_v1') || '{}'); } catch { return {}; } }, []);
  const notes   = useMemoP3(() => { try { return JSON.parse(localStorage.getItem('beza_pauta_notes_v1') || '{}'); } catch { return {}; } }, []);
  const focus   = useMemoP3(() => { try { return JSON.parse(localStorage.getItem('beza_pauta_focus_v1') || '{}'); } catch { return {}; } }, []);
  const personal = useMemoP3(() => { try { return JSON.parse(localStorage.getItem('beza_pauta_personal_v1') || '{}'); } catch { return {}; } }, []);

  const todayDay = window.PAUTA_MONTH?.todayDay || 13;
  const year = window.PAUTA_MONTH?.year || 2026;

  // Status de cada pessoa
  const teamStatus = teamMembers.map(m => {
    const moodKey = `${year}-${todayDay}-${m.id}`;
    const moodId = moods[moodKey];
    const mood = moodId ? MOOD_DETAILS[moodId] : null;
    const note = notes[m.id] || '';
    const focusId = focus[m.id];
    const personalItems = personal[m.id] || [];
    const personalDone = personalItems.filter(p => p.done).length;

    // Tarefas do dia da Pauta
    const tasksToday = (window.TASKS || []).filter(t => t.assignee === m.id && t.dueDay === todayDay);
    const tasksDone = tasksToday.filter(t => ['publicado','aprovacao'].includes(t.status)).length;
    const tasksLate = (window.TASKS || []).filter(t => t.assignee === m.id && t.status === 'atrasada').length;

    return { ...m, mood, moodId, note, focusId, personalItems, personalDone, tasksToday, tasksDone, tasksLate };
  });

  // Quantos checkaram hoje
  const respondidos = teamStatus.filter(t => t.mood).length;
  const cansados = teamStatus.filter(t => t.moodId === 'cansado' || t.moodId === 'ansioso').length;

  return (
    <div>
      <BlockCard kicker="pulso da equipe · agora" title="**Como o time** está hoje">
        <p style={{ margin: '0 0 18px', fontSize: 14, color: 'var(--text-muted)', maxWidth: 720, lineHeight: 1.6 }}>
          Mood, intenção do dia e tarefas de cada pessoa. O time responde na própria tela de boas-vindas pela manhã — você vê o resultado consolidado aqui.
        </p>

        {/* KPIs topo */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(180px, 1fr))', gap: 12, marginBottom: 20 }}>
          <BigStat label="Check-in feito"     value={`${respondidos}/${teamMembers.length}`} accent={respondidos === teamMembers.length} sub={respondidos === teamMembers.length ? 'time todo respondeu' : 'esperando os outros'} />
          <BigStat label="Em estado de risco" value={cansados} sub="cansados ou ansiosos" tone={cansados > 0 ? 'warning' : undefined} />
          <BigStat label="Tarefas concluídas" value={teamStatus.reduce((a,t) => a + t.tasksDone, 0)} sub={`de ${teamStatus.reduce((a,t) => a + t.tasksToday.length, 0)} agendadas pra hoje`} />
          <BigStat label="Atrasadas no time" value={teamStatus.reduce((a,t) => a + t.tasksLate, 0)} tone={teamStatus.reduce((a,t) => a + t.tasksLate, 0) > 2 ? 'error' : undefined} />
        </div>

        {/* Card por pessoa */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(360px, 1fr))', gap: 14 }}>
          {teamStatus.map(t => {
            const hasMood = !!t.mood;
            const intentionStamp = t.note?.split('\n')[0]; // primeira linha (mais recente)
            const intentionStampClean = intentionStamp?.replace(/^\[[^\]]+\]\s*/, '');

            return (
              <div key={t.id} style={{
                padding: 'var(--space-4)',
                background: 'var(--surface)',
                border: '1px solid var(--border)',
                borderRadius: 'var(--r-card-lg)',
                display: 'flex', flexDirection: 'column', gap: 14,
                position: 'relative',
                overflow: 'hidden',
              }}>
                {/* Faixa lateral cor da pessoa */}
                <div style={{
                  position: 'absolute', top: 0, left: 0, bottom: 0,
                  width: 3, background: t.color,
                }} />

                {/* Cabeçalho */}
                <div style={{ display: 'flex', alignItems: 'center', gap: 12, paddingLeft: 6 }}>
                  <div style={{
                    width: 48, height: 48, borderRadius: '50%',
                    background: t.color, color: '#fff',
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    fontSize: 18, fontWeight: 500,
                  }}>{t.avatar}</div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 17, fontWeight: 500, color: 'var(--text)' }}>{t.name}</div>
                    <div style={{ fontSize: 12, color: 'var(--text-faint)' }}>{t.role}</div>
                  </div>
                  {!hasMood && (
                    <Pill tone="warning">⏳ ainda não checou</Pill>
                  )}
                </div>

                {/* MOOD */}
                <div style={{
                  padding: 'var(--space-3)',
                  background: hasMood ? t.mood.color + '12' : 'var(--surface-soft)',
                  border: hasMood ? `1px solid ${t.mood.color}30` : '1px dashed var(--border-strong)',
                  borderRadius: 'var(--r-card)',
                }}>
                  <div className="t-overline" style={{ color: hasMood ? t.mood.color : 'var(--text-faint)', marginBottom: 6 }}>
                    como está
                  </div>
                  {hasMood ? (
                    <>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                        <span style={{ fontSize: 24 }}>{t.mood.emoji}</span>
                        <span style={{ fontSize: 15, fontWeight: 500, color: 'var(--text)' }}>{t.mood.label}</span>
                      </div>
                      <div style={{
                        marginTop: 8, padding: '6px 10px',
                        background: 'var(--surface)',
                        borderLeft: `3px solid ${t.mood.color}`,
                        borderRadius: 4,
                        fontSize: 11, color: 'var(--text-muted)', lineHeight: 1.4,
                      }}>
                        <span style={{ color: 'var(--accent)', fontWeight: 500 }}>gestão: </span>
                        {t.mood.mgr}
                      </div>
                    </>
                  ) : (
                    <div style={{ fontSize: 13, color: 'var(--text-faint)' }}>
                      Sem check-in pra hoje. Talvez não tenha aberto o painel ainda.
                    </div>
                  )}
                </div>

                {/* INTENÇÃO DO DIA */}
                {intentionStampClean && (
                  <div style={{
                    padding: 'var(--space-3)',
                    background: 'var(--surface-soft)',
                    border: '1px solid var(--border)',
                    borderRadius: 'var(--r-card)',
                  }}>
                    <div className="t-overline" style={{ color: 'var(--text-faint)', marginBottom: 6 }}>
                      norte de hoje · escrito por {t.name}
                    </div>
                    <p style={{ margin: 0, fontSize: 13, color: 'var(--text)', lineHeight: 1.5, fontStyle: 'italic' }}>
                      "{intentionStampClean}"
                    </p>
                  </div>
                )}

                {/* TAREFAS DO DIA */}
                <div style={{
                  padding: 'var(--space-3)',
                  background: 'var(--surface-soft)',
                  border: '1px solid var(--border)',
                  borderRadius: 'var(--r-card)',
                }}>
                  <div className="t-overline" style={{ color: 'var(--text-faint)', marginBottom: 8 }}>tarefas de hoje</div>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 6 }}>
                    <span className="num" style={{ fontSize: 22, fontWeight: 500, color: 'var(--text)' }}>
                      {t.tasksDone}<span style={{ color: 'var(--text-faint)', fontWeight: 400 }}>/{t.tasksToday.length}</span>
                    </span>
                    {t.tasksLate > 0 && (
                      <Pill tone="error">{t.tasksLate} atrasada{t.tasksLate === 1 ? '' : 's'}</Pill>
                    )}
                  </div>
                  {t.tasksToday.length > 0 && (
                    <div style={{ height: 6, background: 'var(--surface)', borderRadius: 999, overflow: 'hidden', border: '1px solid var(--border)' }}>
                      <div style={{
                        height: '100%', width: ((t.tasksDone / t.tasksToday.length) * 100) + '%',
                        background: 'var(--success)', borderRadius: 999,
                      }} />
                    </div>
                  )}
                </div>

                {/* LEMBRETES PESSOAIS · só conta, não conteúdo (privado) */}
                {t.personalItems.length > 0 && (
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', fontSize: 11, color: 'var(--text-faint)', paddingTop: 8, borderTop: '1px solid var(--border)' }}>
                    <span>📝 {t.personalItems.length} lembrete{t.personalItems.length === 1 ? '' : 's'} pessoal · {t.personalDone} concluído{t.personalDone === 1 ? '' : 's'}</span>
                    <span style={{ fontStyle: 'italic', color: 'var(--text-faint)' }}>conteúdo privado</span>
                  </div>
                )}

                {/* CTA · check rápido */}
                <button style={{
                  appearance: 'none', border: '1px solid var(--border-strong)',
                  background: 'transparent', color: 'var(--text-muted)',
                  padding: '8px 12px', borderRadius: 'var(--r-btn)',
                  fontSize: 12, fontFamily: 'inherit', cursor: 'pointer',
                  display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 6,
                }}>
                  💬 Mandar mensagem rápida pra {t.name}
                </button>
              </div>
            );
          })}
        </div>

        {/* Privacidade · disclaimer */}
        <div style={{
          marginTop: 18, padding: '10px 14px',
          background: 'var(--surface-soft)', border: '1px solid var(--border)',
          borderRadius: 'var(--r-btn)',
          fontSize: 11, color: 'var(--text-faint)', lineHeight: 1.5,
        }}>
          🔒 <strong>Privacidade · </strong> mood + intenção do dia são compartilhados com a gestão. Notas pessoais e lembretes individuais permanecem privados de cada pessoa. O time foi avisado.
        </div>
      </BlockCard>
    </div>
  );
}
