/* global React, Card, Button, Icon, ICONS, Field, sb */
const { useState, useEffect } = React;

const STAGES = [
  { id: 'new',      lab: 'Novo Lead',  tone: '#597EF7' },
  { id: 'contact',  lab: 'Contato',    tone: '#FADB14' },
  { id: 'proposal', lab: 'Proposta',   tone: '#FA8C16' },
  { id: 'closed',   lab: 'Fechado',    tone: '#22C55E' },
];

function fmtBRL(n) {
  const num = parseFloat(n) || 0;
  if (num === 0) return '—';
  return 'R$ ' + num.toLocaleString('pt-BR', { minimumFractionDigits: 0, maximumFractionDigits: 0 });
}

function rowToLead(row) {
  return {
    id:      row.id,
    name:    row.name     || '—',
    email:   row.email    || '',
    phone:   row.phone    || '',
    company: row.company  || '',
    value:   parseFloat(row.value) || 0,
    stage:   row.stage    || 'new',
    notes:   row.notes    || '',
  };
}

// ─── Lead Modal (create / edit) ──────────────────────────────────────────────
function LeadModal({ lead, onClose, onSave, onDelete }) {
  const isNew = !lead;
  const [form, setForm] = useState(lead ? {
    name:    lead.name,
    email:   lead.email,
    phone:   lead.phone,
    company: lead.company,
    value:   lead.value || '',
    stage:   lead.stage,
    notes:   lead.notes,
  } : { name: '', email: '', phone: '', company: '', value: '', stage: 'new', notes: '' });
  const [saving,     setSaving]     = useState(false);
  const [confirmDel, setConfirmDel] = useState(false);

  const set = (k) => (e) => setForm(f => ({ ...f, [k]: e.target.value }));

  const inputStyle = {
    width: '100%', background: 'var(--bg-elevated)', border: '1px solid var(--border-subtle)',
    borderRadius: 8, padding: '8px 10px', color: 'var(--fg-primary)', fontSize: 13,
    fontFamily: 'inherit', outline: 'none', boxSizing: 'border-box',
  };
  const labelStyle = {
    fontSize: 11, fontWeight: 700, color: 'var(--fg-muted)',
    textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: 6, display: 'block',
  };

  async function handleSave() {
    if (!form.name.trim()) { window.__toast?.('Nome é obrigatório.', { tone: 'danger' }); return; }
    setSaving(true);
    await onSave(form);
    setSaving(false);
    onClose();
  }

  async function handleDelete() {
    await onDelete(lead.id);
    onClose();
  }

  return (
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(8,12,28,0.55)', backdropFilter: 'blur(4px)', zIndex: 200, display: 'flex', alignItems: 'stretch', justifyContent: 'flex-end' }}>
      <div onClick={e => e.stopPropagation()} style={{ width: 440, display: 'flex', flexDirection: 'column', background: 'var(--bg-surface)', borderLeft: '1px solid var(--border-subtle)', boxShadow: '-20px 0 60px rgba(0,0,0,0.4)' }}>
        {/* Header */}
        <div style={{ padding: '18px 22px', borderBottom: '1px solid var(--border-subtle)', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <div>
            <span style={{ display: 'inline-block', fontFamily: 'var(--font-display)', fontSize: 9, fontWeight: 700, letterSpacing: '0.06em', padding: '2px 8px', borderRadius: 4, background: '#597EF724', color: '#597EF7', marginBottom: 6 }}>LEAD</span>
            <h2 style={{ margin: 0, fontSize: 16, fontWeight: 700 }}>{isNew ? 'Novo lead' : form.name}</h2>
          </div>
          <button onClick={onClose} style={{ background: 'transparent', border: 'none', color: 'var(--fg-muted)', cursor: 'pointer', padding: 4 }}><Icon d={ICONS.x} size={18}/></button>
        </div>

        {/* Body */}
        <div style={{ flex: 1, overflow: 'auto', padding: '20px 22px', display: 'flex', flexDirection: 'column', gap: 18 }}>
          <div>
            <label style={labelStyle}>Nome *</label>
            <input value={form.name} onChange={set('name')} placeholder="Nome do lead" style={inputStyle} autoFocus={isNew}/>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
            <div>
              <label style={labelStyle}>E-mail</label>
              <input value={form.email} onChange={set('email')} placeholder="email@exemplo.com" style={inputStyle}/>
            </div>
            <div>
              <label style={labelStyle}>Telefone</label>
              <input value={form.phone} onChange={set('phone')} placeholder="(11) 99999-9999" style={inputStyle}/>
            </div>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
            <div>
              <label style={labelStyle}>Empresa</label>
              <input value={form.company} onChange={set('company')} placeholder="Nome da empresa" style={inputStyle}/>
            </div>
            <div>
              <label style={labelStyle}>Valor do negócio (R$)</label>
              <input type="number" min="0" value={form.value} onChange={set('value')} placeholder="0" style={inputStyle}/>
            </div>
          </div>
          <div>
            <label style={labelStyle}>Etapa</label>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
              {STAGES.map(s => (
                <button key={s.id} onClick={() => setForm(f => ({ ...f, stage: s.id }))}
                  style={{ padding: '6px 12px', borderRadius: 8, fontSize: 12, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit', background: form.stage === s.id ? s.tone + '22' : 'var(--bg-elevated)', color: form.stage === s.id ? s.tone : 'var(--fg-secondary)', border: `1px solid ${form.stage === s.id ? s.tone + '66' : 'var(--border-subtle)'}` }}>
                  {s.lab}
                </button>
              ))}
            </div>
          </div>
          <div>
            <label style={labelStyle}>Notas</label>
            <textarea value={form.notes} onChange={set('notes')} placeholder="Observações sobre o lead…" rows={4} style={{ ...inputStyle, resize: 'vertical', lineHeight: 1.5 }}/>
          </div>
        </div>

        {/* Footer */}
        <div style={{ padding: '12px 22px', borderTop: '1px solid var(--border-subtle)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          {!isNew && (
            confirmDel ? (
              <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <span style={{ fontSize: 12, color: 'var(--fg-secondary)' }}>Apagar este lead?</span>
                <button onClick={handleDelete} style={{ padding: '6px 12px', borderRadius: 7, border: 'none', cursor: 'pointer', fontFamily: 'inherit', fontSize: 12, fontWeight: 600, background: '#EF4444', color: '#fff' }}>Apagar</button>
                <button onClick={() => setConfirmDel(false)} style={{ padding: '6px 12px', borderRadius: 7, border: 'none', cursor: 'pointer', fontFamily: 'inherit', fontSize: 12, fontWeight: 600, background: 'var(--bg-elevated)', color: 'var(--fg-secondary)' }}>Cancelar</button>
              </div>
            ) : (
              <button onClick={() => setConfirmDel(true)}
                style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '6px 10px', borderRadius: 7, border: '1px solid transparent', cursor: 'pointer', fontFamily: 'inherit', fontSize: 12, fontWeight: 500, background: 'transparent', color: 'var(--fg-muted)', transition: 'all 140ms' }}
                onMouseEnter={e => { e.currentTarget.style.background = '#EF444420'; e.currentTarget.style.color = '#EF4444'; e.currentTarget.style.borderColor = '#EF444440'; }}
                onMouseLeave={e => { e.currentTarget.style.background = 'transparent'; e.currentTarget.style.color = 'var(--fg-muted)'; e.currentTarget.style.borderColor = 'transparent'; }}>
                <Icon d={ICONS.trash} size={13}/>Apagar lead
              </button>
            )
          )}
          {isNew && <div/>}
          <div style={{ display: 'flex', gap: 8 }}>
            <Button variant="secondary" onClick={onClose}>Cancelar</Button>
            <Button onClick={handleSave} disabled={saving}>{saving ? 'Salvando…' : isNew ? 'Criar lead' : 'Salvar'}</Button>
          </div>
        </div>
      </div>
    </div>
  );
}

// ─── Lead Card ───────────────────────────────────────────────────────────────
function LeadCard({ lead, dragging, onDragStart, onDragEnd, onClick }) {
  const stage = STAGES.find(s => s.id === lead.stage) || STAGES[0];
  return (
    <div draggable={true}
      onDragStart={e => { e.dataTransfer.setData('text/plain', String(lead.id)); e.dataTransfer.effectAllowed = 'move'; requestAnimationFrame(() => onDragStart(lead.id)); }}
      onDragEnd={onDragEnd}
      onClick={onClick}
      className="ds-card hov"
      style={{ background: 'var(--bg-surface)', border: '1px solid var(--border-subtle)', borderRadius: 10, padding: 12, display: 'flex', flexDirection: 'column', gap: 8, cursor: 'grab', boxShadow: 'var(--shadow-1)', opacity: dragging ? 0.35 : 1, transition: 'opacity 100ms', userSelect: 'none', WebkitUserSelect: 'none' }}>
      {/* Name */}
      <div style={{ fontSize: 13, fontWeight: 700, lineHeight: 1.3 }}>{lead.name}</div>

      {/* Company */}
      {lead.company && (
        <div style={{ fontSize: 11, color: 'var(--fg-muted)', display: 'flex', alignItems: 'center', gap: 5 }}>
          <Icon d={ICONS.briefcase} size={11}/>
          <span>{lead.company}</span>
        </div>
      )}

      {/* Contact info */}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
        {lead.email && (
          <div style={{ fontSize: 11, color: 'var(--fg-secondary)', display: 'flex', alignItems: 'center', gap: 5, overflow: 'hidden' }}>
            <Icon d={ICONS.mail} size={11}/>
            <span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{lead.email}</span>
          </div>
        )}
        {lead.phone && (
          <div style={{ fontSize: 11, color: 'var(--fg-secondary)', display: 'flex', alignItems: 'center', gap: 5 }}>
            <Icon d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07A19.5 19.5 0 0 1 4.69 12 19.79 19.79 0 0 1 1.63 3.44 2 2 0 0 1 3.6 2h3a2 2 0 0 1 2 1.72c.127.96.361 1.903.7 2.81a2 2 0 0 1-.45 2.11L7.91 9.91a16 16 0 0 0 6.18 6.18l.95-.95a2 2 0 0 1 2.11-.45c.907.339 1.85.573 2.81.7A2 2 0 0 1 22 17z" size={11}/>
            <span>{lead.phone}</span>
          </div>
        )}
      </div>

      {/* Value */}
      {lead.value > 0 && (
        <div style={{ marginTop: 2, padding: '4px 8px', borderRadius: 6, background: '#22C55E18', color: '#22C55E', fontSize: 12, fontWeight: 700, fontFamily: 'var(--font-mono)', alignSelf: 'flex-start' }}>
          {fmtBRL(lead.value)}
        </div>
      )}
    </div>
  );
}

// ─── Leads (Pipeline Kanban) ──────────────────────────────────────────────────
function Leads() {
  const [leads,       setLeads]       = useState([]);
  const [loading,     setLoading]     = useState(true);
  const [q,           setQ]           = useState('');
  const [draggingId,  setDraggingId]  = useState(null);
  const [dragOverCol, setDragOverCol] = useState(null);
  const [modal,       setModal]       = useState(null); // null | 'new' | lead object

  useEffect(() => {
    (async () => {
      const { data, error } = await sb.from('leads').select('*').order('created_at', { ascending: false });
      if (error) { window.__toast?.(error.message, { tone: 'danger' }); }
      setLeads((data || []).map(rowToLead));
      setLoading(false);
    })();
  }, []);

  const filtered = leads.filter(l =>
    !q ||
    l.name.toLowerCase().includes(q.toLowerCase()) ||
    (l.company || '').toLowerCase().includes(q.toLowerCase()) ||
    (l.email || '').toLowerCase().includes(q.toLowerCase())
  );

  async function moveLead(id, toStage) {
    setLeads(prev => prev.map(l => l.id === id ? { ...l, stage: toStage } : l));
    await sb.from('leads').update({ stage: toStage }).eq('id', id);
  }

  async function saveLead(form) {
    const { data: { user } } = await sb.auth.getUser();
    const payload = {
      user_id: user?.id,
      name:    form.name.trim(),
      email:   form.email.trim(),
      phone:   form.phone.trim(),
      company: form.company.trim(),
      value:   parseFloat(form.value) || 0,
      stage:   form.stage,
      notes:   form.notes.trim(),
    };

    if (modal && modal !== 'new') {
      // Edit
      const { data, error } = await sb.from('leads').update(payload).eq('id', modal.id).select().single();
      if (error) { window.__toast?.('Erro ao salvar: ' + error.message, { tone: 'danger' }); return; }
      setLeads(prev => prev.map(l => l.id === modal.id ? rowToLead(data) : l));
      window.__toast?.('Lead atualizado!', { tone: 'success' });
    } else {
      // Create
      const { data, error } = await sb.from('leads').insert(payload).select().single();
      if (error) { window.__toast?.('Erro ao criar lead: ' + error.message, { tone: 'danger' }); return; }
      setLeads(prev => [rowToLead(data), ...prev]);
      window.__toast?.('Lead criado!', { tone: 'success' });
    }
  }

  async function deleteLead(id) {
    setLeads(prev => prev.filter(l => l.id !== id));
    const { error } = await sb.from('leads').delete().eq('id', id);
    if (error) window.__toast?.('Erro ao apagar: ' + error.message, { tone: 'danger' });
    else window.__toast?.('Lead removido.', { tone: 'success' });
  }

  if (loading) {
    return <div style={{ padding: 40, textAlign: 'center', color: 'var(--fg-muted)', fontSize: 14 }}>Carregando pipeline…</div>;
  }

  const totalValue = leads.reduce((acc, l) => acc + (l.value || 0), 0);

  return (
    <div style={{ padding: '24px 28px', display: 'flex', flexDirection: 'column', gap: 18, height: '100%', boxSizing: 'border-box' }}>
      {/* Toolbar */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, flexWrap: 'wrap' }}>
        <div style={{ width: 280 }}><Field icon="search" placeholder="Buscar lead…" value={q} onChange={e => setQ(e.target.value)}/></div>
        <div style={{ flex: 1 }}/>
        {totalValue > 0 && (
          <div style={{ fontSize: 13, color: 'var(--fg-secondary)', display: 'flex', alignItems: 'center', gap: 6 }}>
            Pipeline total:
            <span style={{ fontWeight: 700, color: '#22C55E', fontFamily: 'var(--font-mono)' }}>{fmtBRL(totalValue)}</span>
          </div>
        )}
        <Button icon="plus" onClick={() => setModal('new')}>Novo lead</Button>
      </div>

      {/* Empty state */}
      {leads.length === 0 && (
        <div style={{ padding: '48px 24px', textAlign: 'center', color: 'var(--fg-muted)' }}>
          <div style={{ fontSize: 32, marginBottom: 12 }}>📋</div>
          <div style={{ fontSize: 15, fontWeight: 600, marginBottom: 6 }}>Nenhum lead ainda</div>
          <div style={{ fontSize: 13, marginBottom: 20 }}>Adicione seu primeiro lead e comece a mover pelo pipeline.</div>
          <Button icon="plus" onClick={() => setModal('new')}>Adicionar primeiro lead</Button>
        </div>
      )}

      {/* Kanban columns */}
      {leads.length > 0 && (
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14, flex: 1, minHeight: 0 }}>
          {STAGES.map(stage => {
            const items = filtered.filter(l => l.stage === stage.id);
            const stageValue = items.reduce((acc, l) => acc + (l.value || 0), 0);
            const isOver = dragOverCol === stage.id;
            return (
              <div key={stage.id}
                onDragEnter={e => { e.preventDefault(); setDragOverCol(stage.id); }}
                onDragOver={e => { e.preventDefault(); }}
                onDragLeave={e => { if (!e.currentTarget.contains(e.relatedTarget)) setDragOverCol(null); }}
                onDrop={e => { e.preventDefault(); const id = e.dataTransfer.getData('text/plain'); if (id) moveLead(id, stage.id); setDraggingId(null); setDragOverCol(null); }}
                style={{ background: isOver ? stage.tone + '14' : 'var(--bg-surface)', border: `${isOver ? 2 : 1}px solid ${isOver ? stage.tone : 'var(--border-subtle)'}`, borderRadius: 14, padding: 14, display: 'flex', flexDirection: 'column', gap: 10, overflow: 'auto', transition: 'background 100ms, border-color 100ms' }}>
                {/* Column header */}
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '0 4px 6px', flexShrink: 0 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8, fontWeight: 700, fontSize: 13 }}>
                    <span style={{ width: 10, height: 10, borderRadius: '50%', background: stage.tone, flexShrink: 0 }}/>
                    {stage.lab}
                    <span style={{ fontSize: 11, color: 'var(--fg-muted)', fontFamily: 'var(--font-mono)' }}>{items.length}</span>
                  </div>
                  {stageValue > 0 && (
                    <span style={{ fontSize: 11, color: stage.tone, fontFamily: 'var(--font-mono)', fontWeight: 700 }}>{fmtBRL(stageValue)}</span>
                  )}
                </div>

                {/* Cards */}
                {items.map(lead => (
                  <LeadCard
                    key={lead.id}
                    lead={lead}
                    dragging={draggingId === lead.id}
                    onDragStart={id => setDraggingId(id)}
                    onDragEnd={() => { setDraggingId(null); setDragOverCol(null); }}
                    onClick={() => setModal(lead)}
                  />
                ))}

                {/* Add button */}
                <button
                  onClick={() => setModal('new')}
                  style={{ background: 'transparent', border: '1px dashed var(--border-subtle)', borderRadius: 8, padding: 10, color: 'var(--fg-muted)', cursor: 'pointer', fontFamily: 'inherit', fontSize: 12, flexShrink: 0 }}>
                  + Adicionar lead
                </button>
              </div>
            );
          })}
        </div>
      )}

      {/* Modal */}
      {modal && (
        <LeadModal
          lead={modal === 'new' ? null : modal}
          onClose={() => setModal(null)}
          onSave={saveLead}
          onDelete={deleteLead}
        />
      )}
    </div>
  );
}
window.Leads = Leads;
window.dispatchEvent(new CustomEvent('leads-ready'));
