// CRM — Kanban pipeline with drag & drop
const CRM = ({ onNavigate }) => {
  const initialLeads = {
    novo: [
      { id: 'l1', name: 'Giovanna Prado', company: 'Padaria Sol Nascente', value: 4800, churn: 8, owner: 'Camila Rocha', source: 'Google Maps', days: 1, tags: ['Simples Nacional'] },
      { id: 'l2', name: 'Rodrigo Alves', company: 'Restaurante do Zé', value: 7200, churn: 12, owner: 'Bruno Tavares', source: 'WhatsApp', days: 2, tags: ['MEI'] },
      { id: 'l3', name: 'Fernanda Lima', company: 'Loja Vila Nova', value: 3200, churn: 6, owner: 'Camila Rocha', source: 'Site', days: 1, tags: [] },
    ],
    qualificacao: [
      { id: 'l4', name: 'Marcos Souza', company: 'Oficina Souza Motors', value: 11400, churn: 22, owner: 'Camila Rocha', source: 'Indicação', days: 4, tags: ['Lucro Presumido'] },
      { id: 'l5', name: 'Juliana Xavier', company: 'Clínica Vida Plena', value: 18900, churn: 15, owner: 'Bruno Tavares', source: 'Google Ads', days: 3, tags: ['15 funcionários'] },
    ],
    proposta: [
      { id: 'l6', name: 'Eduardo Barreto', company: 'Supermercado Barreto', value: 26500, churn: 18, owner: 'Camila Rocha', source: 'Indicação', days: 7, tags: ['PDV', '28 funcionários'] },
      { id: 'l7', name: 'Patrícia Reis', company: 'Hamburgueria 22', value: 12400, churn: 9, owner: 'João Pedro', source: 'Instagram', days: 5, tags: [] },
      { id: 'l8', name: 'Gustavo Pinheiro', company: 'Pet Shop Amigo Fiel', value: 6800, churn: 11, owner: 'Camila Rocha', source: 'Site', days: 4, tags: ['Simples Nacional'] },
    ],
    negociacao: [
      { id: 'l9', name: 'Renata Colucci', company: 'Distribuidora RC', value: 38900, churn: 42, owner: 'Bruno Tavares', source: 'Indicação', days: 12, tags: ['ALTO VALOR', '50+ funcionários'] },
      { id: 'l10', name: 'Anderson Viana', company: 'Construtora AV', value: 24000, churn: 28, owner: 'Camila Rocha', source: 'Google Ads', days: 9, tags: [] },
    ],
    ganho: [
      { id: 'l11', name: 'Letícia Fonseca', company: 'Farmácia Bem Estar', value: 9600, churn: 3, owner: 'Bruno Tavares', source: 'Indicação', days: 0, tags: [] },
      { id: 'l12', name: 'Carlos Mendonça', company: 'Padaria São João', value: 14800, churn: 5, owner: 'Camila Rocha', source: 'Site', days: 0, tags: [] },
    ],
    perdido: [
      { id: 'l13', name: 'Sérgio Paiva', company: 'Mecânica Rápida', value: 5400, churn: 78, owner: 'João Pedro', source: 'WhatsApp', days: 14, tags: ['Preço'] },
    ],
  };

  const columns = [
    { id: 'novo', label: 'Novo lead', color: 'var(--ink-500)' },
    { id: 'qualificacao', label: 'Qualificação', color: 'var(--blue-500)' },
    { id: 'proposta', label: 'Proposta enviada', color: 'var(--amber-500)' },
    { id: 'negociacao', label: 'Negociação', color: 'var(--coral-500)' },
    { id: 'ganho', label: 'Fechado — Ganho', color: 'var(--green-500)' },
    { id: 'perdido', label: 'Perdido', color: 'var(--red-500)' },
  ];

  const [leads, setLeads] = React.useState(initialLeads);
  const [selected, setSelected] = React.useState(initialLeads.negociacao[0]);
  const [dragging, setDragging] = React.useState(null);
  const [dragOver, setDragOver] = React.useState(null);
  const [filterOwner, setFilterOwner] = React.useState('todos');
  const [filterPeriod, setFilterPeriod] = React.useState('30d');

  const onDragStart = (lead, colId) => setDragging({ lead, from: colId });
  const onDragEnd = () => { setDragging(null); setDragOver(null); };
  const onDrop = (toCol) => {
    if (!dragging || dragging.from === toCol) { setDragging(null); setDragOver(null); return; }
    setLeads(prev => {
      const next = { ...prev };
      next[dragging.from] = next[dragging.from].filter(l => l.id !== dragging.lead.id);
      next[toCol] = [dragging.lead, ...next[toCol]];
      return next;
    });
    setDragging(null); setDragOver(null);
  };

  const totalValue = Object.values(leads).flat().reduce((s, l) => s + l.value, 0);
  const wonValue = leads.ganho.reduce((s, l) => s + l.value, 0);

  const churnColor = (c) => c > 40 ? 'var(--red-500)' : c > 20 ? 'var(--amber-500)' : 'var(--green-500)';
  const churnLabel = (c) => c > 40 ? 'Alto' : c > 20 ? 'Médio' : 'Baixo';

  return (
    <AppShell current="crm" onNavigate={onNavigate}>
      <div data-screen-label="04 CRM Pipeline" style={{ display: 'grid', gridTemplateColumns: selected ? '1fr 360px' : '1fr', height: 'calc(100vh - 70px)' }}>
        <style>{`
          .crm-header { padding: 20px 28px 0; }
          .crm-header-top { display: flex; justify-content: space-between; align-items: center; margin-bottom: 18px; flex-wrap: wrap; gap: 14px; }
          .crm-metrics { flex-wrap: wrap; }
          .crm-title { font-size: 22px; font-weight: 600; letter-spacing: -0.01em; }
          .crm-sub { font-size: 13px; color: var(--ink-500); margin-top: 2px; }
          .crm-metrics { display: flex; gap: 10px; align-items: center; }
          .crm-metric {
            padding: 8px 14px; border-radius: 10px; background: white;
            border: 1px solid var(--ink-200); font-size: 12px;
          }
          .crm-metric b { display: block; font-size: 14px; margin-top: 2px; font-weight: 600; }
          .crm-toolbar {
            display: flex; gap: 8px; align-items: center; margin-bottom: 16px; flex-wrap: wrap;
          }
          .crm-filter {
            padding: 7px 12px; border: 1px solid var(--ink-200); border-radius: 8px;
            background: white; font-size: 12.5px; color: var(--ink-800);
            display: inline-flex; align-items: center; gap: 6px;
          }
          .crm-filter:hover { border-color: var(--ink-300); }
          .crm-filter.active { border-color: var(--coral-400); background: var(--coral-50); color: var(--coral-700); }

          .kanban { flex: 1; overflow-x: auto; padding: 0 28px 28px; }
          .kanban-row { display: flex; gap: 12px; min-height: 500px; }
          .kanban-col {
            flex: 0 0 280px; background: var(--ink-100); border-radius: 12px;
            padding: 12px; display: flex; flex-direction: column; gap: 10px;
            transition: background .15s;
          }
          .kanban-col.drag-over { background: var(--coral-50); box-shadow: 0 0 0 2px var(--coral-400) inset; }
          .kanban-col-head {
            display: flex; align-items: center; gap: 8px; padding: 0 4px;
          }
          .kanban-col-dot { width: 8px; height: 8px; border-radius: 50%; }
          .kanban-col-title { font-size: 12.5px; font-weight: 600; color: var(--ink-800); }
          .kanban-col-count {
            margin-left: auto; background: white; font-size: 11px; padding: 2px 8px; border-radius: 999px;
            color: var(--ink-600); font-weight: 500;
          }
          .kanban-col-sum { font-size: 10px; color: var(--ink-500); padding: 0 4px; margin-top: -4px; }

          .lead-card {
            background: white; border: 1px solid var(--ink-200); border-radius: 10px;
            padding: 12px; cursor: grab; transition: all .15s;
            display: flex; flex-direction: column; gap: 8px;
          }
          .lead-card:hover { border-color: var(--coral-300); box-shadow: var(--shadow-sm); }
          .lead-card.selected { border-color: var(--coral-500); box-shadow: 0 0 0 2px rgba(234,90,31,.15); }
          .lead-card.dragging { opacity: .4; cursor: grabbing; }
          .lead-card-top { display: flex; justify-content: space-between; gap: 8px; align-items: flex-start; }
          .lead-name { font-size: 13px; font-weight: 600; line-height: 1.3; }
          .lead-company { font-size: 11px; color: var(--ink-500); margin-top: 1px; }
          .lead-value { font-size: 13px; font-weight: 600; color: var(--ink-900); }
          .lead-tags { display: flex; flex-wrap: wrap; gap: 4px; }
          .lead-tag {
            font-size: 10px; padding: 2px 7px; border-radius: 4px;
            background: var(--ink-100); color: var(--ink-600); font-weight: 500;
          }
          .lead-tag.alert { background: var(--red-50); color: var(--red-600); }
          .lead-footer {
            display: flex; justify-content: space-between; align-items: center;
            padding-top: 8px; border-top: 1px solid var(--ink-100);
          }
          .lead-churn {
            display: inline-flex; align-items: center; gap: 5px;
            font-size: 10px; font-weight: 500;
            padding: 2px 6px; border-radius: 4px;
          }
          .lead-actions { display: flex; gap: 4px; }
          .lead-icon-btn {
            width: 24px; height: 24px; border-radius: 6px;
            background: var(--ink-50); display: grid; place-items: center;
          }
          .lead-icon-btn:hover { background: var(--ink-100); }

          /* Detail panel */
          .crm-detail {
            background: white; border-left: 1px solid var(--ink-200);
            overflow-y: auto; display: flex; flex-direction: column;
          }
          .detail-head { padding: 20px; border-bottom: 1px solid var(--ink-200); }
          .detail-name { font-size: 18px; font-weight: 600; letter-spacing: -0.01em; }
          .detail-company { font-size: 13px; color: var(--ink-500); margin-top: 2px; }
          .detail-meta { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; padding: 16px 20px; border-bottom: 1px solid var(--ink-200); }
          .detail-meta-item { font-size: 11px; color: var(--ink-500); }
          .detail-meta-item b { display: block; font-size: 13px; color: var(--ink-900); margin-top: 2px; font-weight: 600; }
          .detail-tabs {
            display: flex; border-bottom: 1px solid var(--ink-200); padding: 0 20px;
          }
          .detail-tab {
            padding: 12px 14px; font-size: 12.5px; font-weight: 500; color: var(--ink-500);
            border-bottom: 2px solid transparent;
          }
          .detail-tab.active { color: var(--coral-600); border-color: var(--coral-500); }
          .detail-body { padding: 16px 20px; flex: 1; }
          .timeline-item {
            display: flex; gap: 12px; padding: 12px 0;
            border-bottom: 1px solid var(--ink-100);
          }
          .timeline-item:last-child { border-bottom: none; }
          .timeline-icon {
            width: 28px; height: 28px; border-radius: 50%;
            display: grid; place-items: center; flex-shrink: 0;
          }
          .timeline-text { font-size: 13px; color: var(--ink-800); line-height: 1.5; }
          .timeline-time { font-size: 11px; color: var(--ink-500); margin-top: 2px; }
          .detail-actions {
            padding: 16px 20px; border-top: 1px solid var(--ink-200);
            display: flex; gap: 8px;
          }
        `}</style>

        <div style={{ display: 'flex', flexDirection: 'column', minWidth: 0, overflow: 'hidden' }}>
          <div className="crm-header">
            <div className="crm-header-top">
              <div>
                <div className="crm-title">Pipeline de vendas</div>
                <div className="crm-sub">CRM · 13 leads ativos · arraste para mover entre etapas</div>
              </div>
              <div className="crm-metrics">
                <div className="crm-metric">Pipeline total<b>{BRL(totalValue)}</b></div>
                <div className="crm-metric">Fechados em abril<b style={{color:'var(--green-600)'}}>{BRL(wonValue)}</b></div>
                <div className="crm-metric">Taxa conversão<b>32,4%</b></div>
                <button className="btn btn-primary" style={{ padding: '8px 14px', fontSize: 13 }}>
                  <Icon name="map" size={14}/>
                  Prospecção Google Maps
                </button>
              </div>
            </div>
            <div className="crm-toolbar">
              <div className="crm-filter active">
                <Icon name="filter" size={13}/> Filtros
              </div>
              <div className={`crm-filter ${filterOwner === 'todos' ? 'active' : ''}`} onClick={() => setFilterOwner('todos')}>
                Vendedor: <b style={{ fontWeight: 600 }}>Todos</b> <Icon name="chevronDown" size={11}/>
              </div>
              <div className="crm-filter">
                Etapa: <b style={{ fontWeight: 600 }}>Todas</b> <Icon name="chevronDown" size={11}/>
              </div>
              <div className="crm-filter">
                Período: <b style={{ fontWeight: 600 }}>30 dias</b> <Icon name="chevronDown" size={11}/>
              </div>
              <div className="crm-filter">
                Score churn <Icon name="chevronDown" size={11}/>
              </div>
              <div style={{ marginLeft: 'auto', display: 'flex', gap: 6 }}>
                <button className="crm-filter"><Icon name="grid" size={13}/> Kanban</button>
                <button className="crm-filter"><Icon name="bar" size={13}/> Funil</button>
                <button className="crm-filter"><Icon name="calendar" size={13}/> Calendário</button>
              </div>
            </div>
          </div>

          <div className="kanban">
            <div className="kanban-row">
              {columns.map(col => {
                const items = leads[col.id] || [];
                const sum = items.reduce((s, l) => s + l.value, 0);
                return (
                  <div
                    key={col.id}
                    className={`kanban-col ${dragOver === col.id ? 'drag-over' : ''}`}
                    onDragOver={(e) => { e.preventDefault(); setDragOver(col.id); }}
                    onDragLeave={() => setDragOver(null)}
                    onDrop={() => onDrop(col.id)}
                  >
                    <div className="kanban-col-head">
                      <span className="kanban-col-dot" style={{ background: col.color }}/>
                      <span className="kanban-col-title">{col.label}</span>
                      <span className="kanban-col-count">{items.length}</span>
                    </div>
                    <div className="kanban-col-sum">{BRL(sum)}</div>
                    {items.map(lead => (
                      <div
                        key={lead.id}
                        className={`lead-card ${selected?.id === lead.id ? 'selected' : ''} ${dragging?.lead.id === lead.id ? 'dragging' : ''}`}
                        draggable
                        onDragStart={() => onDragStart(lead, col.id)}
                        onDragEnd={onDragEnd}
                        onClick={() => setSelected(lead)}
                      >
                        <div className="lead-card-top">
                          <div style={{ minWidth: 0, flex: 1 }}>
                            <div className="lead-name">{lead.name}</div>
                            <div className="lead-company">{lead.company}</div>
                          </div>
                          <div className="lead-value">{BRLShort(lead.value)}</div>
                        </div>
                        {lead.tags.length > 0 && (
                          <div className="lead-tags">
                            {lead.tags.map(t => (
                              <span key={t} className={`lead-tag ${t === 'ALTO VALOR' ? 'alert' : ''}`}>{t}</span>
                            ))}
                          </div>
                        )}
                        <div className="lead-footer">
                          <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                            <Avatar name={lead.owner} size={22}/>
                            <span className="lead-churn" style={{ background: 'var(--ink-50)', color: churnColor(lead.churn) }}>
                              <Icon name="cpu" size={10}/> Churn {lead.churn}% · {churnLabel(lead.churn)}
                            </span>
                          </div>
                          <div className="lead-actions">
                            <button className="lead-icon-btn" onClick={(e) => e.stopPropagation()} title="WhatsApp">
                              <Icon name="whatsapp" size={12} color="#25D366"/>
                            </button>
                            <button className="lead-icon-btn" onClick={(e) => e.stopPropagation()} title="Ligar">
                              <Icon name="phone" size={12} color="var(--ink-600)"/>
                            </button>
                          </div>
                        </div>
                      </div>
                    ))}
                    <button className="lead-card" style={{ border: '1px dashed var(--ink-300)', background: 'transparent', cursor: 'pointer', justifyContent: 'center', color: 'var(--ink-500)', fontSize: 12, padding: 10 }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 6, justifyContent: 'center' }}>
                        <Icon name="plus" size={13}/> Adicionar lead
                      </div>
                    </button>
                  </div>
                );
              })}
            </div>
          </div>
        </div>

        {selected && (
          <aside className="crm-detail">
            <div className="detail-head">
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 8 }}>
                <Avatar name={selected.name} size={48}/>
                <button className="shell-top-btn" onClick={() => setSelected(null)} style={{ width: 28, height: 28 }}>
                  <Icon name="close" size={14}/>
                </button>
              </div>
              <div className="detail-name">{selected.name}</div>
              <div className="detail-company">{selected.company}</div>
              <div style={{ display: 'flex', gap: 6, marginTop: 10, flexWrap: 'wrap' }}>
                <span className="chip chip-coral">Em negociação</span>
                <span className="chip" style={{ background: 'var(--ink-50)', color: churnColor(selected.churn) }}>
                  <Icon name="cpu" size={10}/> Churn {selected.churn}%
                </span>
              </div>
            </div>
            <div className="detail-meta">
              <div className="detail-meta-item">Valor estimado<b>{BRL(selected.value)}</b></div>
              <div className="detail-meta-item">Origem<b>{selected.source}</b></div>
              <div className="detail-meta-item">Responsável<b>{selected.owner}</b></div>
              <div className="detail-meta-item">Há quantos dias<b>{selected.days} dias</b></div>
            </div>
            <div className="detail-tabs">
              <div className="detail-tab active">Atividades</div>
              <div className="detail-tab">E-mails</div>
              <div className="detail-tab">Ligações</div>
              <div className="detail-tab">Anexos</div>
            </div>
            <div className="detail-body">
              {[
                { icon: 'whatsapp', color: '#25D366', bg: '#e6f9ee', text: <><b>Mensagem enviada</b> via WhatsApp sobre ajuste na proposta</>, time: 'Hoje às 14h20' },
                { icon: 'doc', color: 'var(--coral-600)', bg: 'var(--coral-50)', text: <><b>Proposta v2</b> enviada — {BRL(selected.value)} · 12x sem juros</>, time: 'Ontem às 17h12' },
                { icon: 'phone', color: 'var(--blue-600)', bg: 'var(--blue-50)', text: <><b>Ligação</b> de 12min — discutiu prazos de implementação</>, time: '16/04 às 10h30' },
                { icon: 'mail', color: 'var(--ink-700)', bg: 'var(--ink-100)', text: <><b>E-mail</b> com apresentação inicial enviado</>, time: '14/04 às 09h00' },
                { icon: 'sparkle', color: 'var(--coral-600)', bg: 'var(--coral-50)', text: <><b>IA</b> identificou objeção de preço — sugerido desconto de 8%</>, time: '13/04 às 11h50' },
              ].map((t, i) => (
                <div key={i} className="timeline-item">
                  <div className="timeline-icon" style={{ background: t.bg, color: t.color }}>
                    <Icon name={t.icon} size={13}/>
                  </div>
                  <div style={{ flex: 1 }}>
                    <div className="timeline-text">{t.text}</div>
                    <div className="timeline-time">{t.time}</div>
                  </div>
                </div>
              ))}
            </div>
            <div className="detail-actions">
              <button className="btn btn-primary" style={{ flex: 1, padding: '10px', fontSize: 13 }}>
                <Icon name="whatsapp" size={14}/> WhatsApp
              </button>
              <button className="btn btn-outline" style={{ padding: '10px 12px', fontSize: 13 }}>
                <Icon name="phone" size={14}/>
              </button>
              <button className="btn btn-outline" style={{ padding: '10px 12px', fontSize: 13 }}>
                <Icon name="mail" size={14}/>
              </button>
              <button className="btn btn-outline" style={{ padding: '10px 12px', fontSize: 13 }}>
                <Icon name="more" size={14}/>
              </button>
            </div>
          </aside>
        )}
      </div>
    </AppShell>
  );
};

Object.assign(window, { CRM });
