// ─── CRM Sucesso 8! — Views ───────────────────────────────────────────────────
(function () {
const {
  FUNIL_ETAPAS: ETAPAS, PRODUTOS: PRODS, ORIGENS: ORIGS,
  TODAY: CRM_TODAY, isOverdue: over, isDueToday: dueToday,
  fmtDate: fmt, fmtCurrency: fmtVal, getEtapa: etapa
} = window.CRMData;

// ─── Dashboard ────────────────────────────────────────────────────────────────
function DashboardView({ leads, onOpenLead, onNewLead }) {
  const regular   = leads.filter(l => !l.isUpsell);
  const upsells   = leads.filter(l => l.isUpsell);
  const pipeline  = leads.filter(l => ['cafe_virtual','proposta_enviada','proposta_aprovada'].includes(l.etapa));
  const contracted = leads.filter(l => ['contrato_assinado','servico_andamento','servico_finalizado'].includes(l.etapa));
  const revenue   = contracted.reduce((s, l) => s + (l.valor || 0), 0);
  const overdueLd = leads.filter(l => over(l.followUpData));
  const todayLd   = leads.filter(l => dueToday(l.followUpData));
  const combined  = [...overdueLd, ...todayLd.filter(l => !over(l.followUpData))];
  const recent    = leads.slice().sort((a,b) => b.criadoEm.localeCompare(a.criadoEm)).slice(0, 5);
  const vozRevenue = contracted.filter(l => l.ecossistema === 'voz').reduce((s,l)=>s+(l.valor||0),0);
  const autoRevenue = contracted.filter(l => l.ecossistema === 'automatiza').reduce((s,l)=>s+(l.valor||0),0);

  return (
    <div style={{ padding: '28px 32px', maxWidth: 1160 }}>
      <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', marginBottom: 28 }}>
        <div>
          <h1 style={{ fontSize: 26, fontWeight: 800, color: '#1C1A12', margin: 0, fontFamily: "'Bricolage Grotesque',sans-serif" }}>Dashboard</h1>
          <p style={{ fontSize: 14, color: '#8C8470', margin: '4px 0 0' }}>Visão geral · Ecossistema Sucesso 8!</p>
        </div>
        <button onClick={() => onNewLead({})} style={{
          display: 'flex', alignItems: 'center', gap: 6, padding: '10px 20px',
          borderRadius: 10, border: 'none', background: '#B8860B', color: '#fff',
          cursor: 'pointer', fontSize: 14, fontWeight: 700, fontFamily: 'inherit',
        }}>+ Novo Lead</button>
      </div>

      {/* Stats */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 14, marginBottom: 28 }}>
        {[
          { label: 'Total de Leads',  value: regular.length,  sub: `${upsells.length} upsell${upsells.length !== 1 ? 's' : ''}`,    accent: '#1C1A12' },
          { label: 'Em Pipeline',     value: pipeline.length, sub: 'oportunidades ativas',                                             accent: '#2563EB' },
          { label: 'Contratos',       value: contracted.length, sub: 'assinados ou em andamento',                                      accent: '#7C3AED' },
          { label: 'Receita Fechada', value: `R$ ${(revenue/1000).toFixed(0)}k`, sub: `V.O.Z. R$${(vozRevenue/1000).toFixed(0)}k · Auto R$${(autoRevenue/1000).toFixed(0)}k`, accent: '#16A34A' },
          { label: 'Follow-ups',      value: overdueLd.length, sub: overdueLd.length > 0 ? 'em atraso — ação necessária' : todayLd.length + ' para hoje', accent: overdueLd.length > 0 ? '#DC2626' : '#B45309' },
        ].map(s => (
          <div key={s.label} style={{
            background: '#fff', borderRadius: 14, padding: '18px 20px',
            border: '1px solid #EAE4D2', boxShadow: '0 1px 4px rgba(0,0,0,0.04)',
          }}>
            <div style={{ fontSize: 28, fontWeight: 800, color: s.accent, fontVariantNumeric: 'tabular-nums', lineHeight: 1 }}>{s.value}</div>
            <div style={{ fontSize: 13, fontWeight: 600, color: '#1C1A12', margin: '6px 0 2px' }}>{s.label}</div>
            <div style={{ fontSize: 11, color: '#8C8470' }}>{s.sub}</div>
          </div>
        ))}
      </div>

      {/* Funil mini */}
      <div style={{ background: '#fff', borderRadius: 14, border: '1px solid #EAE4D2', padding: '16px 20px', marginBottom: 24 }}>
        <div style={{ fontSize: 14, fontWeight: 700, color: '#1C1A12', marginBottom: 14 }}>Distribuição no Funil</div>
        <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
          {ETAPAS.map(e => {
            const count = leads.filter(l => l.etapa === e.id).length;
            return (
              <div key={e.id} style={{
                flex: '1 1 100px', minWidth: 80, padding: '10px 12px', borderRadius: 10,
                background: count > 0 ? e.bg : '#F9F6F0',
                border: `1px solid ${count > 0 ? e.color + '40' : '#EAE4D2'}`,
              }}>
                <div style={{ fontSize: 20, fontWeight: 800, color: count > 0 ? e.color : '#C4BAA8' }}>{count}</div>
                <div style={{ fontSize: 11, fontWeight: 600, color: count > 0 ? e.color : '#8C8470', marginTop: 2, lineHeight: 1.3 }}>{e.label}</div>
              </div>
            );
          })}
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 22 }}>
        {/* Follow-ups */}
        <div style={{ background: '#fff', borderRadius: 14, border: '1px solid #EAE4D2', overflow: 'hidden' }}>
          <div style={{
            padding: '14px 18px', borderBottom: '1px solid #EAE4D2',
            display: 'flex', justifyContent: 'space-between', alignItems: 'center',
          }}>
            <span style={{ fontSize: 14, fontWeight: 700, color: '#1C1A12' }}>⏰ Follow-ups Prioritários</span>
            {combined.length > 0 && (
              <span style={{
                fontSize: 11, fontWeight: 700, padding: '2px 8px', borderRadius: 10,
                background: overdueLd.length > 0 ? '#FEE2E2' : '#FEF9C3',
                color: overdueLd.length > 0 ? '#DC2626' : '#B45309',
              }}>{combined.length}</span>
            )}
          </div>
          <div style={{ maxHeight: 260, overflowY: 'auto' }}>
            {combined.length === 0 ? (
              <p style={{ padding: '24px', color: '#8C8470', fontSize: 13, textAlign: 'center' }}>✓ Tudo em dia!</p>
            ) : combined.map(lead => (
              <div key={lead.id} onClick={() => onOpenLead(lead)}
                onMouseEnter={e => e.currentTarget.style.background='#FAFAF6'}
                onMouseLeave={e => e.currentTarget.style.background='transparent'}
                style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '11px 18px',
                  cursor: 'pointer', borderBottom: '1px solid #F5F2EA', transition: 'background 0.1s' }}>
                <Avatar nome={lead.nome} size={32} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13, fontWeight: 700, color: '#1C1A12', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{lead.nome}</div>
                  <div style={{ fontSize: 11, color: '#8C8470' }}>{lead.followUpHora || '—'} · {lead.produto || '—'}</div>
                </div>
                <FollowUpBadge data={lead.followUpData} hora={lead.followUpHora} />
              </div>
            ))}
          </div>
        </div>

        {/* Leads recentes */}
        <div style={{ background: '#fff', borderRadius: 14, border: '1px solid #EAE4D2', overflow: 'hidden' }}>
          <div style={{ padding: '14px 18px', borderBottom: '1px solid #EAE4D2' }}>
            <span style={{ fontSize: 14, fontWeight: 700, color: '#1C1A12' }}>✦ Leads Recentes</span>
          </div>
          <div>
            {recent.map(lead => (
              <div key={lead.id} onClick={() => onOpenLead(lead)}
                onMouseEnter={e => e.currentTarget.style.background='#FAFAF6'}
                onMouseLeave={e => e.currentTarget.style.background='transparent'}
                style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '11px 18px',
                  cursor: 'pointer', borderBottom: '1px solid #F5F2EA', transition: 'background 0.1s' }}>
                <Avatar nome={lead.nome} size={32} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13, fontWeight: 700, color: '#1C1A12', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{lead.nome}</div>
                  <div style={{ fontSize: 11, color: '#8C8470' }}>{fmt(lead.criadoEm)}</div>
                </div>
                <EtapaTag etapaId={lead.etapa} small />
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

// ─── Kanban Card ─────────────────────────────────────────────────────────────
function KanbanCard({ lead, onClick }) {
  const eco = PRODS[lead.ecossistema];
  return (
    <div onClick={onClick}
      onMouseEnter={e => { e.currentTarget.style.boxShadow='0 4px 12px rgba(0,0,0,0.1)'; e.currentTarget.style.borderColor='#D4C89A'; }}
      onMouseLeave={e => { e.currentTarget.style.boxShadow='0 1px 3px rgba(0,0,0,0.05)'; e.currentTarget.style.borderColor='#EAE4D2'; }}
      style={{
        background: '#fff', borderRadius: 10, padding: '11px 12px',
        border: '1px solid #EAE4D2', cursor: 'pointer',
        boxShadow: '0 1px 3px rgba(0,0,0,0.05)', transition: 'all 0.12s',
      }}>
      <div style={{ display: 'flex', alignItems: 'flex-start', gap: 8, marginBottom: 7 }}>
        <Avatar nome={lead.nome} size={26} />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 13, fontWeight: 700, color: '#1C1A12', lineHeight: 1.3 }}>{lead.nome}</div>
          {lead.empresa && <div style={{ fontSize: 11, color: '#8C8470', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{lead.empresa}</div>}
        </div>
      </div>
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 3, marginBottom: 6 }}>
        {eco && <span style={{ fontSize: 10, fontWeight: 700, padding: '2px 6px', borderRadius: 4, background: eco.bg, color: eco.color }}>{eco.short}</span>}
        {lead.isUpsell && <UpsellBadge />}
        {(over(lead.followUpData) || dueToday(lead.followUpData)) && <FollowUpBadge data={lead.followUpData} hora={lead.followUpHora} />}
      </div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <span style={{ fontSize: 11, color: '#8C8470', flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', marginRight: 8 }}>
          {lead.produto || '—'}
        </span>
        {lead.valor > 0 && (
          <span style={{ fontSize: 11, fontWeight: 700, color: '#B8860B', flexShrink: 0 }}>
            R$ {(lead.valor/1000).toFixed(1)}k
          </span>
        )}
      </div>
    </div>
  );
}

// ─── Kanban View ──────────────────────────────────────────────────────────────
function KanbanView({ leads, onOpenLead, onNewLead }) {
  const [filterEco, setFilterEco] = React.useState('all');
  const [showUpsell, setShowUpsell] = React.useState(true);

  const filtered = leads.filter(l => {
    if (!showUpsell && l.isUpsell) return false;
    if (filterEco !== 'all' && l.ecossistema !== filterEco) return false;
    return true;
  });

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%', overflow: 'hidden' }}>
      <div style={{ padding: '18px 22px 14px', borderBottom: '1px solid #EAE4D2', flexShrink: 0, display: 'flex', alignItems: 'center', gap: 14 }}>
        <h1 style={{ fontSize: 22, fontWeight: 800, color: '#1C1A12', margin: 0, flex: 1, fontFamily: "'Bricolage Grotesque',sans-serif" }}>Funil de Vendas</h1>
        <div style={{ display: 'flex', gap: 6 }}>
          {[{id:'all',label:'Todos'},{id:'voz',label:'V.O.Z.'},{id:'automatiza',label:'Automatiza'}].map(f => (
            <button key={f.id} onClick={() => setFilterEco(f.id)} style={{
              padding: '6px 13px', borderRadius: 8, cursor: 'pointer', fontSize: 12, fontWeight: 600,
              border: filterEco===f.id ? '1px solid #B8860B' : '1px solid #EAE4D2',
              background: filterEco===f.id ? '#FFFBEB' : '#fff',
              color: filterEco===f.id ? '#B8860B' : '#5C5440', fontFamily: 'inherit',
            }}>{f.label}</button>
          ))}
          <button onClick={() => setShowUpsell(!showUpsell)} style={{
            padding: '6px 13px', borderRadius: 8, cursor: 'pointer', fontSize: 12, fontWeight: 600,
            border: showUpsell ? '1px solid #F0CC60' : '1px solid #EAE4D2',
            background: showUpsell ? '#FFFBEB' : '#fff',
            color: showUpsell ? '#B45309' : '#8C8470', fontFamily: 'inherit',
          }}>↑ Upsell {showUpsell ? '✓' : ''}</button>
        </div>
        <button onClick={() => onNewLead({})} style={{
          padding: '8px 18px', borderRadius: 10, border: 'none',
          background: '#B8860B', color: '#fff', cursor: 'pointer',
          fontSize: 13, fontWeight: 700, fontFamily: 'inherit',
        }}>+ Novo Lead</button>
      </div>

      <div style={{ flex: 1, overflowX: 'auto', overflowY: 'hidden', padding: '14px 22px 20px', display: 'flex', gap: 12 }}>
        {ETAPAS.map(e => {
          const stageLeads = filtered.filter(l => l.etapa === e.id);
          const isNegada = e.id === 'proposta_negada';
          return (
            <div key={e.id} style={{
              width: 240, minWidth: 240, flexShrink: 0, display: 'flex', flexDirection: 'column',
              background: isNegada ? '#FFF5F5' : '#F5F2EA',
              borderRadius: 12, border: `1px solid ${isNegada ? '#FECACA' : '#E4DFCF'}`,
              maxHeight: '100%', opacity: isNegada ? 0.92 : 1,
            }}>
              <div style={{ padding: '11px 13px', borderBottom: `1px solid ${isNegada ? '#FECACA' : '#E4DFCF'}`, flexShrink: 0 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
                  <div style={{ width: 9, height: 9, borderRadius: '50%', background: e.color, flexShrink: 0 }}></div>
                  <span style={{ fontSize: 12, fontWeight: 700, color: e.color, flex: 1 }}>{e.label}</span>
                  <span style={{ fontSize: 11, fontWeight: 700, padding: '1px 7px', borderRadius: 10, background: e.bg, color: e.color }}>{stageLeads.length}</span>
                </div>
              </div>
              <div style={{ flex: 1, overflowY: 'auto', padding: '8px 8px', display: 'flex', flexDirection: 'column', gap: 6 }}>
                {stageLeads.map(lead => (
                  <KanbanCard key={lead.id} lead={lead} onClick={() => onOpenLead(lead)} />
                ))}
                {stageLeads.length === 0 && (
                  <div style={{ padding: '18px 8px', textAlign: 'center', color: '#B0A890', fontSize: 12 }}>Vazio</div>
                )}
              </div>
              <div style={{ padding: '8px', flexShrink: 0 }}>
                <button onClick={() => onNewLead({ etapa: e.id })} style={{
                  width: '100%', padding: '6px', borderRadius: 8, border: '1px dashed #D4C89A',
                  background: 'transparent', cursor: 'pointer', fontSize: 12, color: '#8C8470',
                  fontFamily: 'inherit', transition: 'all 0.1s',
                }}
                onMouseEnter={e2 => { e2.currentTarget.style.background='#fff'; e2.currentTarget.style.color='#B8860B'; }}
                onMouseLeave={e2 => { e2.currentTarget.style.background='transparent'; e2.currentTarget.style.color='#8C8470'; }}
                >+ Adicionar</button>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

// ─── Leads List View ──────────────────────────────────────────────────────────
function LeadsView({ leads, onOpenLead, onNewLead }) {
  const [search, setSearch] = React.useState('');
  const [filterEtapa, setFilterEtapa] = React.useState('all');
  const [filterEco, setFilterEco] = React.useState('all');
  const [sortBy, setSortBy] = React.useState('criadoEm');

  const filtered = leads.filter(l => {
    if (filterEtapa !== 'all' && l.etapa !== filterEtapa) return false;
    if (filterEco !== 'all' && l.ecossistema !== filterEco) return false;
    if (search) {
      const q = search.toLowerCase();
      return l.nome.toLowerCase().includes(q) ||
        (l.email||'').toLowerCase().includes(q) ||
        (l.empresa||'').toLowerCase().includes(q) ||
        (l.produto||'').toLowerCase().includes(q);
    }
    return true;
  }).sort((a, b) => {
    if (sortBy === 'nome') return a.nome.localeCompare(b.nome);
    if (sortBy === 'valor') return (b.valor||0) - (a.valor||0);
    return b.criadoEm.localeCompare(a.criadoEm);
  });

  const thS = {
    padding: '10px 14px', fontSize: 11, fontWeight: 700, color: '#8C8470',
    letterSpacing: '0.06em', textTransform: 'uppercase', textAlign: 'left',
    background: '#F9F6F0', borderBottom: '1px solid #EAE4D2', whiteSpace: 'nowrap',
  };
  const tdS = { padding: '11px 14px', fontSize: 13, color: '#1C1A12', borderBottom: '1px solid #F5F2EA' };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%', overflow: 'hidden' }}>
      <div style={{ padding: '18px 22px 14px', borderBottom: '1px solid #EAE4D2', flexShrink: 0 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 12 }}>
          <h1 style={{ fontSize: 22, fontWeight: 800, color: '#1C1A12', margin: 0, flex: 1, fontFamily: "'Bricolage Grotesque',sans-serif" }}>Leads</h1>
          <button onClick={() => onNewLead({})} style={{
            padding: '8px 18px', borderRadius: 10, border: 'none',
            background: '#B8860B', color: '#fff', cursor: 'pointer',
            fontSize: 13, fontWeight: 700, fontFamily: 'inherit',
          }}>+ Novo Lead</button>
        </div>
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
          <input value={search} onChange={e => setSearch(e.target.value)} placeholder="Buscar por nome, e-mail, empresa..."
            style={{
              flex: '1 1 200px', padding: '8px 12px', borderRadius: 8,
              border: '1px solid #EAE4D2', fontSize: 13, fontFamily: 'inherit',
              background: '#fff', outline: 'none',
            }} />
          <select value={filterEtapa} onChange={e => setFilterEtapa(e.target.value)} style={{
            padding: '8px 12px', borderRadius: 8, border: '1px solid #EAE4D2',
            fontSize: 13, fontFamily: 'inherit', background: '#fff', cursor: 'pointer',
          }}>
            <option value="all">Todas as etapas</option>
            {ETAPAS.map(e => <option key={e.id} value={e.id}>{e.label}</option>)}
          </select>
          <select value={filterEco} onChange={e => setFilterEco(e.target.value)} style={{
            padding: '8px 12px', borderRadius: 8, border: '1px solid #EAE4D2',
            fontSize: 13, fontFamily: 'inherit', background: '#fff', cursor: 'pointer',
          }}>
            <option value="all">Todos os ecossistemas</option>
            <option value="voz">Método V.O.Z.</option>
            <option value="automatiza">Automatiza Isso</option>
          </select>
          <select value={sortBy} onChange={e => setSortBy(e.target.value)} style={{
            padding: '8px 12px', borderRadius: 8, border: '1px solid #EAE4D2',
            fontSize: 13, fontFamily: 'inherit', background: '#fff', cursor: 'pointer',
          }}>
            <option value="criadoEm">Mais recentes</option>
            <option value="nome">Nome A→Z</option>
            <option value="valor">Maior valor</option>
          </select>
        </div>
      </div>

      <div style={{ flex: 1, overflowY: 'auto' }}>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            <tr>
              <th style={thS}>Lead</th>
              <th style={thS}>Contato</th>
              <th style={thS}>Ecossistema</th>
              <th style={thS}>Produto</th>
              <th style={thS}>Etapa</th>
              <th style={thS}>Valor</th>
              <th style={thS}>Follow-up</th>
              <th style={thS}>Responsável</th>
            </tr>
          </thead>
          <tbody>
            {filtered.map(lead => (
              <tr key={lead.id}
                onClick={() => onOpenLead(lead)}
                onMouseEnter={e => e.currentTarget.style.background='#FAFAF6'}
                onMouseLeave={e => e.currentTarget.style.background='transparent'}
                style={{ cursor: 'pointer', transition: 'background 0.1s' }}>
                <td style={tdS}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 9 }}>
                    <Avatar nome={lead.nome} size={30} />
                    <div>
                      <div style={{ fontWeight: 700, lineHeight: 1.3 }}>{lead.nome}</div>
                      {lead.empresa && <div style={{ fontSize: 11, color: '#8C8470' }}>{lead.empresa}</div>}
                      {lead.isUpsell && <UpsellBadge />}
                    </div>
                  </div>
                </td>
                <td style={tdS}>
                  <div style={{ fontSize: 12, color: '#5C5440', lineHeight: 1.6 }}>
                    {lead.email && <div>{lead.email}</div>}
                    {lead.whatsapp && <div>{lead.whatsapp}</div>}
                  </div>
                </td>
                <td style={tdS}>{lead.ecossistema && <ProdutoBadge ecossistema={lead.ecossistema} small />}</td>
                <td style={tdS}><span style={{ fontSize: 12, color: '#5C5440' }}>{lead.produto || '—'}</span></td>
                <td style={tdS}><EtapaTag etapaId={lead.etapa} small /></td>
                <td style={tdS}>
                  <span style={{ fontWeight: 700, color: '#B8860B' }}>
                    {lead.valor ? `R$ ${Number(lead.valor).toLocaleString('pt-BR')}` : '—'}
                  </span>
                </td>
                <td style={tdS}>
                  {lead.followUpData ? (
                    <div>
                      <div style={{ fontSize: 12, color: over(lead.followUpData) ? '#DC2626' : '#5C5440', fontWeight: over(lead.followUpData) ? 700 : 400 }}>
                        {fmt(lead.followUpData)}
                      </div>
                      {(over(lead.followUpData) || dueToday(lead.followUpData)) && <FollowUpBadge data={lead.followUpData} hora={lead.followUpHora} />}
                    </div>
                  ) : <span style={{ color: '#B0A890' }}>—</span>}
                </td>
                <td style={tdS}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                    <Avatar nome={lead.responsavel} size={22} />
                    <span style={{ fontSize: 12, color: '#5C5440' }}>{lead.responsavel}</span>
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
        {filtered.length === 0 && (
          <div style={{ padding: '48px', textAlign: 'center', color: '#8C8470', fontSize: 14 }}>Nenhum lead encontrado.</div>
        )}
      </div>
      <div style={{ padding: '10px 22px', borderTop: '1px solid #EAE4D2', fontSize: 12, color: '#8C8470', flexShrink: 0 }}>
        {filtered.length} de {leads.length} lead{leads.length !== 1 ? 's' : ''}
      </div>
    </div>
  );
}

// ─── Notifications View ────────────────────────────────────────────────────────
function NotificationsView({ leads, onOpenLead, onMarkDone }) {
  const overdueLds = leads.filter(l => over(l.followUpData)).sort((a,b) => a.followUpData.localeCompare(b.followUpData));
  const todayLds   = leads.filter(l => dueToday(l.followUpData));
  const upcoming   = leads.filter(l => l.followUpData && l.followUpData > CRM_TODAY && !dueToday(l.followUpData))
    .sort((a,b) => a.followUpData.localeCompare(b.followUpData)).slice(0, 12);

  function NotifSection({ title, items, accentColor, bgColor, borderColor }) {
    if (!items.length) return null;
    return (
      <div style={{ marginBottom: 28 }}>
        <div style={{ fontSize: 12, fontWeight: 700, color: accentColor, letterSpacing: '0.06em',
          textTransform: 'uppercase', marginBottom: 10, display: 'flex', alignItems: 'center', gap: 8 }}>
          {title}
          <span style={{ padding: '1px 8px', borderRadius: 10, background: bgColor, color: accentColor, fontSize: 11 }}>
            {items.length}
          </span>
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {items.map(lead => (
            <div key={lead.id}
              onMouseEnter={e => e.currentTarget.style.boxShadow='0 3px 10px rgba(0,0,0,0.1)'}
              onMouseLeave={e => e.currentTarget.style.boxShadow='0 1px 3px rgba(0,0,0,0.05)'}
              style={{
                display: 'flex', alignItems: 'center', gap: 14,
                background: '#fff', borderRadius: 12, padding: '13px 16px',
                border: `1px solid ${borderColor}`,
                boxShadow: '0 1px 3px rgba(0,0,0,0.05)', transition: 'box-shadow 0.1s',
              }}>
              <div onClick={() => onOpenLead(lead)} style={{ display: 'flex', alignItems: 'center', gap: 12, flex: 1, cursor: 'pointer', minWidth: 0 }}>
                <Avatar nome={lead.nome} size={38} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 15, fontWeight: 700, color: '#1C1A12' }}>{lead.nome}</div>
                  <div style={{ fontSize: 12, color: '#8C8470', marginTop: 1 }}>
                    {fmt(lead.followUpData)}{lead.followUpHora ? ` às ${lead.followUpHora}` : ''}
                    {' · '}{lead.produto || 'sem produto'}{' · '}{lead.responsavel}
                  </div>
                </div>
              </div>
              <div style={{ display: 'flex', gap: 8, alignItems: 'center', flexShrink: 0 }}>
                <EtapaTag etapaId={lead.etapa} small />
                <button onClick={e => { e.stopPropagation(); onMarkDone(lead); }} style={{
                  padding: '6px 12px', borderRadius: 8, border: '1px solid #DCFCE7',
                  background: '#F0FDF4', color: '#16A34A', cursor: 'pointer',
                  fontSize: 12, fontWeight: 700, fontFamily: 'inherit',
                }}>✓ Feito</button>
              </div>
            </div>
          ))}
        </div>
      </div>
    );
  }

  return (
    <div style={{ padding: '28px 32px', maxWidth: 900 }}>
      <h1 style={{ fontSize: 26, fontWeight: 800, color: '#1C1A12', margin: '0 0 4px', fontFamily: "'Bricolage Grotesque',sans-serif" }}>Notificações</h1>
      <p style={{ fontSize: 14, color: '#8C8470', margin: '0 0 28px' }}>Follow-ups e lembretes de ação comercial</p>
      <NotifSection title="⚠ Atrasados"    items={overdueLds} accentColor="#DC2626" bgColor="#FEE2E2" borderColor="#FECACA" />
      <NotifSection title="⏰ Hoje"         items={todayLds}   accentColor="#B45309" bgColor="#FEF9C3" borderColor="#FDE68A" />
      <NotifSection title="📅 Próximos"     items={upcoming}   accentColor="#2563EB" bgColor="#DBEAFE" borderColor="#BAE6FD" />
      {overdueLds.length === 0 && todayLds.length === 0 && upcoming.length === 0 && (
        <div style={{ textAlign: 'center', padding: '64px 0', color: '#8C8470' }}>
          <div style={{ fontSize: 32, marginBottom: 12 }}>✓</div>
          <div style={{ fontSize: 16, fontWeight: 600 }}>Tudo em dia!</div>
          <div style={{ fontSize: 13, marginTop: 4 }}>Sem follow-ups pendentes por enquanto.</div>
        </div>
      )}
    </div>
  );
}

// ─── Inbox View ───────────────────────────────────────────────────────────────
function InboxView({ inboxLeads, onImport, onIgnore }) {
  const [expanded, setExpanded] = React.useState(null);

  if (!inboxLeads.length) {
    return (
      <div style={{ padding: '28px 32px', maxWidth: 860 }}>
        <h1 style={{ fontSize: 26, fontWeight: 800, color: '#1C1A12', margin: '0 0 4px', fontFamily: "'Bricolage Grotesque',sans-serif" }}>Caixa de Entrada</h1>
        <p style={{ fontSize: 14, color: '#8C8470', margin: '0 0 40px' }}>Leads captados via Formulário de Inscrição do site</p>
        <div style={{ textAlign: 'center', padding: '60px 0', color: '#8C8470' }}>
          <div style={{ fontSize: 36, marginBottom: 12 }}>📥</div>
          <div style={{ fontSize: 16, fontWeight: 600 }}>Caixa vazia</div>
          <div style={{ fontSize: 13, marginTop: 4 }}>Nenhum lead novo via formulário.</div>
        </div>
      </div>
    );
  }

  return (
    <div style={{ padding: '28px 32px', maxWidth: 860 }}>
      <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', marginBottom: 24 }}>
        <div>
          <h1 style={{ fontSize: 26, fontWeight: 800, color: '#1C1A12', margin: '0 0 4px', fontFamily: "'Bricolage Grotesque',sans-serif" }}>Caixa de Entrada</h1>
          <p style={{ fontSize: 14, color: '#8C8470', margin: 0 }}>Leads captados via Formulário de Inscrição do site</p>
        </div>
        <span style={{
          padding: '4px 14px', borderRadius: 20, fontSize: 13, fontWeight: 700,
          background: '#FEF3C7', color: '#D97706', border: '1px solid #FDE68A',
        }}>{inboxLeads.length} novo{inboxLeads.length !== 1 ? 's' : ''}</span>
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
        {inboxLeads.map(lead => {
          const isOpen = expanded === lead.id;
          const eco = window.CRMData.PRODUTOS[lead.ecossistema];
          const notasLines = (lead.notas || '').split('\n');

          return (
            <div key={lead.id} style={{
              background: '#fff', borderRadius: 14, border: '1px solid #EAE4D2',
              overflow: 'hidden', boxShadow: '0 2px 8px rgba(0,0,0,0.05)',
            }}>
              {/* Card header */}
              <div style={{ padding: '16px 20px', display: 'flex', alignItems: 'center', gap: 14 }}>
                <Avatar nome={lead.nome} size={44} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 16, fontWeight: 700, color: '#1C1A12', marginBottom: 4 }}>{lead.nome}</div>
                  <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', alignItems: 'center' }}>
                    {eco && <ProdutoBadge ecossistema={lead.ecossistema} small />}
                    <span style={{ fontSize: 12, color: '#5C5440' }}>{lead.produto}</span>
                  </div>
                  <div style={{ fontSize: 12, color: '#8C8470', marginTop: 3 }}>
                    {lead.email} · {lead.whatsapp} · {fmt(lead.criadoEm)}
                  </div>
                </div>
                <div style={{ display: 'flex', gap: 8, flexShrink: 0 }}>
                  <button onClick={() => setExpanded(isOpen ? null : lead.id)} style={{
                    padding: '7px 14px', borderRadius: 8, border: '1px solid #EAE4D2',
                    background: '#FAFAF6', cursor: 'pointer', fontSize: 12, fontWeight: 600,
                    color: '#5C5440', fontFamily: 'inherit',
                  }}>{isOpen ? '▲ Menos' : '▼ Ver respostas'}</button>
                  <button onClick={() => onIgnore(lead.id)} style={{
                    padding: '7px 12px', borderRadius: 8, border: '1px solid #FECACA',
                    background: '#FFF5F5', cursor: 'pointer', fontSize: 12, color: '#DC2626',
                    fontFamily: 'inherit',
                  }}>Ignorar</button>
                  <button onClick={() => onImport(lead)} style={{
                    padding: '7px 16px', borderRadius: 8, border: 'none',
                    background: '#B8860B', color: '#fff', cursor: 'pointer',
                    fontSize: 13, fontWeight: 700, fontFamily: 'inherit',
                  }}>+ Adicionar ao Funil</button>
                </div>
              </div>

              {/* Expanded: questionnaire answers */}
              {isOpen && (
                <div style={{ borderTop: '1px solid #EAE4D2', padding: '16px 20px', background: '#FAFAF6' }}>
                  <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, marginBottom: 16 }}>
                    {lead.linkedin && (
                      <div>
                        <div style={{ fontSize: 11, fontWeight: 700, color: '#8C8470', letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: 4 }}>LinkedIn</div>
                        <a href={lead.linkedin.startsWith('http') ? lead.linkedin : 'https://'+lead.linkedin} target="_blank" rel="noreferrer" style={{ fontSize: 13, color: '#2563EB', textDecoration: 'none' }}>{lead.linkedin}</a>
                      </div>
                    )}
                    {lead.instagram && (
                      <div>
                        <div style={{ fontSize: 11, fontWeight: 700, color: '#8C8470', letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: 4 }}>Instagram</div>
                        <span style={{ fontSize: 13, color: '#5C5440' }}>{lead.instagram}</span>
                      </div>
                    )}
                  </div>
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
                    {notasLines.filter(l => l.trim() && !l.startsWith('📋')).map((line, i) => {
                      const isLabel = !line.startsWith(' ') && notasLines[i+1] && !notasLines[i+1].trim() === false && i > 0;
                      return line.trim() ? (
                        <div key={i} style={{ fontSize: 13, color: line.includes('?') || line.includes(':') ? '#8C8470' : '#1C1A12', fontWeight: line.includes('?') || line.includes(':') ? 600 : 400, lineHeight: 1.6 }}>
                          {line}
                        </div>
                      ) : null;
                    })}
                  </div>
                </div>
              )}
            </div>
          );
        })}
      </div>
    </div>
  );
}

Object.assign(window, { DashboardView, KanbanView, KanbanCard, LeadsView, NotificationsView, InboxView });
})();
