/* COMERCIAL · DIGI — home chat-first.
   Conversa contínua com a Digi AI, mesma thread que WhatsApp.
   Max-width 780px · bubbles iMessage/WA · briefing matinal · cards inline ricos · composer chips.
   Painel contextual direito colapsado por default. */

const DIGI_USER = { name: 'Daniel', avatar: 'DM' };
const DIGI_AGENT = { name: 'Digi' };

// ============ helpers ============
const timeNow = () => {
  const d = new Date();
  return `${String(d.getHours()).padStart(2,'0')}:${String(d.getMinutes()).padStart(2,'0')}`;
};
const clamp = (n, a, b) => Math.max(a, Math.min(b, n));

// ============ atoms ============
const DigiAvatar = ({ size = 26 }) => (
  <div style={{
    width: size, height: size, borderRadius: size/2,
    background: 'linear-gradient(135deg, var(--ai-500), var(--ai-700))',
    display: 'grid', placeItems: 'center', flexShrink: 0,
    boxShadow: '0 0 0 1px var(--border), 0 1px 2px rgba(0,0,0,0.15)',
  }}>
    <Icon name="sparkle" size={Math.round(size * 0.52)} style={{ color: '#fff' }} />
  </div>
);

const UserAvatar = ({ size = 26 }) => (
  <div style={{
    width: size, height: size, borderRadius: size/2,
    background: 'var(--brand-900)', color: '#fff',
    display: 'grid', placeItems: 'center', flexShrink: 0,
    fontFamily: 'var(--font-display)', fontWeight: 700,
    fontSize: Math.round(size * 0.42), letterSpacing: '0.02em',
    boxShadow: '0 0 0 1px var(--border)',
  }}>DM</div>
);

const DateDivider = ({ label }) => (
  <div style={{ display: 'flex', alignItems: 'center', gap: 12, margin: '20px 0 16px', color: 'var(--text-dim)' }}>
    <div style={{ flex: 1, height: 1, background: 'var(--border)' }} />
    <span className="font-mono" style={{ fontSize: 10, letterSpacing: '0.08em' }}>{label}</span>
    <div style={{ flex: 1, height: 1, background: 'var(--border)' }} />
  </div>
);

const ActionChip = ({ label, icon, onClick, primary }) => (
  <button onClick={onClick} style={{
    display: 'inline-flex', alignItems: 'center', gap: 6,
    padding: '6px 12px', borderRadius: 999,
    fontSize: 12, fontWeight: 500,
    background: primary ? 'var(--ai-500)' : 'var(--bg-elev)',
    color: primary ? '#fff' : 'var(--text)',
    border: `1px solid ${primary ? 'transparent' : 'var(--border)'}`,
    transition: 'all 0.12s',
  }}
    onMouseEnter={e => { if (!primary) e.currentTarget.style.background = 'var(--bg-hover)'; }}
    onMouseLeave={e => { if (!primary) e.currentTarget.style.background = 'var(--bg-elev)'; }}
  >
    {icon && <Icon name={icon} size={12} />}
    {label}
  </button>
);

// ============ bubble ============
const SourceBadge = ({ source, voiceMeta, emailMeta }) => {
  if (!source) return null;
  const meta = (window.SOURCE_META || {})[source];
  if (!meta) return null;
  const extra = source === 'voice' && voiceMeta ? `voz · ${voiceMeta.duration}${voiceMeta.transcript ? ' · transcrito' : ''}`
              : source === 'email' && emailMeta ? `email · ${emailMeta.subject}`
              : meta.label;
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 4,
      padding: '2px 7px', borderRadius: 999, fontSize: 10,
      fontFamily: 'var(--font-mono)', letterSpacing: '0.04em',
      background: `color-mix(in oklch, ${meta.color} 14%, transparent)`,
      color: meta.color, fontWeight: 600,
      whiteSpace: 'nowrap',
    }}>
      <span style={{ fontSize: 10 }}>{meta.icon}</span>{extra}
    </span>
  );
};

const Bubble = ({ from, children, time, showAvatar = true, dense = false, source, voiceMeta, emailMeta }) => {
  const isUser = from === 'user';
  return (
    <div style={{
      display: 'flex', gap: 10,
      flexDirection: isUser ? 'row-reverse' : 'row',
      marginBottom: dense ? 4 : 10,
      alignItems: 'flex-end',
    }}>
      <div style={{ width: 26, flexShrink: 0, visibility: showAvatar ? 'visible' : 'hidden' }}>
        {isUser ? <UserAvatar /> : <DigiAvatar />}
      </div>
      <div style={{ maxWidth: '82%', display: 'flex', flexDirection: 'column', alignItems: isUser ? 'flex-end' : 'flex-start', gap: 4 }}>
        {children}
        <div style={{ display: 'flex', gap: 6, alignItems: 'center', padding: '0 4px' }}>
          {isUser && source && <SourceBadge source={source} voiceMeta={voiceMeta} emailMeta={emailMeta} />}
          {time && <span className="font-mono" style={{ fontSize: 9.5, color: 'var(--text-dim)' }}>{time}{isUser && ' ✓✓'}</span>}
        </div>
      </div>
    </div>
  );
};

const TextBubble = ({ from, children }) => {
  const isUser = from === 'user';
  return (
    <div style={{
      padding: '9px 13px',
      borderRadius: 14,
      borderBottomLeftRadius: isUser ? 14 : 4,
      borderBottomRightRadius: isUser ? 4 : 14,
      background: isUser ? 'var(--wa-out, #056162)' : 'var(--bg-elev)',
      color: isUser ? '#fff' : 'var(--text)',
      fontSize: 13.5, lineHeight: 1.5,
      border: isUser ? 'none' : '1px solid var(--border)',
      wordBreak: 'break-word',
    }}>
      {children}
    </div>
  );
};

// ============ inline cards (renderizados dentro da conversa) ============

// Card: briefing matinal — 1 hero + 3 small
const BriefingCard = ({ onNavigate }) => (
  <div style={{
    width: 580, maxWidth: '100%',
    background: 'var(--bg-elev)',
    border: '1px solid var(--border)', borderRadius: 14,
    borderBottomLeftRadius: 4,
    overflow: 'hidden',
  }}>
    <div style={{ padding: '10px 14px 8px', display: 'flex', alignItems: 'center', gap: 8, borderBottom: '1px solid var(--border)' }}>
      <span className="font-mono" style={{ fontSize: 10, color: 'var(--text-dim)', letterSpacing: '0.08em' }}>BRIEFING · TER 23 ABR · 08:00</span>
      <span style={{ flex: 1 }} />
      <span style={{ fontSize: 10, color: 'var(--ai-500)', fontWeight: 600 }}>4 prioridades</span>
    </div>

    {/* HERO — 1 card grande */}
    <div style={{ padding: 14 }}>
      <div
        onClick={() => onNavigate('carteira', { focus: 'grafica-norte' })}
        style={{
          padding: 14,
          background: 'linear-gradient(135deg, color-mix(in oklch, var(--danger) 12%, transparent), color-mix(in oklch, var(--danger) 4%, transparent))',
          border: '1px solid color-mix(in oklch, var(--danger) 32%, var(--border))',
          borderRadius: 10,
          cursor: 'pointer', transition: 'transform 0.15s',
        }}
        onMouseEnter={e => e.currentTarget.style.transform = 'translateY(-1px)'}
        onMouseLeave={e => e.currentTarget.style.transform = 'translateY(0)'}
      >
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginBottom: 8 }}>
          <span style={{ fontSize: 11, fontWeight: 600, color: 'var(--danger)', letterSpacing: '0.04em' }}>🔴 URGENTE · RISCO CHURN</span>
        </div>
        <div className="font-display" style={{ fontSize: 18, fontWeight: 700, letterSpacing: '-0.01em', marginBottom: 4 }}>Gráfica Norte parou há 12 dias</div>
        <div style={{ fontSize: 13, color: 'var(--text-muted)', lineHeight: 1.5, marginBottom: 12 }}>
          Oportunidade de <strong style={{ color: 'var(--text)' }}>340.000 €</strong> em stage 80. Última interacção: proposta enviada dia 11. Sem resposta.
        </div>
        <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
          <ActionChip label="Ligar agora" icon="phone" primary onClick={() => {}} />
          <ActionChip label="Ver cliente" icon="sales" onClick={() => onNavigate('carteira')} />
          <ActionChip label="Rever proposta" icon="doc" onClick={() => {}} />
        </div>
      </div>
    </div>

    {/* 3 pequenos secundários */}
    <div style={{ padding: '0 14px 14px', display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 8 }}>
      {[
        { flag: '📅', flagColor: 'var(--warning)', label: 'Visita 14:00', title: 'SignPro · Leiria', body: 'Briefing pronto. Decisor: João Afonso.', action: 'Abrir briefing' },
        { flag: '⚡', flagColor: 'var(--ai-500)', label: '2 leads novas', title: 'Campanha UV Abril', body: 'Fit 84 · 76. Mimaki-match.', action: 'Ver leads' },
        { flag: '💳', flagColor: 'var(--text-muted)', label: 'Atraso pagamento', title: 'Multiprint Lda', body: '11.240 € · 45d. Limite próximo.', action: 'Ver financeiro' },
      ].map((c, i) => (
        <div key={i} style={{
          padding: 11,
          background: 'var(--bg-sunken)',
          border: '1px solid var(--border)',
          borderRadius: 8,
          cursor: 'pointer', transition: 'background 0.12s',
          display: 'flex', flexDirection: 'column', gap: 4,
        }}
          onMouseEnter={e => e.currentTarget.style.background = 'var(--bg-hover)'}
          onMouseLeave={e => e.currentTarget.style.background = 'var(--bg-sunken)'}
        >
          <div style={{ fontSize: 10, color: c.flagColor, fontWeight: 600, letterSpacing: '0.02em' }}>{c.flag} {c.label}</div>
          <div style={{ fontSize: 12.5, fontWeight: 600, lineHeight: 1.25 }}>{c.title}</div>
          <div style={{ fontSize: 11, color: 'var(--text-muted)', lineHeight: 1.35, flex: 1 }}>{c.body}</div>
          <div style={{ fontSize: 10, color: 'var(--ai-500)', fontWeight: 600, marginTop: 2, display: 'flex', alignItems: 'center', gap: 3 }}>
            {c.action} <Icon name="chevronRight" size={10} />
          </div>
        </div>
      ))}
    </div>
  </div>
);

// Card: cliente (para perguntar "qual é o status da Gráfica Norte?")
const ClienteCard = ({ onNavigate }) => (
  <div
    onClick={() => onNavigate('carteira', { focus: 'grafica-norte' })}
    style={{
      width: 420, maxWidth: '100%',
      background: 'var(--bg-elev)', border: '1px solid var(--border)', borderRadius: 14,
      borderBottomLeftRadius: 4, overflow: 'hidden', cursor: 'pointer',
      transition: 'transform 0.15s',
    }}
    onMouseEnter={e => e.currentTarget.style.transform = 'translateY(-1px)'}
    onMouseLeave={e => e.currentTarget.style.transform = 'translateY(0)'}
  >
    <div style={{ padding: '12px 14px', display: 'flex', alignItems: 'center', gap: 10, borderBottom: '1px solid var(--border)' }}>
      <div style={{ width: 36, height: 36, borderRadius: 8, background: 'var(--surface-muted)', border: '1px solid var(--border)', display: 'grid', placeItems: 'center', color: 'var(--text-muted)', fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 13 }}>GN</div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontWeight: 600, fontSize: 14 }}>Gráfica Norte Lda</div>
        <div style={{ fontSize: 11, color: 'var(--text-muted)' }}>Porto · Sinalética · 28 colab.</div>
      </div>
      <span style={{ padding: '2px 8px', fontSize: 10, fontWeight: 600, color: 'var(--danger)', background: 'color-mix(in oklch, var(--danger) 12%, transparent)', borderRadius: 999 }}>🔴 Risco</span>
    </div>
    <div style={{ padding: 14, display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 10 }}>
      <div>
        <div style={{ fontSize: 10, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', letterSpacing: '0.06em' }}>LTV</div>
        <div style={{ fontSize: 15, fontWeight: 600, fontFamily: 'var(--font-display)' }}>487.2k €</div>
      </div>
      <div>
        <div style={{ fontSize: 10, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', letterSpacing: '0.06em' }}>ÚLT. COMPRA</div>
        <div style={{ fontSize: 13, fontWeight: 600, fontFamily: 'var(--font-display)' }}>há 67 dias</div>
      </div>
      <div>
        <div style={{ fontSize: 10, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', letterSpacing: '0.06em' }}>OP ACTIVA</div>
        <div style={{ fontSize: 13, fontWeight: 600, fontFamily: 'var(--font-display)', color: 'var(--warning)' }}>1 · stage 80</div>
      </div>
    </div>
    <div style={{ padding: '10px 14px', borderTop: '1px solid var(--border)', background: 'var(--bg-sunken)', display: 'flex', alignItems: 'center', justifyContent: 'space-between', fontSize: 11, color: 'var(--text-muted)' }}>
      <span>Mimaki · Decal · PPE100</span>
      <span style={{ color: 'var(--ai-500)', fontWeight: 600, display: 'inline-flex', alignItems: 'center', gap: 3 }}>Abrir ficha <Icon name="chevronRight" size={10} /></span>
    </div>
  </div>
);

// Card: simulação financeira
const SimulacaoCard = ({ onNavigate }) => (
  <div
    onClick={() => onNavigate('simulador')}
    style={{
      width: 420, maxWidth: '100%',
      background: 'var(--bg-elev)', border: '1px solid var(--border)', borderRadius: 14,
      borderBottomLeftRadius: 4, overflow: 'hidden', cursor: 'pointer',
      transition: 'transform 0.15s',
    }}
    onMouseEnter={e => e.currentTarget.style.transform = 'translateY(-1px)'}
    onMouseLeave={e => e.currentTarget.style.transform = 'translateY(0)'}
  >
    <div style={{ padding: '12px 14px', display: 'flex', alignItems: 'center', gap: 10, borderBottom: '1px solid var(--border)' }}>
      <div style={{ width: 36, height: 36, borderRadius: 8, background: 'color-mix(in oklch, var(--ai-500) 14%, transparent)', display: 'grid', placeItems: 'center', color: 'var(--ai-500)' }}>
        <Icon name="dollar" size={16} />
      </div>
      <div style={{ flex: 1 }}>
        <div style={{ fontWeight: 600, fontSize: 14 }}>Simulação · UCJV330-160</div>
        <div style={{ fontSize: 11, color: 'var(--text-muted)' }}>800 m²/mês · PrintPlan Care</div>
      </div>
    </div>
    <div style={{ padding: 14, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
      <div style={{ padding: 10, background: 'var(--bg-sunken)', borderRadius: 8 }}>
        <div style={{ fontSize: 10, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)' }}>€/M²</div>
        <div className="font-display" style={{ fontSize: 20, fontWeight: 700 }}>1,74 €</div>
      </div>
      <div style={{ padding: 10, background: 'var(--bg-sunken)', borderRadius: 8 }}>
        <div style={{ fontSize: 10, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)' }}>€/MÊS</div>
        <div className="font-display" style={{ fontSize: 20, fontWeight: 700 }}>1.395 €</div>
      </div>
      <div style={{ gridColumn: '1 / -1', padding: 10, background: 'color-mix(in oklch, var(--success) 10%, transparent)', borderRadius: 8, display: 'flex', alignItems: 'center', gap: 10 }}>
        <Icon name="trendUp" size={14} style={{ color: 'var(--success)' }} />
        <div style={{ fontSize: 12, color: 'var(--text)' }}>
          <strong>-28% vs Roland VG3 actual</strong> · ROI 14 meses
        </div>
      </div>
    </div>
    <div style={{ padding: '10px 14px', borderTop: '1px solid var(--border)', background: 'var(--bg-sunken)', display: 'flex', gap: 6 }}>
      <span style={{ fontSize: 11, color: 'var(--ai-500)', fontWeight: 600, display: 'inline-flex', alignItems: 'center', gap: 3, flex: 1 }}>Abrir completa <Icon name="chevronRight" size={10} /></span>
      <button className="btn btn-xs" style={{ padding: '2px 8px', fontSize: 10 }} onClick={e => { e.stopPropagation(); }}>Gerar PDF</button>
      <button className="btn btn-xs" style={{ padding: '2px 8px', fontSize: 10 }} onClick={e => { e.stopPropagation(); }}>Enviar WA</button>
    </div>
  </div>
);

// Card: ficha técnica PDF
const FichaCard = () => (
  <div style={{
    width: 380, maxWidth: '100%',
    background: 'var(--bg-elev)', border: '1px solid var(--border)', borderRadius: 14,
    borderBottomLeftRadius: 4, overflow: 'hidden', cursor: 'pointer',
  }}>
    <div style={{ display: 'flex', gap: 12, padding: 12 }}>
      <div style={{ width: 54, height: 70, borderRadius: 6, background: 'linear-gradient(180deg, #fff 0%, #f3f3f3 100%)', border: '1px solid var(--border)', position: 'relative', flexShrink: 0, overflow: 'hidden' }}>
        <div style={{ position: 'absolute', inset: 6, display: 'flex', flexDirection: 'column', gap: 2 }}>
          <div style={{ height: 4, background: '#e11d48', width: '60%', borderRadius: 1 }} />
          {[1,2,3,4,5,6].map(i => (
            <div key={i} style={{ height: 1.5, background: '#d4d4d8', width: `${90 - i*5}%`, borderRadius: 1 }} />
          ))}
        </div>
        <span style={{ position: 'absolute', bottom: 3, right: 3, fontSize: 7, color: '#999', fontWeight: 700 }}>PDF</span>
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontWeight: 600, fontSize: 13.5, marginBottom: 2 }}>PPE100 · Ficha Técnica</div>
        <div style={{ fontSize: 11, color: 'var(--text-muted)', lineHeight: 1.5 }}>Polimero monomérico · 100μm<br/>4 páginas · PT + EN</div>
        <div style={{ marginTop: 8, display: 'flex', gap: 6 }}>
          <ActionChip label="Enviar ao cliente" icon="send" primary onClick={() => {}} />
          <button className="btn btn-xs" style={{ padding: '2px 8px' }}>Abrir</button>
        </div>
      </div>
    </div>
  </div>
);

// Card: leads
const LeadsCard = ({ onNavigate }) => (
  <div
    onClick={() => onNavigate('prospeccao')}
    style={{
      width: 420, maxWidth: '100%',
      background: 'var(--bg-elev)', border: '1px solid var(--border)', borderRadius: 14,
      borderBottomLeftRadius: 4, overflow: 'hidden', cursor: 'pointer',
    }}>
    <div style={{ padding: '10px 14px', borderBottom: '1px solid var(--border)', display: 'flex', alignItems: 'center', gap: 8 }}>
      <Icon name="search" size={14} style={{ color: 'var(--ai-500)' }} />
      <div style={{ flex: 1 }}>
        <div style={{ fontWeight: 600, fontSize: 13 }}>12 leads encontradas</div>
        <div style={{ fontSize: 10.5, color: 'var(--text-muted)' }}>Sinalética · Centro · &gt;15 colab · Apollo + LinkedIn</div>
      </div>
    </div>
    {[
      { name: 'Visualmax Publicidade', loc: 'Leiria · 22 colab', fit: 91, reason: 'Roland VG3 há 6 anos · expansão recente' },
      { name: 'Grupo Siena', loc: 'Coimbra · 34 colab', fit: 84, reason: 'Abriu 2.ª unidade · sector match sinalética' },
      { name: 'PrintNow', loc: 'Aveiro · 18 colab', fit: 76, reason: 'Visitou página Mimaki UCJV330 3×' },
    ].map((l, i) => (
      <div key={i} style={{ padding: '10px 14px', borderTop: i ? '1px solid var(--border)' : 'none', display: 'flex', alignItems: 'center', gap: 10 }}>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 12.5, fontWeight: 500 }}>{l.name}</div>
          <div style={{ fontSize: 10.5, color: 'var(--text-muted)', marginTop: 1 }}>{l.loc} · {l.reason}</div>
        </div>
        <div style={{ padding: '3px 9px', borderRadius: 999, fontSize: 11, fontWeight: 700, fontFamily: 'var(--font-display)', background: l.fit >= 85 ? 'color-mix(in oklch, var(--success) 16%, transparent)' : 'var(--bg-sunken)', color: l.fit >= 85 ? 'var(--success)' : 'var(--text-muted)' }}>{l.fit}</div>
      </div>
    ))}
    <div style={{ padding: '10px 14px', borderTop: '1px solid var(--border)', background: 'var(--bg-sunken)', fontSize: 11, color: 'var(--ai-500)', fontWeight: 600, display: 'flex', alignItems: 'center', gap: 3 }}>
      Abrir lista completa (12) <Icon name="chevronRight" size={10} />
    </div>
  </div>
);

// ============ context panel (colapsado por default) ============
const ContextPanel = ({ open, onClose }) => (
  <aside style={{
    width: open ? 320 : 0,
    flexShrink: 0,
    borderLeft: open ? '1px solid var(--border)' : 'none',
    background: 'var(--bg-sunken)',
    overflow: 'hidden',
    transition: 'width 0.22s cubic-bezier(0.4,0,0.2,1)',
    display: 'flex', flexDirection: 'column',
  }}>
    <div style={{ padding: '12px 16px', borderBottom: '1px solid var(--border)', display: 'flex', alignItems: 'center', gap: 8 }}>
      <Icon name="sparkle" size={13} style={{ color: 'var(--ai-500)' }} />
      <div style={{ flex: 1, fontSize: 12, fontWeight: 600, letterSpacing: '0.04em' }}>Contexto</div>
      <button onClick={onClose} className="btn btn-xs btn-ghost" style={{ padding: 4 }}>
        <Icon name="close" size={12} />
      </button>
    </div>
    <div style={{ padding: 16, overflowY: 'auto', flex: 1 }} className="scrollbar">
      <div style={{ fontSize: 10, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', letterSpacing: '0.06em', marginBottom: 8 }}>O QUE A DIGI ESTÁ A VER</div>
      <div style={{ padding: 12, background: 'var(--bg-elev)', border: '1px solid var(--border)', borderRadius: 8, marginBottom: 12 }}>
        <div style={{ fontSize: 11, color: 'var(--text-muted)', marginBottom: 4 }}>Cliente em foco</div>
        <div style={{ fontSize: 13, fontWeight: 600, marginBottom: 6 }}>Gráfica Norte Lda</div>
        <div style={{ fontSize: 11, color: 'var(--text-muted)', lineHeight: 1.5 }}>LTV 487k € · 67d sem compra · 1 OP stage 80 · risco churn.</div>
      </div>
      <div style={{ padding: 12, background: 'var(--bg-elev)', border: '1px solid var(--border)', borderRadius: 8, marginBottom: 12 }}>
        <div style={{ fontSize: 11, color: 'var(--text-muted)', marginBottom: 4 }}>Simulação recente</div>
        <div style={{ fontSize: 13, fontWeight: 600, marginBottom: 6 }}>UCJV330-160 · 800m²</div>
        <div style={{ fontSize: 11, color: 'var(--text-muted)', lineHeight: 1.5 }}>1,74 €/m² · 1.395 €/mês · ROI 14m.</div>
      </div>
      <div style={{ fontSize: 10, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', letterSpacing: '0.06em', marginBottom: 8 }}>FONTES CONSULTADAS</div>
      <div style={{ fontSize: 11, color: 'var(--text-muted)', lineHeight: 1.8 }}>
        <div>· Primavera CRM · histórico 18m</div>
        <div>· ProdTrack · 3 encomendas</div>
        <div>· SAT · 0 tickets abertos</div>
        <div>· KB · PPE100 · UCJV330</div>
      </div>
    </div>
  </aside>
);

// ============ composer ============
const Composer = ({ onSend, onChipClick }) => {
  const [text, setText] = React.useState('');
  const taRef = React.useRef(null);
  React.useEffect(() => {
    const ta = taRef.current; if (!ta) return;
    ta.style.height = 'auto';
    ta.style.height = clamp(ta.scrollHeight, 22, 120) + 'px';
  }, [text]);
  const submit = () => {
    if (!text.trim()) return;
    onSend(text.trim());
    setText('');
  };
  const CHIPS = [
    { label: 'Simular', icon: 'dollar', prefill: 'Simula UCJV330-160 para 800m²/mês em PrintPlan' },
    { label: 'Prospectar', icon: 'search', prefill: 'Procura empresas de sinalética no centro com >15 colab' },
    { label: 'Ver cliente', icon: 'sales', prefill: 'Qual é o status da Gráfica Norte?' },
    { label: 'Ficha técnica', icon: 'doc', prefill: 'Tens a ficha do PPE100?' },
    { label: 'Coach', icon: 'sparkle', prefill: 'Como abordar uma objecção de preço?' },
  ];
  return (
    <div style={{ borderTop: '1px solid var(--border)', background: 'var(--bg-elev)', padding: '10px 16px 14px' }}>
      <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginBottom: 10 }}>
        {CHIPS.map(c => (
          <button key={c.label}
            onClick={() => onChipClick ? onChipClick(c) : setText(c.prefill)}
            style={{
              display: 'inline-flex', alignItems: 'center', gap: 5,
              padding: '5px 10px', borderRadius: 999,
              fontSize: 11.5, fontWeight: 500,
              background: 'var(--bg-sunken)', color: 'var(--text-muted)',
              border: '1px solid var(--border)',
              transition: 'all 0.12s',
            }}
            onMouseEnter={e => { e.currentTarget.style.color = 'var(--text)'; e.currentTarget.style.background = 'var(--bg-hover)'; }}
            onMouseLeave={e => { e.currentTarget.style.color = 'var(--text-muted)'; e.currentTarget.style.background = 'var(--bg-sunken)'; }}
          >
            <Icon name={c.icon} size={11} />
            {c.label}
          </button>
        ))}
      </div>
      <div style={{
        display: 'flex', alignItems: 'flex-end', gap: 8,
        padding: '8px 8px 8px 12px',
        background: 'var(--bg-sunken)', border: '1px solid var(--border)',
        borderRadius: 22,
      }}>
        <button title="Anexar" className="btn btn-sm btn-ghost" style={{ padding: 6, flexShrink: 0 }}>
          <Icon name="plus" size={16} />
        </button>
        <textarea
          ref={taRef}
          value={text}
          onChange={e => setText(e.target.value)}
          onKeyDown={e => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); submit(); } }}
          placeholder="Pergunta à Digi…"
          rows={1}
          style={{
            flex: 1, resize: 'none', border: 'none', outline: 'none',
            background: 'transparent', color: 'var(--text)',
            fontSize: 14, lineHeight: 1.5, padding: '4px 2px',
            fontFamily: 'inherit', minHeight: 22, maxHeight: 120,
          }}
        />
        <button title="Ditar (em breve)" className="btn btn-sm btn-ghost" style={{ padding: 6, flexShrink: 0, opacity: 0.6 }}>
          <Icon name="mic" size={16} />
        </button>
        <button onClick={submit} disabled={!text.trim()} style={{
          width: 34, height: 34, borderRadius: 17, flexShrink: 0,
          background: text.trim() ? 'var(--ai-500)' : 'var(--surface-muted)',
          color: text.trim() ? '#fff' : 'var(--text-dim)',
          display: 'grid', placeItems: 'center',
          border: 'none',
          transition: 'background 0.12s',
        }}>
          <Icon name="send" size={14} />
        </button>
      </div>
      <div style={{ textAlign: 'center', fontSize: 10, color: 'var(--text-dim)', marginTop: 8, fontFamily: 'var(--font-mono)' }}>
        Enter para enviar · Shift+Enter para nova linha · A Digi pode errar, confirma informação importante.
      </div>
    </div>
  );
};

// ============ main screen ============
const ComercialDigiScreen = ({ onOpenChat, onNavigateSub }) => {
  const [contextOpen, setContextOpen] = React.useState(false);
  const defaultMessages = [
    { id: 'brief', from: 'digi', type: 'briefing', time: '08:00' },
    { id: 'm2', from: 'user', type: 'text', text: 'Bom dia. Abre-me a Gráfica Norte e dá-me um resumo.', time: '09:14' },
    { id: 'm3', from: 'digi', type: 'text', text: 'Aqui vai — a conta está em risco real, não só arrefecer:', time: '09:14' },
    { id: 'm4', from: 'digi', type: 'cliente', time: '09:14' },
    { id: 'm5', from: 'digi', type: 'text', text: 'A OP #1847 ficou em stage 80 desde dia 11. Proposta 340k € enviada, sem resposta.\n\nSugestão: em vez de reenviar, liga ao João Afonso (CEO) e faz uma pergunta aberta sobre o timing da decisão. Recuso de concorrência é mais provável do que de preço — o Roland VG3 deles tem 6 anos, já estão em "modo manutenção mental".', time: '09:14' },
    { id: 'm6', from: 'user', type: 'text', text: 'Ok. Simula UCJV330-160 para o volume deles.', time: '09:16' },
    { id: 'm7', from: 'digi', type: 'text', text: 'Feito. Volume médio histórico: 820 m²/mês. Modelei em PrintPlan (menos CAPEX, mais convincente para uma gráfica em fase de avaliação):', time: '09:16' },
    { id: 'm8', from: 'digi', type: 'simulacao', time: '09:16' },
    { id: 'm9', from: 'digi', type: 'actions', label: 'Queres que…', chips: [
      { label: 'Gere PDF proposta', icon: 'doc', primary: true },
      { label: 'Envie ficha PPE100', icon: 'send' },
      { label: 'Procure decisores adicionais', icon: 'search' },
    ], time: '09:16' },
  ];
  const [messages, setMessages] = React.useState(defaultMessages);
  const [typing, setTyping] = React.useState(false);
  const scrollRef = React.useRef(null);

  React.useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [messages, typing]);

  const handleSend = (text) => {
    const t = timeNow();
    const uMsg = { id: 'u' + Date.now(), from: 'user', type: 'text', text, time: t, source: 'web' };
    setMessages(prev => [...prev, uMsg]);
    setTyping(true);
    setTimeout(() => {
      setTyping(false);
      const reply = inferReply(text);
      setMessages(prev => [...prev, ...reply.map((r, i) => ({ ...r, id: 'd' + Date.now() + i, from: 'digi', time: timeNow() }))]);
    }, 900);
  };

  const inferReply = (t) => {
    const l = t.toLowerCase();
    if (l.includes('ficha') || l.includes('ppe')) return [
      { type: 'text', text: 'Aqui tens:' },
      { type: 'ficha' },
    ];
    if (l.includes('lead') || l.includes('prospec') || l.includes('procura')) return [
      { type: 'text', text: 'Encontrei 12 empresas com fit ≥70. Ordenado por probabilidade de switch:' },
      { type: 'leads' },
    ];
    if (l.includes('simul') || l.includes('ucjv') || l.includes('ujv')) return [
      { type: 'text', text: 'Feito. Assumi volume médio da carteira (~800m²/mês) — ajusta se precisares:' },
      { type: 'simulacao' },
    ];
    if (l.includes('cliente') || l.includes('gráfica') || l.includes('grafica') || l.includes('status')) return [
      { type: 'text', text: 'Claro:' },
      { type: 'cliente' },
    ];
    return [{ type: 'text', text: 'Entendi. Deixa-me ver isso agora…' }];
  };

  const navigateSub = (target) => {
    if (onNavigateSub) onNavigateSub(target);
  };

  return (
    <div style={{ display: 'flex', height: '100%', minHeight: 0, background: 'var(--bg)' }}>
      {/* Main chat column */}
      <div style={{ flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column' }}>
        {/* thin status bar */}
        <div style={{ height: 40, flexShrink: 0, borderBottom: '1px solid var(--border)', padding: '0 20px', display: 'flex', alignItems: 'center', gap: 10, background: 'var(--bg-elev)' }}>
          <DigiAvatar size={22} />
          <div style={{ flex: 1, lineHeight: 1.15 }}>
            <div style={{ fontSize: 12.5, fontWeight: 600 }}>Digi</div>
            <div style={{ fontSize: 10, color: 'var(--success)', display: 'flex', alignItems: 'center', gap: 4 }}>
              <span style={{ width: 5, height: 5, borderRadius: '50%', background: 'var(--success)' }} />
              online · {typing ? 'a escrever…' : 'mesma conversa do WhatsApp'}
            </div>
          </div>
          <button className="btn btn-xs btn-ghost" title="Histórico" style={{ padding: '4px 8px' }}>
            <Icon name="clock" size={12} />
          </button>
          <button
            className="btn btn-xs btn-ghost"
            onClick={() => setContextOpen(v => !v)}
            title={contextOpen ? 'Fechar contexto' : 'Ver contexto'}
            style={{ padding: '4px 8px', background: contextOpen ? 'var(--bg-hover)' : 'transparent' }}
          >
            <Icon name="sparkle" size={12} style={{ color: 'var(--ai-500)' }} />
            <span style={{ marginLeft: 4 }}>Contexto</span>
          </button>
        </div>

        {/* conversation */}
        <div ref={scrollRef} style={{ flex: 1, minHeight: 0, overflowY: 'auto', padding: '8px 0' }} className="scrollbar">
          <div style={{ maxWidth: 780, margin: '0 auto', padding: '0 20px' }}>
            <DateDivider label="TERÇA · 23 ABR" />
            {messages.map((m, idx) => {
              const prev = messages[idx - 1];
              const showAvatar = !prev || prev.from !== m.from;
              if (m.type === 'briefing') {
                return (
                  <Bubble key={m.id} from="digi" time={m.time} showAvatar={showAvatar}>
                    <TextBubble from="digi">Bom dia, Daniel. Hoje tens 4 coisas para olhar:</TextBubble>
                    <BriefingCard onNavigate={navigateSub} />
                  </Bubble>
                );
              }
              if (m.type === 'text') {
                return (
                  <Bubble key={m.id} from={m.from} time={m.time} showAvatar={showAvatar} source={m.source} voiceMeta={m.voiceMeta} emailMeta={m.emailMeta}>
                    <TextBubble from={m.from}>{m.text.split('\n').map((l, i) => <React.Fragment key={i}>{i > 0 && <br/>}{l}</React.Fragment>)}</TextBubble>
                  </Bubble>
                );
              }
              if (m.type === 'cliente') {
                return <Bubble key={m.id} from="digi" time={m.time} showAvatar={showAvatar}><ClienteCard onNavigate={navigateSub} /></Bubble>;
              }
              if (m.type === 'simulacao') {
                return <Bubble key={m.id} from="digi" time={m.time} showAvatar={showAvatar}><SimulacaoCard onNavigate={navigateSub} /></Bubble>;
              }
              if (m.type === 'ficha') {
                return <Bubble key={m.id} from="digi" time={m.time} showAvatar={showAvatar}><FichaCard /></Bubble>;
              }
              if (m.type === 'leads') {
                return <Bubble key={m.id} from="digi" time={m.time} showAvatar={showAvatar}><LeadsCard onNavigate={navigateSub} /></Bubble>;
              }
              if (m.type === 'actions') {
                return (
                  <Bubble key={m.id} from="digi" time={m.time} showAvatar={showAvatar}>
                    <TextBubble from="digi">{m.label}</TextBubble>
                    <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginTop: 2 }}>
                      {m.chips.map((c, i) => <ActionChip key={i} {...c} onClick={() => {}} />)}
                    </div>
                  </Bubble>
                );
              }
              return null;
            })}
            {typing && (
              <Bubble from="digi" showAvatar>
                <div style={{
                  padding: '12px 14px', borderRadius: 14, borderBottomLeftRadius: 4,
                  background: 'var(--bg-elev)', border: '1px solid var(--border)',
                  display: 'flex', gap: 4,
                }}>
                  {[0,1,2].map(i => (
                    <span key={i} style={{
                      width: 6, height: 6, borderRadius: 3, background: 'var(--text-dim)',
                      animation: `digi-typing 1.4s ease-in-out ${i * 0.16}s infinite`,
                    }} />
                  ))}
                </div>
              </Bubble>
            )}
            <div style={{ height: 12 }} />
          </div>
        </div>

        <div style={{ maxWidth: 780, margin: '0 auto', width: '100%' }}>
          <Composer onSend={handleSend} />
        </div>
      </div>

      <ContextPanel open={contextOpen} onClose={() => setContextOpen(false)} />

      <style>{`
        @keyframes digi-typing {
          0%, 60%, 100% { opacity: 0.3; transform: translateY(0); }
          30% { opacity: 1; transform: translateY(-3px); }
        }
        :root { --wa-out: #056162; }
        :root[data-theme="light"] { --wa-out: #0a8f90; }
      `}</style>
    </div>
  );
};

window.ComercialDigiScreen = ComercialDigiScreen;
