/* global React, Icon, Pill, fmt,
   PROPOSALS, DAILY_CALENDAR, TEAM, STAGE_META,
   BlockCard, Punch, BigStat, brl, brlK */
const { useState: useStateP2, useMemo: useMemoP2 } = React;

/* ============================================================
   SECTION · PROPOSTAS · pipeline + gerador automático
   ============================================================ */
function SectionPropostas() {
  const [view, setView] = useStateP2('pipeline'); // pipeline · gerar

  return (
    <div>
      <div style={{
        display: 'inline-flex', gap: 4, padding: 4,
        background: 'var(--surface)', border: '1px solid var(--border)',
        borderRadius: 'var(--r-pill)', marginBottom: 'var(--space-5)',
      }}>
        {[
          { id: 'pipeline', label: '◐ Pipeline' },
          { id: 'gerar',    label: '✨ Gerar nova proposta' },
        ].map(v => {
          const active = view === v.id;
          return (
            <button key={v.id} onClick={() => setView(v.id)} style={{
              appearance: 'none', border: 'none',
              background: active ? 'var(--accent)' : 'transparent',
              color: active ? '#fff' : 'var(--text-muted)',
              padding: '8px 16px', fontSize: 13,
              fontWeight: active ? 500 : 400,
              borderRadius: 'var(--r-pill)', cursor: 'pointer',
              fontFamily: 'inherit', whiteSpace: 'nowrap',
            }}>{v.label}</button>
          );
        })}
      </div>

      {view === 'pipeline' ? <PropostaPipeline /> : <PropostaGerador />}
    </div>
  );
}

function PropostaPipeline() {
  const stages = ['qualificacao', 'reuniao', 'enviada', 'negociacao', 'perdida'];
  const grouped = stages.reduce((acc, s) => {
    acc[s] = PROPOSALS.filter(p => p.stage === s);
    return acc;
  }, {});

  const pipelineValue = PROPOSALS.filter(p => p.stage !== 'perdida').reduce((a, p) => a + p.monthly, 0);
  const closingValue = grouped.negociacao.reduce((a, p) => a + p.monthly, 0);

  return (
    <>
      <BlockCard kicker="estado do pipeline" title="**Propostas** em jogo">
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))', gap: 12 }}>
          <BigStat label="Valor em pipeline"   value={brlK(pipelineValue) + '/mês'} sub={PROPOSALS.filter(p => p.stage !== 'perdida').length + ' propostas ativas'} accent />
          <BigStat label="Próximas de fechar"  value={brlK(closingValue) + '/mês'} sub={grouped.negociacao.length + ' em negociação'} accent />
          <BigStat label="Aguardando"          value={grouped.enviada.length} sub="enviadas, sem resposta ainda" />
          <BigStat label="Perdidas · 30 dias"  value={grouped.perdida.length} tone={grouped.perdida.length > 1 ? 'warning' : undefined} />
        </div>
      </BlockCard>

      <BlockCard kicker="kanban" title="Por **estágio**">
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, minmax(180px, 1fr))', gap: 10, overflowX: 'auto' }}>
          {stages.map(s => {
            const items = grouped[s];
            const stageMeta = STAGE_META[s];
            return (
              <div key={s} style={{
                padding: 12,
                background: 'var(--surface-soft)',
                border: `1px solid var(--border)`,
                borderTop: `3px solid ${stageMeta.color}`,
                borderRadius: 'var(--r-card)',
                minHeight: 240,
              }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 10 }}>
                  <span className="t-overline" style={{ color: stageMeta.color }}>{stageMeta.label}</span>
                  <span className="num" style={{ fontSize: 12, color: 'var(--text-faint)' }}>{items.length}</span>
                </div>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                  {items.length === 0 && <span style={{ fontSize: 11, color: 'var(--text-faint)' }}>—</span>}
                  {items.map(p => (
                    <div key={p.id} style={{
                      padding: 10,
                      background: 'var(--surface)',
                      border: '1px solid var(--border)',
                      borderRadius: 'var(--r-btn)',
                    }}>
                      <div style={{ fontSize: 13, fontWeight: 500, color: 'var(--text)', marginBottom: 4, lineHeight: 1.3 }}>{p.lead}</div>
                      <div style={{ fontSize: 11, color: 'var(--text-faint)', marginBottom: 6 }}>{p.segment}</div>
                      {p.monthly > 0 && (
                        <div className="num" style={{ fontSize: 15, fontWeight: 500, color: 'var(--accent)' }}>{brlK(p.monthly)}/mês</div>
                      )}
                      {p.opens > 0 && (
                        <div style={{ fontSize: 10, color: 'var(--text-muted)', marginTop: 6, paddingTop: 6, borderTop: '1px solid var(--border)' }}>
                          {p.opens} aberturas · {p.lastOpen}
                        </div>
                      )}
                      {p.lossReason && (
                        <div style={{ fontSize: 10, color: 'var(--error)', marginTop: 6, paddingTop: 6, borderTop: '1px solid var(--border)', fontStyle: 'italic' }}>
                          {p.lossReason}
                        </div>
                      )}
                    </div>
                  ))}
                </div>
              </div>
            );
          })}
        </div>
      </BlockCard>
    </>
  );
}

/* ============================================================
   GERADOR DE PROPOSTAS · usa o modelo Beza
   ============================================================ */
const PROPOSAL_TEMPLATES = {
  'soldado-de-deus': {
    name: 'Soldado de Deus · padrão',
    description: 'Conteúdo cristão + YouTube · pacote completo',
    monthly: 6800,
    deliverables: { reels: 8, carrosseis: 4, banners: 4, fotos: 4, youtube: 4, stories: 'à vontade' },
    services: ['Planejamento estratégico mensal', 'Roteirização', 'Gravação na casa do cliente (4x/mês)', 'Edição completa de Reels e vídeos', 'Carrosseis com identidade visual aprovada', 'Banners e fotos institucionais', 'Stories diários (até 5/dia)', 'Relatório mensal com insights', 'Reunião quinzenal'],
  },
  'standard': {
    name: 'Standard · arquitetura/design',
    description: 'Padrão para arquitetos, designers, profissionais liberais',
    monthly: 4200,
    deliverables: { reels: 4, carrosseis: 4, banners: 2, fotos: 0, youtube: 0, stories: 'à vontade' },
    services: ['Planejamento estratégico mensal', 'Roteirização e copy', '4 Reels editados', '4 Carrosseis em identidade', '2 Banners promocionais', 'Stories diários (até 3/dia)', 'Relatório mensal'],
  },
  'premium-ecommerce': {
    name: 'Premium · e-commerce',
    description: 'Marcas com loja online e ticket alto',
    monthly: 7800,
    deliverables: { reels: 12, carrosseis: 6, banners: 4, fotos: 4, youtube: 0, stories: 'à vontade' },
    services: ['Estratégia mensal alinhada com calendário comercial', 'Roteirização e produção de copy', '12 Reels editados', '6 Carrosseis em identidade da marca', '4 Banners (promo + institucional)', 'Sessão de fotos mensal', 'Stories diários integrados ao planejamento', 'Tráfego pago (criativo + segmentação)', 'Relatório mensal com ROAS', 'Reunião quinzenal'],
  },
};

function PropostaGerador() {
  const [form, setForm] = useStateP2({
    template: 'standard',
    leadName: '',
    leadCompany: '',
    leadSegment: '',
    leadEmail: '',
    leadPhone: '',
    challenge: '',
    monthly: 4200,
    months: 12,
    customServices: '',
  });
  const [generated, setGenerated] = useStateP2(false);

  const tpl = PROPOSAL_TEMPLATES[form.template];

  // Atualiza valor + entregas quando troca o template
  const setTemplate = (id) => {
    const t = PROPOSAL_TEMPLATES[id];
    setForm(f => ({ ...f, template: id, monthly: t.monthly }));
  };

  const update = (k, v) => setForm(f => ({ ...f, [k]: v }));

  const handleGenerate = (e) => {
    e.preventDefault();
    setGenerated(true);
    setTimeout(() => document.getElementById('proposal-preview')?.scrollIntoView({ behavior: 'smooth' }), 100);
  };

  return (
    <BlockCard kicker="✨ comercial · automação" title="**Gerar** uma proposta nova">
      <p style={{ margin: '0 0 20px', fontSize: 14, color: 'var(--text-muted)', maxWidth: 720, lineHeight: 1.6 }}>
        Escolha o modelo, preencha os dados do lead e a Beza monta a proposta na linguagem da marca. Pronta para enviar como link rastreável ou exportar PDF.
      </p>

      <form onSubmit={handleGenerate} style={{ display: 'grid', gridTemplateColumns: 'minmax(0, 1fr) minmax(0, 1fr)', gap: 24 }}>
        {/* Coluna 1 · template */}
        <div>
          <div className="t-overline" style={{ color: 'var(--accent)', marginBottom: 10 }}>01 · modelo base</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginBottom: 24 }}>
            {Object.entries(PROPOSAL_TEMPLATES).map(([id, t]) => {
              const active = form.template === id;
              return (
                <button key={id} type="button" onClick={() => setTemplate(id)} style={{
                  appearance: 'none', textAlign: 'left',
                  padding: 14,
                  background: active ? 'var(--accent-soft)' : 'var(--surface)',
                  border: '1px solid',
                  borderColor: active ? 'var(--accent)' : 'var(--border)',
                  borderRadius: 'var(--r-card)',
                  cursor: 'pointer', fontFamily: 'inherit',
                  display: 'flex', flexDirection: 'column', gap: 6,
                }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
                    <span style={{ fontSize: 14, fontWeight: 500, color: active ? 'var(--accent)' : 'var(--text)' }}>{t.name}</span>
                    <span className="num" style={{ fontSize: 13, fontWeight: 500, color: active ? 'var(--accent)' : 'var(--text-muted)' }}>
                      {brlK(t.monthly)}/mês
                    </span>
                  </div>
                  <span style={{ fontSize: 12, color: 'var(--text-muted)', lineHeight: 1.4 }}>{t.description}</span>
                </button>
              );
            })}
          </div>

          <div className="t-overline" style={{ color: 'var(--accent)', marginBottom: 10 }}>02 · ajustes</div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
            <Field label="Valor mensal (R$)" type="number" value={form.monthly} onChange={(v) => update('monthly', +v)} />
            <Field label="Duração (meses)"   type="number" value={form.months}  onChange={(v) => update('months', +v)} />
          </div>
        </div>

        {/* Coluna 2 · lead */}
        <div>
          <div className="t-overline" style={{ color: 'var(--accent)', marginBottom: 10 }}>03 · dados do lead</div>
          <div style={{ display: 'grid', gap: 10 }}>
            <Field label="Nome do contato"      value={form.leadName}    onChange={(v) => update('leadName', v)} required />
            <Field label="Empresa/Projeto"      value={form.leadCompany} onChange={(v) => update('leadCompany', v)} required />
            <Field label="Segmento"             value={form.leadSegment} onChange={(v) => update('leadSegment', v)} placeholder="ex: cafeteria, clínica, e-commerce moda" />
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
              <Field label="E-mail"    type="email" value={form.leadEmail} onChange={(v) => update('leadEmail', v)} />
              <Field label="Telefone"               value={form.leadPhone} onChange={(v) => update('leadPhone', v)} />
            </div>
            <Field
              label="Desafio principal do cliente"
              value={form.challenge}
              onChange={(v) => update('challenge', v)}
              multiline
              placeholder="Em 1-2 frases. Ex: presença irregular nas redes, não converte seguidores em clientes, identidade visual fraca..."
            />
          </div>

          <button type="submit" style={{
            marginTop: 18, width: '100%',
            appearance: 'none', border: '1px solid var(--accent)',
            background: 'var(--accent)', color: '#fff',
            padding: '12px 18px', borderRadius: 'var(--r-btn)',
            fontSize: 14, fontWeight: 500, fontFamily: 'inherit',
            cursor: 'pointer',
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8,
          }}>
            ✨ Gerar proposta
          </button>
        </div>
      </form>

      {generated && form.leadCompany && (
        <ProposalPreview form={form} template={tpl} />
      )}
    </BlockCard>
  );
}

function Field({ label, value, onChange, type = 'text', multiline, placeholder, required }) {
  const Tag = multiline ? 'textarea' : 'input';
  return (
    <label style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
      <span style={{ fontSize: 11, color: 'var(--text-faint)', letterSpacing: '0.04em', textTransform: 'uppercase' }}>{label}{required && ' *'}</span>
      <Tag
        type={multiline ? undefined : type}
        value={value}
        onChange={(e) => onChange(e.target.value)}
        placeholder={placeholder}
        required={required}
        rows={multiline ? 3 : undefined}
        style={{
          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',
          resize: multiline ? 'vertical' : undefined,
          minHeight: multiline ? 72 : undefined,
        }}
      />
    </label>
  );
}

/* ============================================================
   PROPOSAL PREVIEW · usa o tom + estrutura da Beza
   ============================================================ */
function ProposalPreview({ form, template }) {
  const total = form.monthly * form.months;
  const linkSlug = form.leadCompany.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
  const proposalLink = `beza.media/proposta/${linkSlug}`;

  return (
    <div id="proposal-preview" style={{
      marginTop: 'var(--space-6)',
      padding: 'var(--space-5)',
      background: 'linear-gradient(135deg, rgba(154,155,229,0.10), rgba(154,155,229,0.02))',
      border: '1px solid rgba(154,155,229,0.30)',
      borderRadius: 'var(--r-card-lg)',
      animation: 'fadeUp 600ms var(--ease-out)',
    }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 16, marginBottom: 18, flexWrap: 'wrap' }}>
        <div>
          <div className="t-overline" style={{ color: 'var(--accent)', marginBottom: 6 }}>Pronta para enviar</div>
          <h3 className="t-h3" style={{ margin: 0 }}>
            <Punch text={`Proposta para **${form.leadCompany}**`} />
          </h3>
        </div>
        <div style={{ display: 'inline-flex', gap: 8, flexWrap: 'wrap' }}>
          <button onClick={() => navigator.clipboard?.writeText(proposalLink)} style={{
            appearance: 'none', border: '1px solid var(--border-strong)',
            background: 'var(--surface)', color: 'var(--text-muted)',
            padding: '8px 14px', borderRadius: 'var(--r-btn)',
            fontSize: 12, fontFamily: 'inherit', fontWeight: 500, cursor: 'pointer',
            display: 'inline-flex', alignItems: 'center', gap: 6,
          }}>⎘ Copiar link</button>
          <button onClick={() => {
            document.body.classList.add('print-proposal-only');
            setTimeout(() => {
              window.print();
              setTimeout(() => document.body.classList.remove('print-proposal-only'), 500);
            }, 100);
          }} style={{
            appearance: 'none', border: '1px solid var(--accent)',
            background: 'var(--accent)', color: '#fff',
            padding: '8px 14px', borderRadius: 'var(--r-btn)',
            fontSize: 12, fontFamily: 'inherit', fontWeight: 500, cursor: 'pointer',
            display: 'inline-flex', alignItems: 'center', gap: 6,
          }}>↓ Exportar PDF</button>
        </div>
      </div>

      {/* O documento da proposta */}
      <div style={{
        padding: 'var(--space-6)',
        background: 'var(--bg-flat)',
        border: '1px solid var(--border)',
        borderRadius: 'var(--r-card)',
        maxWidth: 760, margin: '0 auto',
      }}>
        <div className="t-overline" style={{ color: 'var(--accent)', marginBottom: 10 }}>Beza Media · proposta</div>
        <h2 className="t-h1" style={{ margin: '0 0 20px', textWrap: 'pretty' }}>
          <span className="t-light">Construindo estruturas para a </span>
          <span className="punch">{form.leadCompany}</span>
          <span className="t-light">.</span>
        </h2>

        <ProposalSection title="O que vimos">
          <p>{form.leadName ? <><strong>{form.leadName}</strong>, </> : ''}{form.challenge || `${form.leadCompany} tem uma marca com substância mas presença irregular nas redes. O que aparece hoje não traduz o que vocês entregam no produto/serviço.`}</p>
          <p>É o tipo de problema que a Beza resolve: dar consistência sem perder a alma da marca, construir estrutura sem engessar a voz.</p>
        </ProposalSection>

        <ProposalSection title="Nossa proposta">
          <p>Pacote <strong>{template.name}</strong> · contrato de {form.months} meses.</p>
          <ul style={{ margin: '12px 0 0', paddingLeft: 20, display: 'flex', flexDirection: 'column', gap: 6 }}>
            {template.services.map((s, i) => (
              <li key={i} style={{ fontSize: 14, lineHeight: 1.5, color: 'var(--text)' }}>{s}</li>
            ))}
          </ul>
        </ProposalSection>

        <ProposalSection title="Entregas mensais">
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(120px, 1fr))', gap: 10, marginTop: 8 }}>
            {Object.entries(template.deliverables).filter(([, v]) => v && v !== 0).map(([k, v]) => (
              <div key={k} style={{
                padding: 14, textAlign: 'center',
                background: 'var(--accent-soft)', border: '1px solid rgba(154,155,229,0.30)',
                borderRadius: 'var(--r-card)',
              }}>
                <div className="num" style={{ fontSize: 24, fontWeight: 500, color: 'var(--accent)' }}>{v}</div>
                <div style={{ fontSize: 11, color: 'var(--text-muted)', textTransform: 'capitalize', marginTop: 2 }}>{k}</div>
              </div>
            ))}
          </div>
        </ProposalSection>

        <ProposalSection title="Investimento">
          <div style={{
            padding: 20, background: 'var(--surface)',
            border: '1px solid var(--border-strong)',
            borderRadius: 'var(--r-card)',
            display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16,
          }}>
            <div>
              <div className="t-overline" style={{ color: 'var(--text-faint)', marginBottom: 4 }}>Mensalidade</div>
              <div className="num" style={{ fontSize: 28, fontWeight: 500, color: 'var(--accent)' }}>{brl(form.monthly)}</div>
            </div>
            <div>
              <div className="t-overline" style={{ color: 'var(--text-faint)', marginBottom: 4 }}>Total · {form.months} meses</div>
              <div className="num" style={{ fontSize: 28, fontWeight: 500, color: 'var(--text)' }}>{brl(total)}</div>
            </div>
          </div>
        </ProposalSection>

        <ProposalSection title="Próximos passos">
          <p>Se fizer sentido, agendamos uma call de 30 minutos para alinhar detalhes e iniciar o onboarding ainda esta semana.</p>
          <p style={{ marginTop: 12, fontSize: 12, color: 'var(--text-faint)', fontStyle: 'italic' }}>
            Proposta válida por 14 dias. Após esse prazo, valores e disponibilidade podem mudar.
          </p>
        </ProposalSection>

        <div style={{ marginTop: 28, paddingTop: 18, borderTop: '1px solid var(--border)', textAlign: 'center' }}>
          <div className="t-overline" style={{ color: 'var(--accent)', marginBottom: 4 }}>Construindo estruturas para o extraordinário.</div>
          <div style={{ fontSize: 11, color: 'var(--text-faint)' }}>Beza Media · {proposalLink}</div>
        </div>
      </div>

      <div style={{
        marginTop: 16, padding: '10px 14px',
        background: 'var(--surface-soft)', border: '1px dashed var(--border-strong)',
        borderRadius: 'var(--r-btn)',
        fontSize: 12, color: 'var(--text-muted)', textAlign: 'center',
      }}>
        🔗 link único: <span style={{ fontFamily: 'monospace', color: 'var(--accent)' }}>{proposalLink}</span> · rastreia aberturas e expira em 14 dias
      </div>
    </div>
  );
}

function ProposalSection({ title, children }) {
  return (
    <div style={{ marginBottom: 20 }}>
      <div className="t-overline" style={{ color: 'var(--accent)', marginBottom: 8 }}>{title}</div>
      <div style={{ fontSize: 14, lineHeight: 1.65, color: 'var(--text)' }}>{children}</div>
    </div>
  );
}

/* ============================================================
   SECTION · CALENDÁRIO · grade tipo Google Sheets · gestor sobe
   demandas, time recebe automaticamente na Pauta.
   ============================================================ */
const CAL_LS_KEY = 'beza_gestao_calendar_v1';

function SectionCalendario() {
  const today = DAILY_CALENDAR.todayDay;
  const teamMembers = (window.TEAM || [
    { id: 'grazi',    name: 'Grazi',    role: 'Planejamento + Copy', color: '#9A9BE5' },
    { id: 'reinaldy', name: 'Reinaldy', role: 'Designer',            color: '#77B8F1' },
    { id: 'lucas',    name: 'Lucas',    role: 'Vídeo',               color: '#6FC878' },
  ]);

  // Edits feitos pelo gestor (override por célula); persiste local
  const [edits, setEdits] = useStateP2(() => {
    try { return JSON.parse(localStorage.getItem(CAL_LS_KEY) || '{}'); } catch { return {}; }
  });
  const [editing, setEditing] = useStateP2(null); // { day, memberId }

  useEffectGS(() => {
    try { localStorage.setItem(CAL_LS_KEY, JSON.stringify(edits)); } catch (e) {}
  }, [edits]);

  // Mês completo · 31 dias de maio/2026 + bridge dos primeiros dias de junho
  // quando estamos próximos do fim do mês
  const daysInMonth = 31;
  const daysToShowNextMonth = (daysInMonth - today) <= 7 ? 7 : 0;
  const allDays = [
    ...Array.from({ length: daysInMonth }, (_, i) => ({ day: i + 1, month: 'mai' })),
    ...Array.from({ length: daysToShowNextMonth }, (_, i) => ({ day: i + 1, month: 'jun' })),
  ];

  const getDayLabel = (d, m) => {
    // 1 de maio 2026 = sexta (5), 1 de junho 2026 = segunda (1)
    const baseOffset = m === 'mai' ? 5 : 1;
    const dow = (baseOffset + d - 1) % 7;
    return ['DOM','SEG','TER','QUA','QUI','SEX','SÁB'][dow];
  };
  const isWeekend = (d, m) => {
    const baseOffset = m === 'mai' ? 5 : 1;
    const dow = (baseOffset + d - 1) % 7;
    return dow === 0 || dow === 6;
  };

  const cellKey = (d, m, memberId) => `${m}-${d}::${memberId}`;

  // Retorna o foco do dia para a pessoa (override OU dado mock OU vazio)
  const getCellContent = (d, m, member) => {
    const key = cellKey(d, m, member.id);
    if (edits[key] != null) return edits[key];
    if (m !== 'mai') return ''; // junho ainda vazio
    const dayData = DAILY_CALENDAR.days[d];
    if (!dayData || !dayData[member.id]) return '';
    return dayData[member.id].map(t => `${t.client} · ${t.title}`).join('\n');
  };

  // Verifica se as tarefas daquele dia/pessoa estão concluídas (mock baseado nos dados da pauta)
  const isCellComplete = (d, m, member) => {
    if (m !== 'mai') return false;
    const dayData = DAILY_CALENDAR.days[d];
    if (!dayData || !dayData[member.id]) return false;
    const tasks = dayData[member.id];
    return tasks.length > 0 && tasks.every(t => t.done);
  };

  const setCellContent = (d, m, memberId, text) => {
    setEdits(prev => ({ ...prev, [cellKey(d, m, memberId)]: text }));
  };

  // Stats globais
  const filledCells = allDays.flatMap(({day, month}) => teamMembers.map(m => getCellContent(day, month, m))).filter(Boolean).length;
  const totalCells = allDays.length * teamMembers.length;
  const completedCells = allDays.flatMap(({day, month}) => teamMembers.map(m => isCellComplete(day, month, m))).filter(Boolean).length;

  return (
    <div>
      <BlockCard kicker="você controla, o time recebe" title="**Calendário** do mês · tabela editável">
        <p style={{ margin: '0 0 18px', fontSize: 14, color: 'var(--text-muted)', maxWidth: 720, lineHeight: 1.6 }}>
          Funciona como a planilha da pauta, mas tudo dentro da Beza. Clique em qualquer célula para adicionar o foco daquela pessoa naquele dia. Aparece automaticamente no painel de Pauta de cada um. Mudanças são salvas localmente em tempo real.
        </p>

        {/* Stats topo */}
        <div style={{
          display: 'flex', gap: 24, padding: '12px 16px',
          background: 'var(--surface-soft)', border: '1px solid var(--border)',
          borderRadius: 'var(--r-btn)', marginBottom: 16, flexWrap: 'wrap',
        }}>
          <CalStat label="Mês"           value={DAILY_CALENDAR.month} />
          <CalStat label="Hoje"          value={`${today} (${getDayLabel(today, 'mai')})`} accent />
          <CalStat label="Células preenchidas" value={`${filledCells} / ${totalCells}`} />
          <CalStat label="Concluídas pelo time" value={completedCells} accent />
          <CalStat label="Time"          value={`${teamMembers.length} pessoas`} />
          <div style={{ marginLeft: 'auto', display: 'inline-flex', gap: 8 }}>
            <button onClick={() => { if (confirm('Limpar todas as suas marcações? Os dados originais (mock) voltam.')) setEdits({}); }} style={btnGhostGS}>
              ↻ resetar marcações
            </button>
            <button style={{ ...btnGhostGS, color: 'var(--accent)', borderColor: 'rgba(154,155,229,0.30)' }}>
              ✨ colar da planilha
            </button>
          </div>
        </div>

        {/* Grade tipo Google Sheets */}
        <div style={{
          border: '1px solid var(--border)',
          borderRadius: 'var(--r-card)',
          overflow: 'auto', maxHeight: 640,
          background: 'var(--surface)',
        }}>
          <table style={{
            width: '100%', borderCollapse: 'separate', borderSpacing: 0,
            fontSize: 13, fontFamily: 'inherit',
            minWidth: 760,
          }}>
            <thead style={{ position: 'sticky', top: 0, zIndex: 2 }}>
              <tr>
                <th style={{ ...calTh, width: 100, position: 'sticky', left: 0, zIndex: 3, background: 'var(--surface-strong)' }}>Dia</th>
                {teamMembers.map(m => (
                  <th key={m.id} style={{ ...calTh, borderTop: `3px solid ${m.color}` }}>
                    <div style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}>
                      <span style={{
                        width: 22, height: 22, borderRadius: '50%',
                        background: m.color, color: '#fff',
                        display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                        fontSize: 10, fontWeight: 500,
                      }}>{m.name[0]}</span>
                      <span style={{ fontSize: 13, fontWeight: 500, color: 'var(--text)', letterSpacing: 0, textTransform: 'none' }}>
                        {m.name}
                      </span>
                      <span style={{ fontSize: 10, color: 'var(--text-faint)', letterSpacing: 0, textTransform: 'none', fontWeight: 400 }}>
                        · {m.role}
                      </span>
                    </div>
                  </th>
                ))}
              </tr>
            </thead>
            <tbody>
              {allDays.map(({day: d, month: m}, idx) => {
                const isToday = d === today && m === 'mai';
                const weekend = isWeekend(d, m);
                const dayLabel = getDayLabel(d, m);
                const isNextMonth = m === 'jun';
                const isMonthBoundary = isNextMonth && idx > 0 && allDays[idx-1].month === 'mai';
                return (
                  <React.Fragment key={`${m}-${d}`}>
                    {isMonthBoundary && (
                      <tr>
                        <td colSpan={teamMembers.length + 1} style={{
                          padding: '12px 16px',
                          background: 'linear-gradient(90deg, rgba(154,155,229,0.10), transparent)',
                          borderTop: '2px solid var(--accent)',
                          borderBottom: '1px solid var(--border)',
                        }}>
                          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                            <span className="t-overline" style={{ color: 'var(--accent)' }}>
                              → Junho 2026 · próximo mês
                            </span>
                            <span style={{ fontSize: 11, color: 'var(--text-faint)' }}>
                              comece a planejar enquanto fecha maio
                            </span>
                          </div>
                        </td>
                      </tr>
                    )}
                    <tr style={{
                      background: isToday ? 'rgba(154,155,229,0.06)' : (weekend ? 'var(--surface-soft)' : 'transparent'),
                      opacity: isNextMonth ? 0.85 : 1,
                    }}>
                      <td style={{
                        ...calTdDay,
                        position: 'sticky', left: 0,
                        background: isToday ? 'rgba(154,155,229,0.12)' : (weekend ? 'var(--surface-soft)' : 'var(--surface)'),
                        borderLeft: isToday ? '3px solid var(--accent)' : '3px solid transparent',
                      }}>
                        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                          <div>
                            <div style={{ fontSize: 10, color: isToday ? 'var(--accent)' : 'var(--text-faint)', fontWeight: 500, letterSpacing: '0.08em' }}>
                              {dayLabel}{isNextMonth ? ' · jun' : ''}
                            </div>
                            <div className="num" style={{ fontSize: 20, fontWeight: isToday ? 500 : 400, color: isToday ? 'var(--accent)' : 'var(--text)' }}>
                              {d}
                            </div>
                          </div>
                          {isToday && (
                            <span style={{
                              fontSize: 9, color: '#fff', background: 'var(--accent)',
                              padding: '2px 6px', borderRadius: 999, letterSpacing: '0.08em',
                              textTransform: 'uppercase', fontWeight: 500,
                            }}>hoje</span>
                          )}
                        </div>
                      </td>
                      {teamMembers.map(member => {
                        const content = getCellContent(d, m, member);
                        const complete = isCellComplete(d, m, member);
                        const isEditing = editing && editing.day === d && editing.month === m && editing.memberId === member.id;
                        return (
                          <td
                            key={member.id}
                            onClick={() => !isEditing && setEditing({ day: d, month: m, memberId: member.id })}
                            style={{
                              ...calTdCell,
                              background: isEditing ? 'rgba(154,155,229,0.05)' : 'transparent',
                              borderLeft: `1px solid var(--border)`,
                              cursor: isEditing ? 'text' : 'pointer',
                            }}>
                            {isEditing ? (
                              <textarea
                                autoFocus
                                defaultValue={content}
                                onBlur={(e) => { setCellContent(d, m, member.id, e.target.value); setEditing(null); }}
                                onKeyDown={(e) => {
                                  if (e.key === 'Escape') setEditing(null);
                                  if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) {
                                    setCellContent(d, m, member.id, e.currentTarget.value);
                                    setEditing(null);
                                  }
                                }}
                                style={{
                                  width: '100%', minHeight: 80, resize: 'vertical',
                                  appearance: 'none', border: `2px solid ${member.color}`,
                                  background: 'var(--bg-flat)', color: 'var(--text)',
                                  padding: 8, borderRadius: 'var(--r-btn)',
                                  fontFamily: 'inherit', fontSize: 12, lineHeight: 1.4,
                                  outline: 'none',
                                }}
                                placeholder="Foco do dia · ex: Brady · 4 reels"
                              />
                            ) : content ? (
                              <div style={{
                                padding: '8px 10px', borderRadius: 'var(--r-btn)',
                                background: complete ? 'rgba(111,200,120,0.12)' : member.color + '12',
                                border: complete ? '1px solid rgba(111,200,120,0.30)' : `1px solid ${member.color}30`,
                                borderLeft: complete ? '3px solid var(--success)' : `3px solid ${member.color}`,
                                fontSize: 12, lineHeight: 1.4, color: 'var(--text)',
                                whiteSpace: 'pre-wrap',
                                minHeight: 38,
                                position: 'relative',
                              }}>
                                {complete && (
                                  <span style={{
                                    position: 'absolute', top: 6, right: 6,
                                    width: 16, height: 16, borderRadius: '50%',
                                    background: 'var(--success)', color: '#fff',
                                    display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                                    fontSize: 10, fontWeight: 700,
                                  }} title="Time concluíu essa demanda">✓</span>
                                )}
                                <span style={{
                                  color: complete ? 'var(--text-muted)' : 'var(--text)',
                                  textDecoration: complete ? 'line-through' : 'none',
                                }}>{content}</span>
                              </div>
                            ) : (
                              <div style={{
                                padding: '12px 10px', textAlign: 'center',
                                color: 'var(--text-faint)', fontSize: 11,
                                border: '1px dashed var(--border)',
                                borderRadius: 'var(--r-btn)',
                                minHeight: 38, display: 'flex', alignItems: 'center', justifyContent: 'center',
                              }}>
                                + adicionar
                              </div>
                            )}
                          </td>
                        );
                      })}
                    </tr>
                  </React.Fragment>
                );
              })}
            </tbody>
          </table>
        </div>

        <div style={{ marginTop: 14, padding: '10px 14px', background: 'var(--surface-soft)', border: '1px solid var(--border)', borderRadius: 'var(--r-btn)', display: 'flex', justifyContent: 'space-between', flexWrap: 'wrap', gap: 12, fontSize: 12 }}>
          <span style={{ color: 'var(--text-faint)' }}>
            Clique numa célula para editar · <kbd style={kbd}>Esc</kbd> cancela · <kbd style={kbd}>⌘ ↵</kbd> salva
          </span>
          <span style={{ color: 'var(--success)', display: 'inline-flex', alignItems: 'center', gap: 6 }}>
            <span style={{ width: 8, height: 8, borderRadius: '50%', background: 'currentColor', border: '2px solid var(--bg-flat)' }} />
            <span style={{ color: 'var(--text-muted)' }}>verde = time concluíu</span>
            <span style={{ color: 'var(--text-faint)', marginLeft: 4 }}>·</span>
            <span style={{ color: 'var(--text-muted)' }}>sincroniza com a Pauta a cada 5min</span>
          </span>
        </div>
      </BlockCard>
    </div>
  );
}

function CalStat({ label, value, accent }) {
  return (
    <div>
      <div className="t-overline" style={{ color: 'var(--text-faint)', fontSize: 10, marginBottom: 2 }}>{label}</div>
      <div style={{ fontSize: 14, fontWeight: 500, color: accent ? 'var(--accent)' : 'var(--text)' }}>{value}</div>
    </div>
  );
}

const calTh = {
  padding: '12px 14px', textAlign: 'left',
  fontSize: 11, fontWeight: 500, letterSpacing: '0.08em', textTransform: 'uppercase',
  color: 'var(--text-faint)',
  background: 'var(--surface-strong)',
  borderBottom: '1px solid var(--border)',
};

const calTdDay = {
  padding: '10px 12px', verticalAlign: 'top',
  borderBottom: '1px solid var(--border)',
  width: 100, minWidth: 100,
};

const calTdCell = {
  padding: '6px 8px', verticalAlign: 'top',
  borderBottom: '1px solid var(--border)',
  minWidth: 180,
};

const btnGhostGS = {
  appearance: 'none', border: '1px solid var(--border-strong)',
  background: 'transparent', color: 'var(--text-muted)',
  fontSize: 11, padding: '5px 10px',
  borderRadius: 999, cursor: 'pointer', fontFamily: 'inherit',
};

const kbd = {
  padding: '1px 5px', fontSize: 10,
  background: 'var(--surface)', border: '1px solid var(--border-strong)',
  borderRadius: 4, fontFamily: 'monospace', color: 'var(--text)',
};

// useEffect alias para escopo deste arquivo
const useEffectGS = React.useEffect;

Object.assign(window, { SectionPropostas, SectionCalendario, SectionAllHands });

/* ============================================================
   SECTION · ALL HANDS · cópia consolidada da reunião de segunda
   ----
   Reaproveita o que o time vê na Pauta, mas com lente de gestão:
   contexto cumulativo, decisões pendentes, countdown da próxima.
   ============================================================ */
function SectionAllHands() {
  const meeting = window.LAST_MEETING;
  if (!meeting) {
    return (
      <BlockCard>
        <p style={{ color: 'var(--text-muted)', margin: 0 }}>Carregando dados da última All Hands...</p>
      </BlockCard>
    );
  }

  // Countdown até a próxima All Hands (segunda 09h)
  const [now, setNow] = useStateP2(Date.now());
  useEffectP2(() => {
    const id = setInterval(() => setNow(Date.now()), 60000);
    return () => clearInterval(id);
  }, []);

  // Próxima segunda às 09h em maio/2026 (manualmente · 18 de maio)
  const nextDate = new Date(2026, 4, 18, 9, 0, 0);
  const diff = nextDate.getTime() - now;
  const days = Math.max(0, Math.floor(diff / 86400000));
  const hours = Math.max(0, Math.floor((diff % 86400000) / 3600000));
  const minutes = Math.max(0, Math.floor((diff % 3600000) / 60000));

  const TEAM = window.TEAM || [];
  const totalActions = meeting.actionItems.length;
  const completedActions = 0; // mock

  return (
    <div>
      {/* Status faixa */}
      <BlockCard kicker="hub da All Hands · segundas" title={`Última: **${meeting.date}** · próxima em ${days}d ${hours}h ${minutes}min`}>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(180px, 1fr))', gap: 12, marginBottom: 18 }}>
          <BigStat label="Última reunião" value={meeting.date} sub={`${meeting.durationMin}min · ${meeting.attendees.length} presentes`} />
          <BigStat label="Decisões" value={meeting.decisions.length} sub="da última call" accent />
          <BigStat label="Ações em aberto" value={totalActions - completedActions} sub={`${completedActions} concluídas`} tone={totalActions - completedActions > 3 ? 'warning' : undefined} />
          <BigStat label="Próxima" value={`em ${days}d`} sub="segunda · 09h" accent />
        </div>

        <div style={{
          padding: 'var(--space-4)',
          background: 'linear-gradient(135deg, rgba(154,155,229,0.10), rgba(154,155,229,0.02))',
          border: '1px solid rgba(154,155,229,0.30)',
          borderRadius: 'var(--r-card)',
        }}>
          <div className="t-overline" style={{ color: 'var(--accent)', marginBottom: 8 }}>resumo</div>
          <p style={{ margin: 0, fontSize: 15, color: 'var(--text)', lineHeight: 1.6 }}>
            {meeting.summary}
          </p>
        </div>
      </BlockCard>

      {/* Decisões */}
      <BlockCard kicker="01 · decisões" title="O que **ficou definido**">
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {meeting.decisions.map(d => {
            const who = d.who ? TEAM.find(t => t.id === d.who) : null;
            return (
              <div key={d.id} style={{
                padding: 14,
                background: 'var(--surface)',
                border: '1px solid var(--border)',
                borderLeft: '3px solid var(--accent)',
                borderRadius: 'var(--r-card)',
                display: 'grid', gridTemplateColumns: '32px 1fr', gap: 14, alignItems: 'flex-start',
              }}>
                <span style={{
                  width: 26, height: 26, borderRadius: '50%',
                  background: 'var(--accent-soft)', color: 'var(--accent)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  fontWeight: 500, fontSize: 12, marginTop: 1,
                }}>✓</span>
                <div>
                  <div style={{ fontSize: 14, color: 'var(--text)', lineHeight: 1.5 }}>{d.text}</div>
                  {who && (
                    <div style={{ marginTop: 8, display: 'inline-flex' }}>
                      <Pill tone="purple">Resp. · {who.name}</Pill>
                    </div>
                  )}
                </div>
              </div>
            );
          })}
        </div>
      </BlockCard>

      {/* Ações + Avisos lado a lado */}
      <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0, 1.4fr) minmax(0, 1fr)', gap: 'var(--space-5)' }}>
        <BlockCard kicker="02 · ações com prazo" title="**Pra fazer** até a próxima call">
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {meeting.actionItems.map(ai => {
              const who = ai.who ? TEAM.find(t => t.id === ai.who) : null;
              return (
                <div key={ai.id} style={{
                  padding: 12,
                  background: 'var(--surface)',
                  border: '1px solid var(--border)',
                  borderRadius: 'var(--r-btn)',
                  display: 'grid', gridTemplateColumns: '24px 1fr auto auto', gap: 12, alignItems: 'center',
                }}>
                  <span style={{
                    width: 18, height: 18, borderRadius: '50%',
                    border: '1.5px solid var(--border-strong)',
                  }} />
                  <span style={{ fontSize: 13, color: 'var(--text)', lineHeight: 1.4 }}>{ai.text}</span>
                  <span style={{ fontSize: 11, color: 'var(--text-faint)', whiteSpace: 'nowrap' }}>dia {ai.due}</span>
                  {who && (
                    <span style={{
                      width: 22, height: 22, borderRadius: '50%',
                      background: who.color, color: '#fff',
                      display: 'flex', alignItems: 'center', justifyContent: 'center',
                      fontSize: 10, fontWeight: 500,
                    }}>{who.avatar}</span>
                  )}
                </div>
              );
            })}
          </div>
        </BlockCard>

        <BlockCard kicker="03 · mural" title="**Avisos** internos">
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {meeting.announcements.map(a => {
              const toneMap = {
                info:    { color: 'var(--accent)',  bg: 'rgba(119,184,241,0.08)' },
                warning: { color: 'var(--warning)', bg: 'rgba(243,174,77,0.10)' },
                success: { color: 'var(--success)', bg: 'rgba(111,200,120,0.10)' },
              };
              const t = toneMap[a.tone] || toneMap.info;
              return (
                <div key={a.id} style={{
                  padding: 12,
                  background: t.bg,
                  border: `1px solid ${t.color}40`,
                  borderLeft: `3px solid ${t.color}`,
                  borderRadius: 'var(--r-btn)',
                  fontSize: 13, color: 'var(--text)', lineHeight: 1.5,
                }}>
                  {a.text}
                </div>
              );
            })}
          </div>
        </BlockCard>
      </div>

      {/* Auto-sync · próxima All Hands */}
      <BlockCard kicker="✨ automação" title="Como **alimenta** este painel">
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: 12 }}>
          <SyncStep n={1} label="Toda segunda 09h"      sub="você grava a All Hands com o time" />
          <SyncStep n={2} label="Sobe a transcrição"    sub="cola o texto aqui ou usa a integração com o Meet" />
          <SyncStep n={3} label="Claude organiza"       sub="extrai decisões, ações, avisos e atualiza a Pauta" />
          <SyncStep n={4} label="Painel vivo"           sub="você e o time veem o histórico cumulativo no próprio dashboard" />
        </div>

        <div style={{ marginTop: 18, display: 'flex', gap: 10, flexWrap: 'wrap' }}>
          <button style={{
            appearance: 'none', border: '1px solid var(--accent)',
            background: 'var(--accent-soft)', color: 'var(--accent)',
            padding: '10px 16px', borderRadius: 'var(--r-btn)',
            fontSize: 13, fontFamily: 'inherit', fontWeight: 500, cursor: 'pointer',
            display: 'inline-flex', alignItems: 'center', gap: 8,
          }}>
            ✨ Colar transcrição da próxima All Hands
          </button>
          <button 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: 'pointer',
          }}>
            📜 Histórico de All Hands anteriores
          </button>
        </div>
      </BlockCard>
    </div>
  );
}

function SyncStep({ n, label, sub }) {
  return (
    <div style={{
      padding: 14,
      background: 'var(--surface)',
      border: '1px solid var(--border)',
      borderRadius: 'var(--r-card)',
      display: 'flex', flexDirection: 'column', gap: 8,
    }}>
      <div style={{
        width: 28, height: 28, borderRadius: '50%',
        background: 'linear-gradient(135deg, var(--accent), var(--beza-deep))',
        color: '#fff',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontSize: 12, fontWeight: 500,
      }}>{n}</div>
      <div>
        <div style={{ fontSize: 14, fontWeight: 500, color: 'var(--text)' }}>{label}</div>
        <div style={{ fontSize: 12, color: 'var(--text-faint)', marginTop: 2, lineHeight: 1.4 }}>{sub}</div>
      </div>
    </div>
  );
}

const useEffectP2 = React.useEffect;
