/* Comercial · Daily Prospect
 * ========================================================
 * Design system: Digidelta Portal DS (dgd-* tokens)
 * Alinhado com screen_comercial_daily_briefing.jsx
 * Scroll: className="dgd-design-system scrollbar" height 100% overflow auto
 * ======================================================== */

// ── Helpers ────────────────────────────────────────────────────────────────────

const MONO_STYLE = { fontFamily: 'var(--dgd-font-mono, monospace)' };

function fmtDate(iso) {
  if (!iso) return '';
  const d = new Date(iso);
  const days = ['domingo', 'segunda-feira', 'terça-feira', 'quarta-feira', 'quinta-feira', 'sexta-feira', 'sábado'];
  const months = ['Jan', 'Fev', 'Mar', 'Abr', 'Mai', 'Jun', 'Jul', 'Ago', 'Set', 'Out', 'Nov', 'Dez'];
  return `${days[d.getDay()]}, ${d.getDate()} ${months[d.getMonth()]} ${d.getFullYear()}`;
}

function initials(nome) {
  if (!nome) return '?';
  const parts = nome.trim().split(/\s+/);
  return (parts[0]?.[0] || '') + (parts[parts.length - 1]?.[0] || '');
}

// ── Design tokens (via CSS vars) ─────────────────────────────────────────────

const T = {
  card:    { background: 'var(--dgd-bg-surface)', border: '1px solid var(--dgd-border,#e2e6ea)', borderRadius: 'var(--dgd-radius-xl,14px)', boxShadow: 'var(--dgd-shadow-card)', overflow: 'hidden' },
  green:   'var(--dgd-green-700,#15803d)',
  greenBg: 'var(--dgd-green-50,#f0fdf4)',
  red:     'var(--dgd-red-700,#b91c1c)',
  redBg:   'var(--dgd-red-50,#fef2f2)',
  amber:   'var(--dgd-yellow-700,#a16207)',
  amberBg: 'var(--dgd-yellow-50,#fefce8)',
  accent:  'var(--dgd-primary-600,#2563eb)',
  accentBg:'var(--dgd-primary-50,#eff6ff)',
  teal:    'var(--dgd-teal-700,#0f766e)',
  tealBg:  'var(--dgd-teal-50,#f0fdfa)',
  fg1:     'var(--dgd-fg-1)',
  fg2:     'var(--dgd-fg-2)',
  fg3:     'var(--dgd-fg-3)',
  border:  'var(--dgd-border,#e2e6ea)',
};

// ── Sub-components ──────────────────────────────────────────────────────────────

function ProspectLabel({ children, style }) {
  return React.createElement('div', {
    style: { ...MONO_STYLE, fontSize: 9, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.1em', color: T.fg3, ...style }
  }, children);
}

function BlocoHeader({ num, titulo, color }) {
  const bg = color === 'alert' ? T.redBg : color === 'camp' ? T.tealBg : T.accentBg;
  const fg = color === 'alert' ? T.red : color === 'camp' ? T.teal : T.accent;
  return React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 10, padding: '14px 18px 0' } },
    React.createElement('div', {
      style: { width: 24, height: 24, borderRadius: 7, background: bg, color: fg, display: 'grid', placeItems: 'center', ...MONO_STYLE, fontSize: 12, fontWeight: 700, flexShrink: 0 }
    }, num),
    React.createElement('div', { style: { ...MONO_STYLE, fontSize: 10.5, letterSpacing: '0.12em', textTransform: 'uppercase', color: T.fg3, fontWeight: 600 } }, titulo)
  );
}

function UrgIcon({ type }) {
  if (type === 'fire') return React.createElement('span', { style: { color: T.red, fontSize: 13 } }, '\u2691');
  if (type === 'warn') return React.createElement('span', { style: { color: T.amber, fontSize: 12 } }, '\u26A0');
  if (type === 'star') return React.createElement('span', { style: { color: T.amber, fontSize: 12 } }, '\u2605');
  return React.createElement('span', { style: { color: T.green, fontWeight: 600, fontSize: 11 } }, '\u2713');
}

function UrgBadge({ type }) {
  const [bg, fg, label] = {
    fire: [T.redBg,   T.red,   '!'],
    warn: [T.amberBg, T.amber, '\u26A0'],
    star: [T.amberBg, T.amber, '\u2605'],
  }[type] || [T.greenBg, T.green, '\u2713'];
  return React.createElement('span', {
    style: { flexShrink: 0, width: 20, height: 20, borderRadius: 6, background: bg, color: fg, display: 'inline-grid', placeItems: 'center', fontSize: 10, fontWeight: 700, marginTop: 2, ...MONO_STYLE }
  }, label);
}

function HerdadaChip() {
  return React.createElement('span', {
    style: { fontSize: 9, letterSpacing: '0.1em', textTransform: 'uppercase', background: T.amberBg, color: T.amber, border: `1px solid ${T.amberBg}`, borderRadius: 4, padding: '1px 5px', fontWeight: 700, marginLeft: 6, ...MONO_STYLE }
  }, 'herdada');
}

function StatusPill({ status }) {
  const [bg, fg, label] = {
    em_campanha: [T.tealBg,    T.teal,  'Em campanha'],
    submetido:   [T.accentBg,  T.accent,'Submetida'],
    expirada:    [T.redBg,     T.red,   'Expirada'],
    rejeitado:   [T.redBg,     T.red,   'Rejeitado'],
  }[status] || ['var(--dgd-grey-100,#f3f4f6)', T.fg3, 'Sem campanha'];
  return React.createElement('span', {
    style: { display: 'inline-block', fontSize: 10, letterSpacing: '0.06em', textTransform: 'uppercase', fontWeight: 700, padding: '2px 8px', borderRadius: 999, background: bg, color: fg, ...MONO_STYLE }
  }, label);
}

function OfferCell({ oferta_resumo, oferta_prazo }) {
  if (!oferta_resumo) return React.createElement('div', {
    style: { marginTop: 6, background: 'var(--dgd-grey-100,#f3f4f6)', borderLeft: `3px solid ${T.border}`, borderRadius: 5, padding: '6px 10px', fontSize: 11, color: T.fg3 }
  }, 'Sem oferta definida');
  return React.createElement('div', {
    style: { marginTop: 6, background: T.tealBg, borderLeft: `3px solid ${T.teal}`, borderRadius: 5, padding: '6px 10px', fontSize: 12, color: T.fg1 }
  },
    React.createElement('div', { style: { ...MONO_STYLE, fontSize: 9, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase', color: T.teal, marginBottom: 2 } }, 'Oferta comercial'),
    React.createElement('strong', null, oferta_resumo),
    oferta_prazo && React.createElement('div', { style: { ...MONO_STYLE, fontSize: 10, color: T.red, fontWeight: 700, marginTop: 3 } }, `V\u00e1lida at\u00e9 ${oferta_prazo}`)
  );
}

function RuleBox({ children, color }) {
  const bg = color === 'teal' ? T.tealBg : T.redBg;
  return React.createElement('div', {
    style: { background: bg, border: `1px solid ${T.border}`, borderRadius: 10, padding: '10px 14px', margin: '4px 0 12px', fontSize: 12.5, lineHeight: 1.55, color: T.fg1 }
  }, children);
}

// ── KPI Cards ────────────────────────────────────────────────────────────────

function KPICards({ kpis }) {
  if (!kpis) return null;
  const { urgente_label, urgente_contexto, prospeccao_total_contas, prospeccao_total_valor_k, prospeccao_breakdown, campanha_urgente_nome, campanha_urgente_dias, campanha_urgente_contexto, agenda_n_chamadas, agenda_contas } = kpis;
  const cards = [
    { lb: 'Urgente hoje \u2691', v: urgente_label || '\u2014', d: urgente_contexto, vc: T.red },
    { lb: 'Prospec\u00e7\u00e3o total', v: prospeccao_total_contas ? `${prospeccao_total_contas} contas \u00b7 ${prospeccao_total_valor_k}k\u20ac` : '\u2014', d: prospeccao_breakdown },
    campanha_urgente_nome && { lb: `Prazo ${campanha_urgente_nome}`, v: campanha_urgente_dias != null ? `${campanha_urgente_dias} dias` : '\u2014', d: campanha_urgente_contexto, vc: T.amber },
    { lb: 'Agenda hoje', v: agenda_n_chamadas ? `${agenda_n_chamadas} \u00d7 20 min` : '\u2014', d: (agenda_contas || []).join(' \u00b7 ') },
  ].filter(Boolean);

  return React.createElement('div', { style: { display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(190px, 1fr))', gap: 12 } },
    cards.map((c, i) =>
      React.createElement('div', { key: i, style: { ...T.card, padding: '13px 15px', display: 'flex', flexDirection: 'column', gap: 3, overflow: 'visible' } },
        React.createElement(ProspectLabel, null, c.lb),
        React.createElement('div', { style: { fontSize: 18, fontWeight: 700, color: c.vc || T.fg1, letterSpacing: '-0.01em', marginTop: 4 } }, c.v),
        React.createElement('div', { style: { fontSize: 11, color: T.fg3, marginTop: 1, lineHeight: 1.4 } }, c.d || '')
      )
    )
  );
}

// ── Bloco 1: Leitura do dia ────────────────────────────────────────────────────

function Bloco1({ bloco }) {
  if (!bloco) return null;
  const { narrativa, acoes } = bloco;
  return React.createElement('div', { style: T.card },
    React.createElement(BlocoHeader, { num: 1, titulo: 'Digi AI recomenda \u2014 leitura do dia' }),
    React.createElement('div', { style: { padding: '12px 18px 6px', fontSize: 13, lineHeight: 1.65, color: T.fg2 } },
      narrativa && React.createElement('p', {
        style: { margin: '0 0 12px' },
        dangerouslySetInnerHTML: { __html: narrativa.replace(/\*\*(.*?)\*\*/g, `<strong style="color:${T.fg1}">$1</strong>`) }
      }),
      acoes?.length > 0 && React.createElement('div', { style: { display: 'grid', gap: 8, margin: '4px 0 10px' } },
        acoes.map((a, i) =>
          React.createElement('div', { key: i, style: { display: 'flex', gap: 10, alignItems: 'flex-start' } },
            React.createElement(UrgBadge, { type: a.urgencia }),
            React.createElement('span', { style: { fontSize: 13, lineHeight: 1.55, color: T.fg2 } },
              React.createElement('strong', { style: { color: T.fg1 } }, a.titulo),
              a.titulo && a.detalhe ? ' ' : null,
              a.detalhe
            )
          )
        )
      )
    )
  );
}

// ── Bloco 2: LOSTs ────────────────────────────────────────────────────────────

function Bloco2({ bloco }) {
  if (!bloco?.length) return null;
  const totalNom = bloco.reduce((s, r) => s + (r.valor_nominal || 0), 0);
  const totalCred = bloco.reduce((s, r) => s + (r.valor_credivel || 0), 0);

  const thStyle = { padding: '8px 10px', textAlign: 'left', ...MONO_STYLE, fontSize: 11, fontWeight: 600, color: T.fg3, borderBottom: `1px solid ${T.border}`, whiteSpace: 'nowrap' };
  const tdBase = { padding: '8px 10px', borderBottom: `1px solid color-mix(in oklch, ${T.border} 60%, transparent)`, verticalAlign: 'top', fontSize: 12 };

  return React.createElement('div', { style: T.card },
    React.createElement(BlocoHeader, { num: 2, titulo: 'Prospec\u00e7\u00e3o de carteira \u00b7 LOSTs \u2014 Digi AI recomenda', color: 'alert' }),
    React.createElement('div', { style: { padding: '10px 18px 4px', fontSize: 13, color: T.fg2, lineHeight: 1.5 } },
      React.createElement('span', { style: { color: T.red } }, '\u2691'), ' urgente hoje \u00b7 ',
      React.createElement('span', { style: { color: T.amber } }, '\u26A0'), ' verificar antes \u00b7 ',
      React.createElement('span', { style: { color: T.amber } }, '\u2605'), ' priorit\u00e1rio esta semana'
    ),
    React.createElement('div', { style: { overflowX: 'auto', padding: '0 10px 14px' } },
      React.createElement('table', { style: { borderCollapse: 'collapse', width: '100%', ...MONO_STYLE, fontSize: 12 } },
        React.createElement('thead', null,
          React.createElement('tr', null,
            React.createElement('th', { style: { ...thStyle, width: 24 } }, ''),
            React.createElement('th', { style: thStyle }, 'Cliente / Produto / Valor'),
            React.createElement('th', { style: { ...thStyle, minWidth: 200, whiteSpace: 'normal' } }, 'Motivo do LOST'),
            React.createElement('th', { style: { ...thStyle, minWidth: 200 } }, 'Campanha + Oferta'),
            React.createElement('th', { style: { ...thStyle, minWidth: 180, whiteSpace: 'normal' } }, 'USP'),
            React.createElement('th', { style: { ...thStyle, minWidth: 180, whiteSpace: 'normal' } }, 'Ac\u00e7\u00e3o \u00b7 Prazo')
          )
        ),
        React.createElement('tbody', null,
          bloco.map((r, i) => {
            const isLast = i === bloco.length - 1;
            const rowBg = r.urgencia === 'fire' ? `color-mix(in oklch, ${T.red} 4%, transparent)` : 'transparent';
            const td = { ...tdBase, borderBottom: isLast ? 'none' : tdBase.borderBottom, background: rowBg };
            return React.createElement('tr', { key: i },
              React.createElement('td', { style: { ...td, textAlign: 'center', width: 24 } }, React.createElement(UrgIcon, { type: r.urgencia })),
              React.createElement('td', { style: td },
                React.createElement('strong', { style: { color: T.fg1 } }, r.cliente),
                r.herdada && React.createElement(HerdadaChip),
                React.createElement('br'),
                React.createElement('span', { style: { color: T.fg3 } }, r.produto_perdido),
                React.createElement('br'),
                React.createElement('span', { style: { color: T.fg3, fontSize: 11 } },
                  r.valor_nominal ? `${(r.valor_nominal / 1000).toFixed(1)}k\u20ac` : '\u2014',
                  r.valor_credivel ? ` \u00b7 ${(r.valor_credivel / 1000).toFixed(1)}k\u20ac cred\u00edvel (${r.credibilidade_pct || '?'}%)` : ''
                )
              ),
              React.createElement('td', { style: { ...td, whiteSpace: 'normal', fontFamily: 'inherit', minWidth: 200, lineHeight: 1.5 } },
                r.motivo_lost ? React.createElement('em', { style: { color: T.fg2 } }, `"${r.motivo_lost}"`) : '\u2014'
              ),
              React.createElement('td', { style: { ...td, minWidth: 200, verticalAlign: 'top' } },
                React.createElement(StatusPill, { status: r.campanha_status }),
                React.createElement(OfferCell, { oferta_resumo: r.oferta_resumo, oferta_prazo: r.oferta_prazo })
              ),
              React.createElement('td', { style: { ...td, whiteSpace: 'normal', minWidth: 180, lineHeight: 1.5, fontFamily: 'inherit' } }, r.usp || '\u2014'),
              React.createElement('td', { style: { ...td, whiteSpace: 'normal', minWidth: 180, lineHeight: 1.5, fontFamily: 'inherit' } }, r.acao || '\u2014')
            );
          })
        ),
        React.createElement('tfoot', null,
          React.createElement('tr', null,
            React.createElement('td', null),
            React.createElement('td', { style: { padding: '8px 10px', fontWeight: 600, ...MONO_STYLE, fontSize: 12, color: T.fg1, borderTop: `1px solid ${T.border}` } },
              `Total \u00b7 ${bloco.length} contas`
            ),
            React.createElement('td', { style: { padding: '8px 10px', fontWeight: 600, ...MONO_STYLE, fontSize: 12, color: T.fg1, borderTop: `1px solid ${T.border}` } },
              `${(totalNom / 1000).toFixed(1)}k\u20ac nom \u00b7 ${(totalCred / 1000).toFixed(1)}k\u20ac cred\u00edvel`
            ),
            React.createElement('td', { colSpan: 3, style: { padding: '8px 10px', fontSize: 11, color: T.fg3, borderTop: `1px solid ${T.border}` } })
          )
        )
      )
    ),
    React.createElement('div', { style: { padding: '0 18px 16px' } },
      React.createElement(RuleBox, null,
        React.createElement('strong', { style: { color: T.red } }, 'Regra do recontacto eficaz: '),
        'nunca come\u00e7as com "estou a ligar para ver se ainda tens interesse". Come\u00e7as com o que aprendeste da \u00faltima conversa \u2014 mostra que tomaste nota, e usa isso como raz\u00e3o do contacto.'
      )
    )
  );
}

// ── Bloco 3: Wins dormentes ────────────────────────────────────────────────────

function Bloco3({ bloco }) {
  if (!bloco?.length) return null;
  const thStyle = { padding: '8px 10px', textAlign: 'left', ...MONO_STYLE, fontSize: 11, fontWeight: 600, color: T.fg3, borderBottom: `1px solid ${T.border}`, whiteSpace: 'nowrap' };
  const tdBase = { padding: '8px 10px', fontSize: 12, verticalAlign: 'top' };

  return React.createElement('div', { style: T.card },
    React.createElement(BlocoHeader, { num: 3, titulo: 'Prospec\u00e7\u00e3o de carteira \u00b7 Wins dormentes \u226512m \u2014 Digi AI cross-sell' }),
    React.createElement('div', { style: { padding: '10px 18px 4px', fontSize: 13, color: T.fg2, lineHeight: 1.5 } },
      'Clientes que compraram h\u00e1 12+ meses sem OP nova. A Digi AI cruzou o ',
      React.createElement('strong', { style: { color: T.fg1 } }, 'equipamento instalado'),
      ' com as campanhas e sugeriu a ',
      React.createElement('strong', { style: { color: T.fg1 } }, 'expans\u00e3o natural'),
      '.'
    ),
    React.createElement('div', { style: { overflowX: 'auto', padding: '0 10px 14px' } },
      React.createElement('table', { style: { borderCollapse: 'collapse', width: '100%', ...MONO_STYLE, fontSize: 12 } },
        React.createElement('thead', null,
          React.createElement('tr', null,
            React.createElement('th', { style: thStyle }, 'Cliente / Equipamento'),
            React.createElement('th', { style: { ...thStyle, minWidth: 180, whiteSpace: 'normal' } }, 'Sinal do intel'),
            React.createElement('th', { style: { ...thStyle, minWidth: 180 } }, 'Campanha + Oferta'),
            React.createElement('th', { style: { ...thStyle, minWidth: 160, whiteSpace: 'normal' } }, 'USP relevante'),
            React.createElement('th', { style: { ...thStyle, minWidth: 160, whiteSpace: 'normal' } }, 'Ac\u00e7\u00e3o \u00b7 Prazo')
          )
        ),
        React.createElement('tbody', null,
          bloco.map((r, i) => {
            const isLast = i === bloco.length - 1;
            const td = { ...tdBase, borderBottom: isLast ? 'none' : `1px solid color-mix(in oklch, ${T.border} 60%, transparent)` };
            return React.createElement('tr', { key: i },
              React.createElement('td', { style: td },
                React.createElement('strong', { style: { color: T.fg1 } }, r.cliente),
                r.herdada && React.createElement(HerdadaChip),
                React.createElement('br'),
                React.createElement('span', { style: { color: T.fg3 } },
                  r.produto_instalado,
                  r.valor_compra ? ` \u00b7 ${(r.valor_compra / 1000).toFixed(1)}k\u20ac` : '',
                  r.meses_desde_compra ? ` \u00b7 ${r.meses_desde_compra}m` : ''
                )
              ),
              React.createElement('td', { style: { ...td, whiteSpace: 'normal', fontFamily: 'inherit', minWidth: 180, lineHeight: 1.5 } }, r.sinal_intel || '\u2014'),
              React.createElement('td', { style: { ...td, minWidth: 180 } },
                r.campanha_nome
                  ? React.createElement(StatusPill, { status: 'em_campanha' })
                  : React.createElement(StatusPill, { status: 'sem_campanha' }),
                React.createElement(OfferCell, { oferta_resumo: r.oferta_resumo })
              ),
              React.createElement('td', { style: { ...td, whiteSpace: 'normal', fontFamily: 'inherit', minWidth: 160, lineHeight: 1.5 } }, r.usp || '\u2014'),
              React.createElement('td', { style: { ...td, whiteSpace: 'normal', fontFamily: 'inherit', minWidth: 160, lineHeight: 1.5 } }, r.acao || '\u2014')
            );
          })
        )
      )
    )
  );
}

// ── Bloco 4: Campanhas referencia rapida ──────────────────────────────────────

function Bloco4({ bloco }) {
  if (!bloco?.length) return null;
  const thStyle = { padding: '8px 10px', textAlign: 'left', ...MONO_STYLE, fontSize: 11, fontWeight: 600, color: T.fg3, borderBottom: `1px solid ${T.border}`, whiteSpace: 'nowrap' };
  const tdBase = { padding: '8px 10px', fontSize: 12, verticalAlign: 'top' };

  return React.createElement('div', { style: T.card },
    React.createElement(BlocoHeader, { num: 4, titulo: 'Campanhas Mimaki \u00b7 refer\u00eancia r\u00e1pida', color: 'camp' }),
    React.createElement('div', { style: { padding: '10px 18px 4px', fontSize: 13, color: T.fg2, lineHeight: 1.5 } },
      'Briefings com ', React.createElement('strong', { style: { color: T.fg1 } }, 'USPs validados'),
      '. Detalhe de USPs por LOST/Win nas tabelas dos blocos 2, 3 e 5.'
    ),
    React.createElement('div', { style: { overflowX: 'auto', padding: '0 10px 14px' } },
      React.createElement('table', { style: { borderCollapse: 'collapse', width: '100%', ...MONO_STYLE, fontSize: 12 } },
        React.createElement('thead', null,
          React.createElement('tr', null,
            React.createElement('th', { style: thStyle }, 'Campanha \u00b7 Segmento'),
            React.createElement('th', { style: thStyle }, 'Status'),
            React.createElement('th', { style: { ...thStyle, minWidth: 200, whiteSpace: 'normal' } }, 'USP principal'),
            React.createElement('th', { style: { ...thStyle, minWidth: 180, whiteSpace: 'normal' } }, 'Oferta comercial'),
            React.createElement('th', { style: thStyle }, 'Prazo'),
            React.createElement('th', { style: { ...thStyle, minWidth: 160, whiteSpace: 'normal' } }, 'Match vendedor')
          )
        ),
        React.createElement('tbody', null,
          bloco.map((r, i) => {
            const isLast = i === bloco.length - 1;
            const isUrgent = r.dias_restantes != null && r.dias_restantes <= 30;
            const rowBg = isUrgent ? `color-mix(in oklch, ${T.red} 4%, transparent)` : 'transparent';
            const td = { ...tdBase, borderBottom: isLast ? 'none' : `1px solid color-mix(in oklch, ${T.border} 60%, transparent)`, background: rowBg };
            return React.createElement('tr', { key: i },
              React.createElement('td', { style: td },
                React.createElement('strong', { style: { color: T.fg1 } }, r.campanha_nome),
                React.createElement('br'),
                React.createElement('span', { style: { color: T.fg3, fontSize: 11 } }, r.segmento)
              ),
              React.createElement('td', { style: td }, React.createElement(StatusPill, { status: r.status })),
              React.createElement('td', { style: { ...td, whiteSpace: 'normal', fontFamily: 'inherit', minWidth: 200, lineHeight: 1.5 } }, r.usp_principal || '\u2014'),
              React.createElement('td', { style: { ...td, whiteSpace: 'normal', fontFamily: 'inherit', minWidth: 180, lineHeight: 1.5 } }, r.oferta_resumo || '\u2014'),
              React.createElement('td', { style: td },
                r.dias_restantes != null && r.dias_restantes <= 30
                  ? React.createElement('span', { style: { display: 'inline-block', fontSize: 10, fontWeight: 700, padding: '2px 8px', borderRadius: 999, background: T.redBg, color: T.red } }, `${r.dias_restantes} dias`)
                  : React.createElement('span', { style: { color: T.fg3, fontSize: 11 } }, r.prazo || '\u2014')
              ),
              React.createElement('td', { style: { ...td, whiteSpace: 'normal', fontFamily: 'inherit', minWidth: 160, lineHeight: 1.5, color: T.fg3, fontSize: 11 } }, r.match_contas || '\u2014')
            );
          })
        )
      )
    ),
    React.createElement('div', { style: { padding: '0 18px 16px' } },
      React.createElement(RuleBox, { color: 'teal' },
        React.createElement('strong', { style: { color: T.teal } }, 'Regra: '),
        'chamada primeiro (contexto), pitch depois (USP), oferta s\u00f3 quando o cliente demonstra interesse. Oferta = gatilho de urg\u00eancia, n\u00e3o abertura de conversa.'
      )
    )
  );
}

// ── Bloco 5: Prospeccao nova (alvos sugeridos) ────────────────────────────────

function Bloco5({ bloco }) {
  if (!bloco?.length) return null;
  const thStyle = { padding: '8px 10px', textAlign: 'left', ...MONO_STYLE, fontSize: 11, fontWeight: 600, color: T.fg3, borderBottom: `1px solid ${T.border}`, whiteSpace: 'nowrap' };
  const tdBase = { padding: '8px 10px', fontSize: 12, verticalAlign: 'top' };

  return React.createElement('div', { style: T.card },
    React.createElement(BlocoHeader, { num: 5, titulo: 'Prospec\u00e7\u00e3o nova \u00b7 Alvos sugeridos pela Digi AI' }),
    React.createElement('div', { style: { padding: '10px 18px 4px', fontSize: 13, color: T.fg2, lineHeight: 1.5 } },
      'Perfis de empresas-alvo fora do CRM, cruzando o ',
      React.createElement('strong', { style: { color: T.fg1 } }, 'territ\u00f3rio e campanhas'),
      ' deste comercial. ',
      React.createElement('span', { style: { color: T.fg3, fontSize: 12 } }, '(Alvos sugeridos pela AI \u2014 validar antes de contactar)')
    ),
    React.createElement('div', { style: { overflowX: 'auto', padding: '0 10px 14px' } },
      React.createElement('table', { style: { borderCollapse: 'collapse', width: '100%', ...MONO_STYLE, fontSize: 12 } },
        React.createElement('thead', null,
          React.createElement('tr', null,
            React.createElement('th', { style: thStyle }, 'Empresa \u00b7 Localiza\u00e7\u00e3o'),
            React.createElement('th', { style: { ...thStyle, minWidth: 200, whiteSpace: 'normal' } }, 'Sector \u00b7 Sinal'),
            React.createElement('th', { style: { ...thStyle, minWidth: 180 } }, 'Campanha + Oferta'),
            React.createElement('th', { style: { ...thStyle, minWidth: 180, whiteSpace: 'normal' } }, 'USP que se posiciona'),
            React.createElement('th', { style: { ...thStyle, minWidth: 160, whiteSpace: 'normal' } }, 'Ac\u00e7\u00e3o de primeira aproxima\u00e7\u00e3o')
          )
        ),
        React.createElement('tbody', null,
          bloco.map((r, i) => {
            const isLast = i === bloco.length - 1;
            const td = { ...tdBase, borderBottom: isLast ? 'none' : `1px solid color-mix(in oklch, ${T.border} 60%, transparent)` };
            return React.createElement('tr', { key: i },
              React.createElement('td', { style: td },
                React.createElement('strong', { style: { color: T.fg1 } }, r.empresa),
                React.createElement('br'),
                React.createElement('span', { style: { color: T.fg3, fontSize: 11 } }, r.localizacao)
              ),
              React.createElement('td', { style: { ...td, whiteSpace: 'normal', fontFamily: 'inherit', minWidth: 200, lineHeight: 1.5 } }, r.sector_sinal || '\u2014'),
              React.createElement('td', { style: { ...td, minWidth: 180 } },
                r.campanha_nome && React.createElement(StatusPill, { status: 'em_campanha' }),
                React.createElement(OfferCell, { oferta_resumo: r.oferta_resumo })
              ),
              React.createElement('td', { style: { ...td, whiteSpace: 'normal', fontFamily: 'inherit', minWidth: 180, lineHeight: 1.5 } }, r.usp || '\u2014'),
              React.createElement('td', { style: { ...td, whiteSpace: 'normal', fontFamily: 'inherit', minWidth: 160, lineHeight: 1.5 } }, r.acao || '\u2014')
            );
          })
        ),
        React.createElement('tfoot', null,
          React.createElement('tr', null,
            React.createElement('td', { style: { padding: '8px 10px', fontWeight: 600, ...MONO_STYLE, fontSize: 12, color: T.fg1, borderTop: `1px solid ${T.border}` } },
              `Total \u00b7 ${bloco.length} alvos`
            ),
            React.createElement('td', { colSpan: 4, style: { padding: '8px 10px', fontSize: 11, color: T.fg3, borderTop: `1px solid ${T.border}`, textAlign: 'left' } },
              'Registar como novas entidades no Gestor quando responderem.'
            )
          )
        )
      )
    )
  );
}

// ── Bloco 6: Agenda ────────────────────────────────────────────────────────────

function Bloco6({ bloco }) {
  if (!bloco) return null;
  const { principais, suplentes, regra_do_dia } = bloco;
  const urgBg = { fire: T.redBg, warn: T.amberBg };
  const urgFg = { fire: T.red, warn: T.amber };

  return React.createElement('div', { style: T.card },
    React.createElement(BlocoHeader, { num: 6, titulo: 'Agenda do dia \u00b7 Top 3 contactos' }),
    React.createElement('div', { style: { padding: '12px 18px 6px' } },
      principais?.map((a, i) =>
        React.createElement('div', {
          key: i,
          style: { display: 'flex', gap: 12, alignItems: 'flex-start', border: `1px solid ${T.border}`, borderRadius: 10, padding: '12px 14px', marginBottom: 10 }
        },
          React.createElement('div', {
            style: { flexShrink: 0, width: 28, height: 28, borderRadius: 8, background: urgBg[a.urgencia] || T.accentBg, color: urgFg[a.urgencia] || T.accent, display: 'grid', placeItems: 'center', fontWeight: 700, fontSize: 13, ...MONO_STYLE }
          }, a.n || (i + 1)),
          React.createElement('div', null,
            React.createElement('strong', { style: { fontSize: 13, color: T.fg1 } }, a.titulo),
            a.detalhe && React.createElement('p', { style: { margin: '4px 0 0', fontSize: 12, lineHeight: 1.5, color: T.fg2 } }, a.detalhe)
          )
        )
      ),
      suplentes?.length > 0 && React.createElement(React.Fragment, null,
        React.createElement(ProspectLabel, { style: { margin: '8px 0 8px' } }, 'Suplentes'),
        suplentes.map((a, i) =>
          React.createElement('div', {
            key: i,
            style: { display: 'flex', gap: 12, alignItems: 'flex-start', border: `1px solid ${T.border}`, borderRadius: 10, padding: '10px 14px', marginBottom: 8, opacity: 0.75 }
          },
            React.createElement('div', {
              style: { flexShrink: 0, width: 28, height: 28, borderRadius: 8, background: T.accentBg, color: T.accent, display: 'grid', placeItems: 'center', fontWeight: 700, fontSize: 13, ...MONO_STYLE }
            }, a.n || (i + 4)),
            React.createElement('div', null,
              React.createElement('strong', { style: { fontSize: 12, color: T.fg1 } }, a.titulo),
              a.detalhe && React.createElement('p', { style: { margin: '3px 0 0', fontSize: 11.5, color: T.fg2 } }, a.detalhe)
            )
          )
        )
      ),
      regra_do_dia && React.createElement('div', { style: { margin: '4px 0 10px' } },
        React.createElement(RuleBox, null,
          React.createElement('strong', { style: { color: T.red } }, 'Regra do dia: '),
          regra_do_dia
        )
      )
    )
  );
}

// ── ProspectHero — header estilo DashHero ─────────────────────────────────────

function ProspectHero({ nome, metricas, pj, gerado_em, onRegenerate, regenerating, loading }) {
  const firstName = (nome || 'Comercial').split(' ')[0];
  const d = new Date();
  const diasSem = ['Domingo','Segunda','Ter\u00e7a','Quarta','Quinta','Sexta','S\u00e1bado'];
  const mesesNome = ['Janeiro','Fevereiro','Mar\u00e7o','Abril','Maio','Junho','Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'];
  const nowStr = `${diasSem[d.getDay()]}, ${d.getDate()} de ${mesesNome[d.getMonth()]}`;

  const headline = React.useMemo(() => {
    if (!metricas) return `${firstName}, o teu Daily Prospect est\u00e1 a ser preparado\u2026`;
    const { total_losts, campanhas_activas, campanha_urgente_dias, campanha_mais_urgente } = metricas;
    if (campanhas_activas > 0 && total_losts > 0) {
      if (campanha_urgente_dias != null && campanha_urgente_dias <= 7) {
        return `${firstName}, a campanha \u201c${campanha_mais_urgente}\u201d fecha em ${campanha_urgente_dias} dias \u2014 hora de ligar.`;
      }
      return `${firstName}, tens ${campanhas_activas} campanha${campanhas_activas > 1 ? 's' : ''} activa${campanhas_activas > 1 ? 's' : ''} para acordar ${total_losts} LOST${total_losts > 1 ? 's' : ''}.`;
    }
    if (total_losts > 0) return `${firstName}, tens ${total_losts} LOST${total_losts > 1 ? 's' : ''} para analisar e recuperar.`;
    return `${firstName}, o teu Daily Prospect est\u00e1 pronto.`;
  }, [firstName, metricas]);

  // Frase motivacional: regra_do_dia da AI, com fallback contextual
  const motivacao = React.useMemo(() => {
    if (pj?.bloco6?.regra_do_dia) return pj.bloco6.regra_do_dia;
    if (!metricas) return null;
    const { campanha_urgente_dias, campanha_mais_urgente, total_losts, campanhas_activas } = metricas;
    if (campanha_urgente_dias != null && campanha_urgente_dias <= 7)
      return `A campanha \u201c${campanha_mais_urgente}\u201d fecha em ${campanha_urgente_dias} dias. Quem liga primeiro, fecha primeiro.`;
    if (total_losts > 10)
      return `${total_losts} LOSTs com valor real \u2014 a concorr\u00eancia tamb\u00e9m os est\u00e1 a ligar.`;
    if (campanhas_activas > 0)
      return 'As campanhas est\u00e3o no ar. O pipeline n\u00e3o cresce sozinho \u2014 vamos a isso.';
    return 'O follow-up que n\u00e3o fazes hoje, algu\u00e9m da concorr\u00eancia faz.';
  }, [pj, metricas]);

  const urgBadge = metricas?.campanha_urgente_dias != null && metricas.campanha_urgente_dias <= 14
    ? 'URGENTE'
    : metricas?.campanhas_activas > 0 ? 'ACTIVO' : null;
  const urgColor = urgBadge === 'URGENTE' ? T.red   : T.teal;
  const urgBg    = urgBadge === 'URGENTE' ? T.redBg : T.tealBg;
  const geradoHora = gerado_em ? new Date(gerado_em).toLocaleTimeString('pt-PT', { hour: '2-digit', minute: '2-digit' }) : null;

  return React.createElement(React.Fragment, null,
    // ── Card principal
    React.createElement('div', {
      style: {
        background: 'var(--dgd-bg-surface)',
        borderRadius: 'var(--dgd-radius-xl,14px)',
        boxShadow: 'var(--dgd-shadow-card)',
        padding: 24,
      }
    },
      React.createElement('div', {
        style: { font: 'var(--dgd-caption)', color: 'var(--dgd-fg-3)', textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: 8 }
      }, `Comercial \u00b7 ${nowStr}`),
      React.createElement('h1', {
        style: { margin: 0, font: 'var(--dgd-h1)', letterSpacing: '-0.015em', color: 'var(--dgd-fg-1)' }
      }, headline),
      metricas && React.createElement('p', {
        style: { margin: '10px 0 0', font: 'var(--dgd-body-lg)', color: 'var(--dgd-fg-2)', lineHeight: 1.55, maxWidth: 760 }
      },
        metricas.total_losts > 0 && React.createElement(React.Fragment, null,
          'Tens ',
          React.createElement('strong', { style: { color: T.fg1 } }, `${metricas.total_losts} LOST${metricas.total_losts > 1 ? 's' : ''}`),
          ` com ${metricas.total_losts_valor_k}k\u20ac`
        ),
        metricas.campanhas_activas > 0 && React.createElement(React.Fragment, null,
          metricas.total_losts > 0 ? ' e ' : '',
          React.createElement('strong', { style: { color: T.fg1 } }, `${metricas.campanhas_activas} campanha${metricas.campanhas_activas > 1 ? 's' : ''} activa${metricas.campanhas_activas > 1 ? 's' : ''}`)
        ),
        metricas.campanha_mais_urgente && React.createElement(React.Fragment, null,
          '. Mais urgente: ',
          React.createElement('strong', { style: { color: T.fg1 } }, metricas.campanha_mais_urgente),
          metricas.campanha_urgente_dias != null && ` \u2014 ${metricas.campanha_urgente_dias} dias.`
        )
      ),
      motivacao && React.createElement('p', {
        style: { margin: '10px 0 0', font: 'var(--dgd-body-lg)', color: 'var(--dgd-fg-3)', lineHeight: 1.55, fontStyle: 'italic' }
      }, motivacao)
    ),
    // ── Barra Digi — fora do card
    React.createElement('div', {
      style: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8, padding: '0 4px' }
    },
      React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 8 } },
        React.createElement('span', { style: { fontSize: 14 } }, '\u26A1'),
        React.createElement('div', { style: { ...MONO_STYLE, fontSize: 10, color: 'var(--dgd-fg-2)', letterSpacing: '0.08em', textTransform: 'uppercase' } },
          'Digi \u00b7 Agente AI Digidelta'
        )
      ),
      React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 8 } },
        geradoHora && React.createElement('div', {
          style: { ...MONO_STYLE, fontSize: 10, color: T.fg3 }
        }, `gerado \u00e0s ${geradoHora}`),
        urgBadge && React.createElement('div', {
          style: { ...MONO_STYLE, padding: '3px 9px', borderRadius: 999, fontSize: 10.5, fontWeight: 700, background: urgBg, color: urgColor, textTransform: 'uppercase', letterSpacing: '0.04em' }
        }, urgBadge),
        React.createElement('button', {
          onClick: onRegenerate,
          disabled: regenerating || loading,
          className: 'dgd-btn dgd-btn-ghost',
          style: { padding: '4px 10px', fontSize: 10.5, opacity: (regenerating || loading) ? 0.5 : 1 }
        }, regenerating ? '\u2026' : '\u21bb Actualizar')
      )
    )
  );
}

// ── Loading / Error ────────────────────────────────────────────────────────────

function ProspectLoading() {
  return React.createElement('div', {
    style: { display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: '80px 20px', gap: 16 }
  },
    React.createElement('div', { style: { fontSize: 32 } }, '\u26A1'),
    React.createElement('p', { style: { color: T.fg2, margin: 0, fontSize: 14 } }, 'A gerar o teu Daily Prospect com Digi AI...'),
    React.createElement('p', { style: { ...MONO_STYLE, fontSize: 11, color: T.fg3, margin: 0 } }, 'Pode demorar 30\u201360 segundos na primeira vez')
  );
}

function ProspectError({ message, onRetry }) {
  return React.createElement('div', {
    style: { display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: '80px 20px', gap: 16 }
  },
    React.createElement('div', { style: { fontSize: 28, color: T.red } }, '\u26A0'),
    React.createElement('p', { style: { color: T.red, margin: 0, fontSize: 13 } }, message),
    React.createElement('button', { className: 'dgd-btn dgd-btn-primary', onClick: onRetry }, 'Tentar novamente')
  );
}

// ── Main Screen ────────────────────────────────────────────────────────────────

function ComercialProspectScreen({ user, vendedorId }) {
  const [state, setState] = React.useState({ loading: true, error: null, data: null });
  const [regenerating, setRegenerating] = React.useState(false);
  const pollRef = React.useRef(null);

  const stopPoll = () => { if (pollRef.current) { clearInterval(pollRef.current); pollRef.current = null; } };

  const load = React.useCallback((force = false) => {
    const asParam = vendedorId ? `?as=${encodeURIComponent(vendedorId)}` : '';

    if (force) {
      setRegenerating(true);
      stopPoll();
      const clientStartTs = Date.now(); // timestamp local do cliente
      // Disparar regeneração (resposta imediata do servidor)
      fetch(`/api/comercial/prospect/regenerate${asParam}`, { method: 'POST' })
        .then(r => r.json())
        .then(d => {
          if (d.error) { setRegenerating(false); return; }
          // Timeout: ao fim de 5 min faz load normal independentemente
          const maxWaitMs = 5 * 60 * 1000;
          // Polling a cada 5s até aparecer resultado mais recente
          pollRef.current = setInterval(() => {
            const elapsed = Date.now() - clientStartTs;
            fetch(`/api/comercial/prospect/today${asParam}`)
              .then(r => r.json())
              .then(result => {
                if (result.error) {
                  // Se timeout atingido, desiste e recarrega
                  if (elapsed > maxWaitMs) { stopPoll(); setState(s => ({ ...s, loading: false })); setRegenerating(false); }
                  return;
                }
                // Comparar usando timestamp em milissegundos UTC para evitar problemas de timezone
                const geradoEm = result.gerado_em ? new Date(result.gerado_em).getTime() : 0;
                const isNewer = geradoEm > clientStartTs;
                if (isNewer || elapsed > maxWaitMs) {
                  stopPoll();
                  setRegenerating(false);
                  setState({ loading: false, error: null, data: result });
                }
              })
              .catch(() => {
                if (Date.now() - clientStartTs > maxWaitMs) { stopPoll(); setRegenerating(false); }
              });
          }, 5000);
        })
        .catch(() => setRegenerating(false));
      return;
    }

    setState(s => ({ ...s, loading: true, error: null }));
    fetch(`/api/comercial/prospect/today${asParam}`)
      .then(r => r.json())
      .then(d => {
        if (d.error) throw new Error(d.error);
        setState({ loading: false, error: null, data: d });
      })
      .catch(e => setState({ loading: false, error: e.message, data: null }));
  }, [vendedorId]);

  React.useEffect(() => { load(); return stopPoll; }, [load]);

  const nome = user?.nome_apresentar || user?.nome || 'Comercial';
  const { loading, error, data } = state;
  const { prospect_json: pj, metricas, date, gerado_em } = data || {};

  const pad = 20;

  return React.createElement('div', {
    className: 'dgd-design-system scrollbar',
    style: { height: '100%', overflow: 'auto', background: 'var(--dgd-bg-app)' }
  },
    React.createElement('div', { style: { padding: `${pad}px ${pad}px 60px`, maxWidth: '100%', margin: '0 auto', display: 'flex', flexDirection: 'column', gap: 16 } },

      // ── Header
      React.createElement(ProspectHero, {
        nome, metricas, pj, gerado_em,
        onRegenerate: () => load(true),
        regenerating, loading,
      }),

      // ── Content
      loading
        ? React.createElement(ProspectLoading)
        : error
          ? React.createElement(ProspectError, { message: error, onRetry: () => load() })
          : pj && React.createElement(React.Fragment, null,
              React.createElement(KPICards, { kpis: pj.kpis }),
              React.createElement(Bloco1, { bloco: pj.bloco1 }),
              React.createElement(Bloco2, { bloco: pj.bloco2 }),
              React.createElement(Bloco3, { bloco: pj.bloco3 }),
              React.createElement(Bloco4, { bloco: pj.bloco4 }),
              React.createElement(Bloco5, { bloco: pj.bloco5 }),
              React.createElement(Bloco6, { bloco: pj.bloco6 }),
              React.createElement('div', { style: { ...MONO_STYLE, fontSize: 11, color: T.fg3, textAlign: 'center', paddingTop: 8 } },
                'Daily Prospect \u00b7 Digi AI \u00b7 Digidelta'
              )
            )
    )
  );
}

window.ComercialProspectScreen = ComercialProspectScreen;
