
// CRM Module

function CRM() {
  const [clients, setClients] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [selected, setSelected] = React.useState(null);
  const [detailNotes, setDetailNotes] = React.useState([]);
  const [note, setNote] = React.useState('');
  const [addModal, setAddModal] = React.useState(false);
  const [editModal, setEditModal] = React.useState(false);
  const [delConfirm, setDelConfirm] = React.useState(false);
  const [saving, setSaving] = React.useState(false);
  const emptyForm = { name: '', contact: '', email: '', phone: '', city: '', segment: 'SMB', status: 'Prospect' };
  const [form, setForm] = React.useState(emptyForm);
  const [editForm, setEditForm] = React.useState(emptyForm);
  const [toast, setToast] = React.useState(null);
  const showToast = (msg, type = 'success') => { setToast({ msg, type }); setTimeout(() => setToast(null), 3000); };

  React.useEffect(() => {
    sb.from('clients').select('*').order('name').then(({ data }) => {
      if (data) setClients(data);
      setLoading(false);
    });
  }, []);

  const openClient = (c) => {
    setSelected(c);
    setDetailNotes(c.notes || []);
    setNote('');
  };

  const closeClient = () => { setSelected(null); setDetailNotes([]); setNote(''); };

  const saveNote = async () => {
    if (!note.trim() || !selected) return;
    const updated = [...detailNotes, note];
    setDetailNotes(updated);
    setNote('');
    await sb.from('clients').update({ notes: updated }).eq('id', selected.id);
    setClients(prev => prev.map(cl => cl.id === selected.id ? { ...cl, notes: updated } : cl));
    showToast('Anotação salva!');
  };

  const openEdit = () => {
    setEditForm({ name: selected.name, contact: selected.contact || '', email: selected.email || '', phone: selected.phone || '', city: selected.city || '', segment: selected.segment || 'SMB', status: selected.status || 'Prospect' });
    setEditModal(true);
  };

  const handleEditSave = async () => {
    if (!editForm.name.trim()) { showToast('Preencha o nome.', 'danger'); return; }
    setSaving(true);
    const { data, error } = await sb.from('clients').update({
      name: editForm.name, contact: editForm.contact, email: editForm.email,
      phone: editForm.phone, city: editForm.city, segment: editForm.segment, status: editForm.status,
    }).eq('id', selected.id).select().single();
    setSaving(false);
    if (error) { showToast('Erro ao salvar.', 'danger'); return; }
    setClients(prev => prev.map(c => c.id === data.id ? data : c).sort((a, b) => a.name.localeCompare(b.name)));
    setSelected(data);
    setDetailNotes(data.notes || []);
    setEditModal(false);
    showToast('Cliente atualizado!');
  };

  const handleDelete = async () => {
    const id = selected.id;
    const nome = selected.name;
    await sb.from('clients').delete().eq('id', id);
    setClients(prev => prev.filter(c => c.id !== id));
    setDelConfirm(false);
    closeClient();
    showToast(`${nome} excluído.`);
  };

  const handleCreate = async () => {
    if (!form.name.trim()) { showToast('Preencha o nome do cliente.', 'danger'); return; }
    setSaving(true);
    const { data, error } = await sb.from('clients').insert({
      name: form.name, contact: form.contact, email: form.email,
      phone: form.phone, city: form.city, segment: form.segment,
      status: form.status, events_count: 0, total_spent: 0, notes: [],
    }).select().single();
    setSaving(false);
    if (error) { showToast('Erro ao adicionar cliente.', 'danger'); return; }
    setClients(prev => [...prev, data].sort((a, b) => a.name.localeCompare(b.name)));
    setAddModal(false);
    setForm(emptyForm);
    showToast(`${data.name} adicionado com sucesso!`);
  };

  const statusColor   = { 'Ativo': 'success', 'Prospect': 'warning', 'Inativo': 'default' };
  const segmentColor  = { 'Enterprise': 'primary', 'SMB': 'default', 'PF': 'purple' };
  const totalAtivos   = clients.filter(c => c.status === 'Ativo').length;
  const receitaTotal  = clients.reduce((s, c) => s + (c.total_spent || 0), 0);
  const ticketMedio   = clients.length > 0 ? receitaTotal / clients.length : 0;

  const timeline = [
    { icon: 'calendar', text: 'Evento confirmado',          date: '22 Abr 2026', color: DS.colors.primary },
    { icon: 'budget',   text: 'Orçamento enviado',          date: '18 Abr 2026', color: DS.colors.warning },
    { icon: 'message',  text: 'Reunião de briefing realizada', date: '10 Abr 2026', color: DS.colors.success },
  ];

  return (
    <div>
      {/* Header */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 28 }}>
        <div>
          <h1 style={{ fontSize: 24, fontWeight: 700, color: DS.colors.text, margin: 0, letterSpacing: '-0.02em' }}>Clientes (CRM)</h1>
          <p style={{ fontSize: 13, color: DS.colors.textSec, margin: '4px 0 0' }}>Gerencie relacionamentos e histórico de clientes</p>
        </div>
        <Btn icon="plus" onClick={() => setAddModal(true)}>Novo cliente</Btn>
      </div>

      {/* Stats */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12, marginBottom: 24 }}>
        {[
          { label: 'Clientes ativos',  value: totalAtivos,                                          color: DS.colors.primary },
          { label: 'Receita total',    value: 'R$ ' + (receitaTotal / 1000000).toFixed(1) + 'M',   color: DS.colors.success },
          { label: 'Ticket médio',     value: 'R$ ' + Math.round(ticketMedio / 1000) + 'k',         color: DS.colors.warning },
        ].map(s => (
          <Card key={s.label} style={{ padding: '14px 18px' }}>
            <div style={{ fontSize: 11, color: DS.colors.textMuted, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.06em' }}>{s.label}</div>
            <div style={{ fontSize: 22, fontWeight: 800, color: s.color, marginTop: 4 }}>{s.value}</div>
          </Card>
        ))}
      </div>

      {/* Table */}
      <Card>
        {loading ? <Spinner /> : (
          <>
            <div style={{ display: 'grid', gridTemplateColumns: '2fr 1.2fr 1fr 0.8fr 0.8fr 0.8fr 0.8fr', padding: '10px 24px', borderBottom: `1px solid ${DS.colors.border}`, fontSize: 11, fontWeight: 700, color: DS.colors.textMuted, textTransform: 'uppercase', letterSpacing: '0.06em' }}>
              <span>Empresa</span><span>Contato</span><span>Último evento</span><span>Eventos</span><span>Segmento</span><span>Status</span><span style={{ textAlign: 'right' }}>Total</span>
            </div>
            {clients.length === 0
              ? <EmptyState icon="crm" title="Nenhum cliente encontrado" />
              : clients.map((c, i) => (
                <div key={c.id} onClick={() => openClient(c)}
                  style={{ display: 'grid', gridTemplateColumns: '2fr 1.2fr 1fr 0.8fr 0.8fr 0.8fr 0.8fr', padding: '14px 24px', borderBottom: i < clients.length - 1 ? `1px solid ${DS.colors.border}` : 'none', alignItems: 'center', cursor: 'pointer', transition: 'background 0.1s' }}
                  onMouseEnter={e => e.currentTarget.style.background = '#F8FAFC'}
                  onMouseLeave={e => e.currentTarget.style.background = 'transparent'}
                >
                  <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                    <Avatar name={c.name} size={32} />
                    <span style={{ fontSize: 13, fontWeight: 600, color: DS.colors.text }}>{c.name}</span>
                  </div>
                  <span style={{ fontSize: 13, color: DS.colors.textSec }}>{c.contact}</span>
                  <span style={{ fontSize: 13, color: DS.colors.textSec }}>{(c.last_event || '').substring(0, 18)}{(c.last_event || '').length > 18 ? '…' : ''}</span>
                  <span style={{ fontSize: 13, fontWeight: 600, color: DS.colors.text }}>{c.events_count || 0}</span>
                  <span><Badge variant={segmentColor[c.segment]}>{c.segment}</Badge></span>
                  <span><Badge variant={statusColor[c.status]}>{c.status}</Badge></span>
                  <span style={{ fontSize: 13, fontWeight: 700, color: DS.colors.text, textAlign: 'right' }}>R$ {((c.total_spent || 0) / 1000).toFixed(0)}k</span>
                </div>
              ))
            }
          </>
        )}
      </Card>

      {/* ── Popup detalhe do cliente ── */}
      <Modal open={!!selected} onClose={closeClient} title={selected?.name || ''} width={820}
        extra={selected && (
          <div style={{ display: 'flex', gap: 8 }}>
            <Btn variant="secondary" size="sm" icon="edit" onClick={openEdit}>Editar</Btn>
            <Btn variant="danger" size="sm" icon="x" onClick={() => setDelConfirm(true)}>Excluir</Btn>
          </div>
        )}>
        {selected && (
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 280px', gap: 20 }}>
            {/* Coluna esquerda */}
            <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
              {/* Stats */}
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 10 }}>
                {[
                  { label: 'Total investido',   value: 'R$ ' + (selected.total_spent || 0).toLocaleString('pt-BR'), color: DS.colors.primary },
                  { label: 'Eventos realizados', value: selected.events_count || 0,                                  color: DS.colors.success },
                  { label: 'Ticket médio',       value: selected.events_count > 0 ? 'R$ ' + Math.round((selected.total_spent || 0) / selected.events_count).toLocaleString('pt-BR') : '—', color: DS.colors.warning },
                ].map(s => (
                  <div key={s.label} style={{ padding: '14px 16px', background: '#F8FAFC', borderRadius: DS.radius.sm, border: `1px solid ${DS.colors.border}` }}>
                    <div style={{ fontSize: 10, color: DS.colors.textMuted, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.06em' }}>{s.label}</div>
                    <div style={{ fontSize: 20, fontWeight: 800, color: s.color, marginTop: 4 }}>{s.value}</div>
                  </div>
                ))}
              </div>

              {/* Timeline */}
              <div style={{ padding: '18px 20px', background: '#F8FAFC', borderRadius: DS.radius.md, border: `1px solid ${DS.colors.border}` }}>
                <div style={{ fontSize: 13, fontWeight: 700, color: DS.colors.text, marginBottom: 16 }}>Linha do tempo</div>
                {timeline.map((t, i) => (
                  <div key={i} style={{ display: 'flex', gap: 12, marginBottom: i < timeline.length - 1 ? 16 : 0 }}>
                    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', flexShrink: 0 }}>
                      <div style={{ width: 28, height: 28, borderRadius: '50%', background: t.color + '18', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                        <Icon name={t.icon} size={13} color={t.color} />
                      </div>
                      {i < timeline.length - 1 && <div style={{ width: 1, height: 16, background: DS.colors.border, marginTop: 4 }} />}
                    </div>
                    <div style={{ paddingTop: 4 }}>
                      <div style={{ fontSize: 12, fontWeight: 600, color: DS.colors.text }}>{t.text}</div>
                      <div style={{ fontSize: 11, color: DS.colors.textMuted, marginTop: 1 }}>{t.date}</div>
                    </div>
                  </div>
                ))}
              </div>

              {/* Notas */}
              <div style={{ padding: '18px 20px', background: '#F8FAFC', borderRadius: DS.radius.md, border: `1px solid ${DS.colors.border}` }}>
                <div style={{ fontSize: 13, fontWeight: 700, color: DS.colors.text, marginBottom: 12 }}>Anotações & Follow-up</div>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 6, marginBottom: 12 }}>
                  {detailNotes.length === 0
                    ? <div style={{ fontSize: 12, color: DS.colors.textMuted }}>Nenhuma anotação ainda.</div>
                    : detailNotes.map((n, i) => (
                      <div key={i} style={{ display: 'flex', gap: 8, padding: '8px 12px', background: '#FFFBEB', borderRadius: DS.radius.sm, borderLeft: `3px solid ${DS.colors.warning}` }}>
                        <Icon name="edit" size={12} color={DS.colors.warning} />
                        <span style={{ fontSize: 12, color: DS.colors.text }}>{n}</span>
                      </div>
                    ))
                  }
                </div>
                <div style={{ display: 'flex', gap: 8 }}>
                  <input value={note} onChange={e => setNote(e.target.value)}
                    onKeyDown={e => { if (e.key === 'Enter') saveNote(); }}
                    placeholder="Adicionar anotação..."
                    style={{ flex: 1, border: `1px solid ${DS.colors.border}`, borderRadius: DS.radius.sm, padding: '7px 11px', fontSize: 13, outline: 'none', fontFamily: 'inherit' }}
                    onFocus={e => e.target.style.borderColor = DS.colors.primary}
                    onBlur={e => e.target.style.borderColor = DS.colors.border}
                  />
                  <Btn size="sm" onClick={saveNote}>Salvar</Btn>
                </div>
              </div>
            </div>

            {/* Coluna direita — informações */}
            <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
              {/* Avatar + badges */}
              <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', padding: '20px 16px', background: '#F8FAFC', borderRadius: DS.radius.md, border: `1px solid ${DS.colors.border}`, gap: 10 }}>
                <Avatar name={selected.name} size={56} />
                <div style={{ textAlign: 'center' }}>
                  <div style={{ fontSize: 14, fontWeight: 700, color: DS.colors.text }}>{selected.name}</div>
                  <div style={{ fontSize: 12, color: DS.colors.textSec, marginTop: 2 }}>{selected.contact}</div>
                </div>
                <div style={{ display: 'flex', gap: 6 }}>
                  <Badge variant={segmentColor[selected.segment]}>{selected.segment}</Badge>
                  <Badge variant={statusColor[selected.status]}>{selected.status}</Badge>
                </div>
                <div style={{ display: 'flex', gap: 6, width: '100%', marginTop: 4 }}>
                  <Btn variant="secondary" size="sm" icon="mail" style={{ flex: 1, justifyContent: 'center' }}
                    onClick={() => selected.email ? window.open(`mailto:${selected.email}`) : showToast('E-mail não cadastrado.', 'danger')}>E-mail</Btn>
                  <Btn variant="secondary" size="sm" icon="phone" style={{ flex: 1, justifyContent: 'center' }}
                    onClick={() => selected.phone ? window.open(`tel:${selected.phone.replace(/\D/g, '')}`) : showToast('Telefone não cadastrado.', 'danger')}>Ligar</Btn>
                </div>
              </div>

              {/* Dados */}
              <div style={{ padding: '16px', background: '#F8FAFC', borderRadius: DS.radius.md, border: `1px solid ${DS.colors.border}` }}>
                <div style={{ fontSize: 11, fontWeight: 700, color: DS.colors.textMuted, textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: 10 }}>Contato</div>
                {[
                  { icon: 'mail',  label: selected.email  || '—' },
                  { icon: 'phone', label: selected.phone  || '—' },
                  { icon: 'map',   label: selected.city   || '—' },
                ].map(r => (
                  <div key={r.icon} style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '6px 0', borderBottom: `1px solid ${DS.colors.border}`, fontSize: 12 }}>
                    <Icon name={r.icon} size={13} color={DS.colors.textMuted} />
                    <span style={{ color: DS.colors.text }}>{r.label}</span>
                  </div>
                ))}
              </div>

              {/* Último evento */}
              {selected.last_event && (
                <div style={{ padding: '14px 16px', background: DS.colors.primaryLight, borderRadius: DS.radius.md, border: `1px solid #BFDBFE` }}>
                  <div style={{ fontSize: 10, fontWeight: 700, color: DS.colors.primary, textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: 4 }}>Último evento</div>
                  <div style={{ fontSize: 13, fontWeight: 600, color: DS.colors.text }}>{selected.last_event}</div>
                </div>
              )}
            </div>
          </div>
        )}
      </Modal>

      {/* Modal editar cliente */}
      <Modal open={editModal} onClose={() => setEditModal(false)} title="Editar Cliente" width={560}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          <Input label="Empresa / Nome *" value={editForm.name} onChange={v => setEditForm(f => ({ ...f, name: v }))} placeholder="Ex: TechCorp Brasil" />
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
            <Input label="Pessoa de contato" value={editForm.contact} onChange={v => setEditForm(f => ({ ...f, contact: v }))} placeholder="Ex: Marcelo Andrade" />
            <Input label="Cidade" value={editForm.city} onChange={v => setEditForm(f => ({ ...f, city: v }))} placeholder="Ex: São Paulo" />
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
            <Input label="E-mail" value={editForm.email} onChange={v => setEditForm(f => ({ ...f, email: v }))} placeholder="Ex: contato@empresa.com" />
            <Input label="Telefone" value={editForm.phone} onChange={v => setEditForm(f => ({ ...f, phone: v }))} placeholder="Ex: (11) 3291-4400" />
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
            <Select label="Segmento" value={editForm.segment} onChange={v => setEditForm(f => ({ ...f, segment: v }))} options={[{ value: 'Enterprise', label: 'Enterprise' }, { value: 'SMB', label: 'SMB' }, { value: 'PF', label: 'Pessoa Física' }]} />
            <Select label="Status" value={editForm.status} onChange={v => setEditForm(f => ({ ...f, status: v }))} options={[{ value: 'Prospect', label: 'Prospect' }, { value: 'Ativo', label: 'Ativo' }, { value: 'Inativo', label: 'Inativo' }]} />
          </div>
          <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end', marginTop: 4 }}>
            <Btn variant="secondary" onClick={() => setEditModal(false)}>Cancelar</Btn>
            <Btn onClick={handleEditSave} disabled={saving} icon="check">{saving ? 'Salvando…' : 'Salvar alterações'}</Btn>
          </div>
        </div>
      </Modal>

      {/* Confirmação de exclusão */}
      <Modal open={delConfirm} onClose={() => setDelConfirm(false)} title="Excluir cliente" width={400}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <p style={{ fontSize: 14, color: DS.colors.textSec, lineHeight: 1.6 }}>Tem certeza que deseja excluir <strong style={{ color: DS.colors.text }}>{selected?.name}</strong>? Esta ação não pode ser desfeita.</p>
          <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
            <Btn variant="secondary" onClick={() => setDelConfirm(false)}>Cancelar</Btn>
            <Btn variant="danger" icon="x" onClick={handleDelete}>Excluir</Btn>
          </div>
        </div>
      </Modal>

      {/* Modal novo cliente */}
      <Modal open={addModal} onClose={() => { setAddModal(false); setForm(emptyForm); }} title="Novo Cliente" width={560}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          <Input label="Empresa / Nome *" value={form.name} onChange={v => setForm(f => ({ ...f, name: v }))} placeholder="Ex: TechCorp Brasil" />
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
            <Input label="Pessoa de contato" value={form.contact} onChange={v => setForm(f => ({ ...f, contact: v }))} placeholder="Ex: Marcelo Andrade" />
            <Input label="Cidade" value={form.city} onChange={v => setForm(f => ({ ...f, city: v }))} placeholder="Ex: São Paulo" />
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
            <Input label="E-mail" value={form.email} onChange={v => setForm(f => ({ ...f, email: v }))} placeholder="Ex: contato@empresa.com" />
            <Input label="Telefone" value={form.phone} onChange={v => setForm(f => ({ ...f, phone: v }))} placeholder="Ex: (11) 3291-4400" />
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
            <Select label="Segmento" value={form.segment} onChange={v => setForm(f => ({ ...f, segment: v }))} options={[
              { value: 'Enterprise', label: 'Enterprise' },
              { value: 'SMB',        label: 'SMB' },
              { value: 'PF',         label: 'Pessoa Física' },
            ]} />
            <Select label="Status" value={form.status} onChange={v => setForm(f => ({ ...f, status: v }))} options={[
              { value: 'Prospect', label: 'Prospect' },
              { value: 'Ativo',    label: 'Ativo' },
              { value: 'Inativo',  label: 'Inativo' },
            ]} />
          </div>
          <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end', marginTop: 4 }}>
            <Btn variant="secondary" onClick={() => { setAddModal(false); setForm(emptyForm); }}>Cancelar</Btn>
            <Btn onClick={handleCreate} disabled={saving} icon="crm">{saving ? 'Salvando…' : 'Adicionar cliente'}</Btn>
          </div>
        </div>
      </Modal>

      {toast && <Toast message={toast.msg} type={toast.type} onClose={() => setToast(null)} />}
    </div>
  );
}

Object.assign(window, { CRM });
