﻿// Global Novo Lead modal — shared across all app pages
// Trigger:  window.dispatchEvent(new CustomEvent('horos:new-lead'))
// Success:  window.dispatchEvent(new CustomEvent('horos:lead-created', { detail: lead }))

const AREA_TO_SEG = {
  mcmv: 'imobiliario', consorcios: 'consorcios',
  seguros: 'seguros', credito: 'credito', creditos: 'credito', veiculos: 'veiculos',
  // demais ramos (horos-segments.js): o segmento do lead é o próprio ramo
  saude: 'saude', educacao: 'educacao', academia: 'academia', servicos: 'servicos', assinaturas: 'assinaturas', varejo: 'varejo', generico: 'generico',
};

function NewLeadModal({ onClose, onCreated }) {
  const [form, setForm] = React.useState({ name: '', phone: '', email: '', cat: '', temp: 'warm', col: 'inbox', origem: '' });
  const [userSeg, setUserSeg] = React.useState('imobiliario');
  const [userName, setUserName] = React.useState('');
  const [saving, setSaving] = React.useState(false);
  const [error, setError] = React.useState('');
  // Vários funis: sem mexer, o banco escolhe pelas regras de entrada; escolhendo, o lead vai para o funil escolhido
  const pipes = usePipelines();
  const [pipe, setPipe] = React.useState(null); // null = automático
  const kanbanCols = useKanbanCols(pipe || pipes.entry || 'main');
  // Gestor (cargo real) pode mandar o lead para a fila de distribuição da equipe; escolha lembrada
  const canDistribute = ['gerente', 'super', 'diretor', 'ceo'].includes(window.HOROS_WORKSPACE?.role)
    && !(window.horosIsSolo && window.horosIsSolo());
  const [distribute, setDistribute] = React.useState(() => {
    try { return localStorage.getItem('horos-newlead-distribute') === '1'; } catch { return false; }
  });
  const setDistributeKeep = (v) => { setDistribute(v); try { localStorage.setItem('horos-newlead-distribute', v ? '1' : '0'); } catch {} };

  const set =(k, v) => setForm(prev => ({ ...prev, [k]: v }));

  const maskPhone = (v) => {
    let d = v.replace(/\D/g, '');
    if (d.length > 11) {
      const take = d.length === 12 ? 10 : 11;
      d = d.slice(d.length - take);
    }
    d = d.slice(0, 11);
    if (d.length <= 2) return d.length ? `(${d}` : '';
    if (d.length <= 6) return `(${d.slice(0,2)}) ${d.slice(2)}`;
    if (d.length <= 10) return `(${d.slice(0,2)}) ${d.slice(2,6)}-${d.slice(6)}`;
    return `(${d.slice(0,2)}) ${d.slice(2,7)}-${d.slice(7)}`;
  };

  React.useEffect(() => {
    const sb = window.HOROS_SB;
    if (!sb) return;
    sb.auth.getSession().then(({ data: { session } }) => {
      if (!session) return;
      sb.from('profiles').select('area, nome, sobrenome').eq('id', session.user.id).single()
        .then(({ data }) => {
          if (data) {
            if (data.area) setUserSeg(AREA_TO_SEG[data.area] || 'imobiliario');
            const name = [data.nome, data.sobrenome].filter(Boolean).join(' ');
            if (name) setUserName(name);
          }
        });
    });
  }, []);

  // Close on Escape
  React.useEffect(() => {
    const handler = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', handler);
    return () => window.removeEventListener('keydown', handler);
  }, []);

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!form.name.trim()) { setError('Nome é obrigatório'); return; }
    if (!form.phone.trim()) { setError('Telefone é obrigatório'); return; }
    setSaving(true); setError('');
    try {
      const sb = window.HOROS_SB;
      const { data: { session } } = await sb.auth.getSession();
      const userId = (session && session.user && session.user.id) || (window.HOROS_USER && window.HOROS_USER.id);
      if (!userId) throw new Error('Sessão expirada. Faça login novamente.');

      const initials = window.initials(form.name) || '?';
      const id = 'L' + Date.now().toString(36).toUpperCase();
      const initialScore = typeof calcScore === 'function'
        ? calcScore({ nome: form.name.trim(), telefone: form.phone.trim(), email: form.email.trim() || '', temp: form.temp }, {})
        : (form.name && form.phone ? (form.temp === 'hot' ? 25 : 22) : 10);
      const { data: newLead, error: dbErr } = await sb.rpc('insert_lead', {
        p_id:      id,
        p_name:    form.name.trim(),
        p_initials: initials,
        p_phone:   form.phone.trim(),
        p_email:   form.email.trim() || null,
        p_seg:     userSeg,
        p_cat:     form.cat.trim(),
        p_temp:    form.temp,
        p_col:     form.col,
        p_value:   0,
        p_score:   initialScore,
        p_broker:  userName || null,
        p_data:    { origemLead: form.origem || 'manual', origemNome: (form.origemNome || '').trim() || undefined, corretor: userName || null },
      });
      if (dbErr) throw dbErr;
      // Deduplicação no banco: mesmo telefone (qualquer formato) já ativo no workspace
      if (newLead && newLead.error === 'duplicate') {
        setError(`Lead duplicado — "${newLead.name}" já está cadastrado com este telefone.`);
        setSaving(false);
        return;
      }

      let lead = newLead || { id, user_id: userId, name: form.name.trim(), initials, seg: userSeg, cat: form.cat.trim(), phone: form.phone.trim(), email: form.email.trim() || null, value: 0, temp: form.temp, col: form.col, score: initialScore, broker: userName || '' };
      let handedOff = false;
      if (canDistribute && distribute && lead.id) {
        const { data: to } = await sb.rpc('distribute_lead', { p_lead_id: lead.id });
        if (to && to !== userId) { lead = { ...lead, assigned_to: to, user_id: to }; handedOff = true; }
      }
      if (pipe && lead.id && !handedOff && (lead.pipeline_id || 'main') !== pipe) {
        try { await horosMoveLeadsPipeline([lead.id], pipe, form.col); lead = { ...lead, pipeline_id: pipe === 'main' ? null : pipe }; }
        catch (e) { console.warn('[novo lead] mover de funil:', e.message); }
      }
      onCreated(lead);
      onClose();

      // Salva contato no WhatsApp como [Horos] {nome} (fire-and-forget)
      const tok = window.HOROS_SESSION?.access_token;
      const rawPhone = form.phone.trim().replace(/\D/g, '');
      if (tok && rawPhone) {
        fetch('/api/whatsapp-instance', {
          method: 'PUT',
          headers: { 'Authorization': `Bearer ${tok}`, 'Content-Type': 'application/json' },
          body: JSON.stringify({ number: rawPhone, contactName: '[Horos] ' + form.name.trim() }),
        }).catch(() => {});
      }

      // Automações "Novo lead": disparadas no banco (trg_lead_new_automation), para lead de qualquer origem
    } catch (err) {
      setError('Ocorreu um erro ao criar o lead. Tente novamente ou fale com o suporte.');
      setSaving(false);
    }
  };

  const F = {
    label: { fontSize:12, fontWeight:600, color:'var(--fg)', display:'block', marginBottom:6 },
    input: { width:'100%', boxSizing:'border-box', background:'var(--bg-1)', border:'1.5px solid var(--line-strong)', borderRadius:8, padding:'9px 12px', fontSize:13, color:'var(--fg)', outline:'none', fontFamily:'inherit', transition:'border-color .15s' },
    select: { width:'100%', boxSizing:'border-box', background:'var(--bg-1)', border:'1.5px solid var(--line-strong)', borderRadius:8, padding:'9px 12px', fontSize:13, color:'var(--fg)', outline:'none', fontFamily:'inherit', cursor:'pointer', appearance:'none', backgroundImage:`url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12' fill='none'%3E%3Cpath d='m2 4 4 4 4-4' stroke='%239EA4B0' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E")`, backgroundRepeat:'no-repeat', backgroundPosition:'right 10px center' },
  };

  const temps = [['hot','Quente','#ff5a4e'],['warm','Morno','#f5b544'],['cold','Frio','#59c8ff']];

  return (
    <div style={{ position:'fixed', inset:0, zIndex:2000, display:'flex', alignItems:'center', justifyContent:'center' }}>
      <div onClick={onClose} style={{ position:'absolute', inset:0, background:'rgba(0,0,0,0.6)', backdropFilter:'blur(6px)' }} />
      <div style={{ position:'relative', background:'var(--bg-2)', border:'1px solid var(--border)', borderRadius:20, width:500, maxWidth:'92vw', maxHeight:'92vh', overflowY:'auto', boxShadow:'0 24px 60px rgba(0,0,0,0.35)' }}>

        <div style={{ padding:'22px 24px 18px', borderBottom:'1px solid var(--line)' }}>
          <div style={{ display:'flex', alignItems:'center', gap:10 }}>
            <div style={{ width:32, height:32, borderRadius:9, background:'#1F93FF', display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0 }}>
              <svg width="14" height="14" viewBox="0 0 14 14" fill="none"><path d="M7 1v12M1 7h12" stroke="#fff" strokeWidth="2" strokeLinecap="round"/></svg>
            </div>
            <div>
              <div style={{ fontSize:15, fontWeight:700, color:'var(--fg)', lineHeight:1.2 }}>Novo Lead</div>
              <div style={{ fontSize:11, color:'var(--fg-3)', marginTop:2 }}>Preencha os dados do lead</div>
            </div>
            <button onClick={onClose} style={{ marginLeft:'auto', background:'var(--bg-1)', border:'1px solid var(--border)', cursor:'pointer', color:'var(--fg-3)', width:30, height:30, borderRadius:8, display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0 }}>
              <svg width="14" height="14" viewBox="0 0 14 14" fill="none"><path d="m2 2 10 10M12 2 2 12" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/></svg>
            </button>
          </div>
        </div>

        <form onSubmit={handleSubmit} style={{ padding:'20px 24px 24px', display:'flex', flexDirection:'column', gap:18, background:'var(--bg-2)', borderRadius:'0 0 20px 20px' }}>
          <div>
            <label style={F.label}>Nome completo *</label>
            <input style={F.input} type="text" placeholder="Ex: Helena Duarte"
              value={form.name} onChange={e => set('name', e.target.value)} autoFocus />
          </div>

          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:12 }}>
            <div>
              <label style={F.label}>Telefone *</label>
              <input style={F.input} type="tel" placeholder="(11) 99999-9999"
                value={form.phone} onChange={e => set('phone', maskPhone(e.target.value))} />
            </div>
            <div>
              <label style={F.label}>E-mail <span style={{ fontWeight:400, color:'var(--fg-4)' }}>(opcional)</span></label>
              <input style={F.input} type="email" placeholder="nome@email.com"
                value={form.email} onChange={e => set('email', e.target.value)} />
            </div>
          </div>

          <div>
            <label style={F.label}>Temperatura</label>
            <div style={{ display:'flex', gap:8 }}>
              {temps.map(([v, label, color]) => (
                <button key={v} type="button" onClick={() => set('temp', v)} style={{
                  flex:1, padding:'10px 8px', borderRadius:10,
                  border: `1.5px solid ${form.temp === v ? color : 'var(--line-strong)'}`,
                  background: form.temp === v ? color + '18' : 'var(--bg-1)',
                  color: form.temp === v ? color : 'var(--fg-3)',
                  fontSize:12, fontWeight:600, cursor:'pointer', transition:'all .15s',
                  display:'flex', flexDirection:'column', alignItems:'center', gap:4,
                }}>
                  <Icon name={v === 'hot' ? 'flame' : v === 'warm' ? 'sun' : 'snow'} size={16} style={{ color: v === 'hot' ? '#ff5a4e' : v === 'warm' ? '#f5b544' : '#59c8ff' }} />
                  {label}
                </button>
              ))}
            </div>
          </div>

          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:12 }}>
            <div>
              <label style={F.label}>Região</label>
              <input style={F.input} type="text" placeholder="Ex: Vila Madalena, SP"
                value={form.cat} onChange={e => set('cat', e.target.value)} />
            </div>
            {pipes.pipelines.length > 0 && (
              <div>
                <label style={F.label}>Funil</label>
                <select style={F.select} value={pipe || ''} onChange={e => { setPipe(e.target.value || null); set('col', 'inbox'); }}>
                  <option value="">Automático (regras de entrada)</option>
                  {[{ id: 'main', name: pipes.mainName }, ...pipes.pipelines].map(p => <option key={p.id} value={p.id}>{p.name}</option>)}
                </select>
              </div>
            )}
            <div>
              <label style={F.label}>Etapa inicial</label>
              <select style={F.select} value={form.col} onChange={e => set('col', e.target.value)}>
                {kanbanCols.map(c => <option key={c.id} value={c.id}>{c.title}</option>)}
              </select>
            </div>
          </div>

          <div>
            <label style={F.label}>Origem do lead <span style={{ fontWeight:400, color:'var(--fg-4)' }}>(opcional)</span></label>
            <select style={F.select} value={form.origem} onChange={e => set('origem', e.target.value)}>
              <option value="">Selecionar origem...</option>
              {leadOriginOptions('').map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
            </select>
            {['campanha', 'lista', 'importacao', 'feirao', 'acao_rua'].includes(form.origem) && (
              <input style={{ ...F.input, marginTop:8 }} value={form.origemNome || ''} onChange={e => set('origemNome', e.target.value)}
                placeholder={form.origem === 'campanha' ? 'Nome da campanha' : form.origem === 'feirao' ? 'Nome do evento' : form.origem === 'acao_rua' ? 'Onde foi a ação (ex.: Praça Sete, panfletagem)' : 'Nome da lista ou quem mandou'} maxLength={120} />
            )}
          </div>

          {canDistribute && (
            <label style={{ display:'flex', alignItems:'flex-start', gap:10, padding:'10px 12px', borderRadius:8, cursor:'pointer',
              border:`1px solid ${distribute ? 'color-mix(in srgb, var(--accent) 40%, transparent)' : 'var(--line)'}`,
              background: distribute ? 'color-mix(in srgb, var(--accent) 7%, var(--card))' : 'var(--bg-1)' }}>
              <input type="checkbox" checked={distribute} onChange={e => setDistributeKeep(e.target.checked)} style={{ marginTop:2, accentColor:'var(--accent)' }} />
              <span>
                <span style={{ display:'block', fontSize:12.5, fontWeight:600, color:'var(--fg)' }}>Distribuir pela fila da equipe</span>
                <span style={{ display:'block', fontSize:11.5, color:'var(--fg-3)', marginTop:2 }}>O lead vai para o próximo da fila (ou para quem tem menos leads), com a origem e o seu nome no repasse.</span>
              </span>
            </label>
          )}

          {error && (
            <div style={{ background:'rgba(255,90,78,0.1)', border:'1px solid rgba(255,90,78,0.3)', borderRadius:8, padding:'8px 12px', fontSize:12, color:'#ff5a4e' }}>
              {error}
            </div>
          )}

          <div style={{ display:'flex', gap:8, justifyContent:'flex-end', paddingTop:4, borderTop:'1px solid var(--line)', marginTop:2 }}>
            <button type="button" onClick={onClose}
              style={{ background:'var(--bg-1)', border:'1.5px solid var(--border)', borderRadius:8, padding:'8px 16px', fontSize:13, fontWeight:500, color:'var(--fg)', cursor:'pointer' }}>
              Cancelar
            </button>
            <button type="submit" disabled={saving}
              style={{ background: saving ? '#4f52c8' : '#1F93FF', color:'#fff', border:'none', borderRadius:8, padding:'8px 20px', fontSize:13, fontWeight:600, cursor: saving ? 'not-allowed' : 'pointer', display:'flex', alignItems:'center', gap:6 }}>
              {saving ? (
                <>
                  <svg style={{ animation:'spin 1s linear infinite' }} width="13" height="13" viewBox="0 0 24 24" fill="none"><circle cx="12" cy="12" r="10" stroke="rgba(255,255,255,0.3)" strokeWidth="3"/><path d="M12 2a10 10 0 0 1 10 10" stroke="#fff" strokeWidth="3" strokeLinecap="round"/></svg>
                  Criando…
                </>
              ) : (
                <>
                  <svg width="11" height="11" viewBox="0 0 12 12" fill="none"><path d="M6 1v10M1 6h10" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/></svg>
                  Criar Lead
                </>
              )}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}

// Global wrapper — listens for 'horos:new-lead' event, dispatches 'horos:lead-created' on success
function GlobalNewLeadModal() {
  const [open, setOpen] = React.useState(false);

  React.useEffect(() => {
    const handler = () => setOpen(true);
    window.addEventListener('horos:new-lead', handler);
    return () => window.removeEventListener('horos:new-lead', handler);
  }, []);

  if (!open) return null;

  return (
    <NewLeadModal
      onClose={() => setOpen(false)}
      onCreated={(lead) => {
        window.dispatchEvent(new CustomEvent('horos:lead-created', { detail: lead }));
        setOpen(false);
      }}
    />
  );
}

// Mount into dedicated root div
const _nlmEl = document.getElementById('nlm-root');
if (_nlmEl) ReactDOM.createRoot(_nlmEl).render(<GlobalNewLeadModal />);

window.NewLeadModal = NewLeadModal;
