// Lead Modal — New / Edit with Checklist
const LeadModal = ({ lead, onClose, onSave }) => {
  const isNew = !lead.id;
  const [form, setForm] = React.useState({
    empresa: lead.empresa || '',
    contato: lead.contato || '',
    tel: lead.tel || '',
    email: lead.email || '',
    responsavel: lead.responsavel || RESPONSAVEIS[0],
    origem: lead.origem || ORIGENS[0],
    segmento: lead.segmento || SEGMENTOS[0],
    valor: lead.valor || '',
    stage: lead.stage || STAGES[0],
    entrada: lead.entrada || new Date().toISOString().split('T')[0],
    followup: lead.followup || '',
    notas: lead.notas || '',
    checklist: lead.checklist || CHECKLIST_ITEMS.map(c => ({ ...c, done: false })),
  });
  const [tab, setTab] = React.useState('info');

  const set = (k, v) => setForm(prev => ({ ...prev, [k]: v }));

  const toggleCheck = (id) => {
    setForm(prev => ({
      ...prev,
      checklist: prev.checklist.map(c => c.id === id ? { ...c, done: !c.done } : c),
    }));
  };

  const handleSave = () => {
    if (!form.empresa.trim()) return alert('Informe o nome da empresa.');
    onSave({ ...lead, ...form, valor: Number(form.valor) || 0, id: lead.id || Date.now() });
    onClose();
  };

  const checkDone = form.checklist.filter(c => c.done).length;
  const checkTotal = form.checklist.length;
  const pct = Math.round((checkDone / checkTotal) * 100);

  // Group checklist by stage
  const checkByStage = STAGES.map(s => ({
    stage: s,
    items: form.checklist.filter(c => c.stage === s),
  }));

  return (
    <div style={ms.overlay} onClick={e => e.target === e.currentTarget && onClose()}>
      <div style={ms.modal}>
        {/* Header */}
        <div style={ms.modalHeader}>
          <div>
            <div style={ms.modalTitle}>{isNew ? 'Novo Lead' : form.empresa || 'Lead'}</div>
            <div style={ms.modalSub}>{isNew ? 'Preencha os dados do novo lead' : `Editando · ${form.stage}`}</div>
          </div>
          <button style={ms.closeBtn} onClick={onClose}>✕</button>
        </div>

        {/* Tabs */}
        <div style={ms.tabs}>
          {[['info', 'Informações'], ['checklist', `Checklist (${checkDone}/${checkTotal})`]].map(([id, label]) => (
            <button key={id} onClick={() => setTab(id)}
              style={{ ...ms.tab, ...(tab === id ? ms.tabActive : {}) }}>{label}</button>
          ))}
          {/* Progress bar */}
          <div style={{ flex: 1 }} />
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginRight: 4 }}>
            <div style={ms.progressBg}>
              <div style={{ ...ms.progressFill, width: pct + '%', background: STAGE_COLORS[form.stage] }} />
            </div>
            <span style={{ fontSize: 11, color: '#4a4f6a' }}>{pct}%</span>
          </div>
        </div>

        <div style={ms.body}>
          {tab === 'info' && (
            <div style={ms.grid}>
              <div style={ms.fieldFull}>
                <label style={ms.label}>Empresa *</label>
                <input style={ms.input} value={form.empresa} onChange={e => set('empresa', e.target.value)} placeholder="Nome da empresa" />
              </div>
              <div style={ms.field}>
                <label style={ms.label}>Contato</label>
                <input style={ms.input} value={form.contato} onChange={e => set('contato', e.target.value)} placeholder="Nome do contato" />
              </div>
              <div style={ms.field}>
                <label style={ms.label}>Telefone / WhatsApp</label>
                <input style={ms.input} value={form.tel} onChange={e => set('tel', e.target.value)} placeholder="(11) 99999-0000" />
              </div>
              <div style={ms.field}>
                <label style={ms.label}>E-mail</label>
                <input style={ms.input} value={form.email} onChange={e => set('email', e.target.value)} placeholder="contato@empresa.com" />
              </div>
              <div style={ms.field}>
                <label style={ms.label}>Valor Estimado (R$)</label>
                <input style={ms.input} type="number" value={form.valor} onChange={e => set('valor', e.target.value)} placeholder="0" />
              </div>
              <div style={ms.field}>
                <label style={ms.label}>Etapa do Pipeline</label>
                <select style={ms.select} value={form.stage} onChange={e => set('stage', e.target.value)}>
                  {STAGES.map(s => <option key={s} value={s}>{s}</option>)}
                </select>
              </div>
              <div style={ms.field}>
                <label style={ms.label}>Responsável</label>
                <select style={ms.select} value={form.responsavel} onChange={e => set('responsavel', e.target.value)}>
                  {RESPONSAVEIS.map(r => <option key={r} value={r}>{r}</option>)}
                </select>
              </div>
              <div style={ms.field}>
                <label style={ms.label}>Origem</label>
                <select style={ms.select} value={form.origem} onChange={e => set('origem', e.target.value)}>
                  {ORIGENS.map(o => <option key={o} value={o}>{o}</option>)}
                </select>
              </div>
              <div style={ms.field}>
                <label style={ms.label}>Segmento</label>
                <select style={ms.select} value={form.segmento} onChange={e => set('segmento', e.target.value)}>
                  {SEGMENTOS.map(s => <option key={s} value={s}>{s}</option>)}
                </select>
              </div>
              <div style={ms.field}>
                <label style={ms.label}>Data de Entrada</label>
                <input style={ms.input} type="date" value={form.entrada} onChange={e => set('entrada', e.target.value)} />
              </div>
              <div style={ms.field}>
                <label style={ms.label}>Próximo Follow-up</label>
                <input style={ms.input} type="date" value={form.followup} onChange={e => set('followup', e.target.value)} />
              </div>
              <div style={ms.fieldFull}>
                <label style={ms.label}>Anotações</label>
                <textarea style={{ ...ms.input, height: 80, resize: 'vertical' }} value={form.notas} onChange={e => set('notas', e.target.value)} placeholder="Observações, histórico de contato..." />
              </div>
            </div>
          )}

          {tab === 'checklist' && (
            <div>
              <div style={ms.checkInfo}>
                Marque as etapas concluídas do processo comercial. O progresso reflete no pipeline.
              </div>
              {checkByStage.map(({ stage, items }) => (
                <div key={stage} style={ms.checkGroup}>
                  <div style={ms.checkGroupHeader}>
                    <div style={{ width: 8, height: 8, borderRadius: '50%', background: STAGE_COLORS[stage] }} />
                    <span style={{ color: STAGE_COLORS[stage], fontWeight: 700, fontSize: 11, letterSpacing: 0.5 }}>{stage}</span>
                    <span style={{ color: '#2a2d3e', fontSize: 10 }}>({items.filter(i => i.done).length}/{items.length})</span>
                  </div>
                  {items.map(item => (
                    <label key={item.id} style={{ ...ms.checkItem, ...(item.done ? ms.checkItemDone : {}) }}>
                      <div style={{ ...ms.checkbox, ...(item.done ? ms.checkboxDone : {}) }}
                        onClick={() => toggleCheck(item.id)}>
                        {item.done && <span style={{ fontSize: 10, color: '#0d1020', fontWeight: 900 }}>✓</span>}
                      </div>
                      <span style={{ fontSize: 13, flex: 1 }}>{item.label}</span>
                    </label>
                  ))}
                </div>
              ))}
            </div>
          )}
        </div>

        {/* Footer */}
        <div style={ms.footer}>
          <button style={ms.cancelBtn} onClick={onClose}>Cancelar</button>
          <button style={ms.saveBtn} onClick={handleSave}>{isNew ? 'Criar Lead' : 'Salvar Alterações'}</button>
        </div>
      </div>
    </div>
  );
};

const ms = {
  overlay: {
    position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.7)', display: 'flex',
    alignItems: 'center', justifyContent: 'center', zIndex: 1000, backdropFilter: 'blur(4px)',
  },
  modal: {
    background: '#151828', border: '1px solid #1e2235', borderRadius: 14,
    width: '95%', maxWidth: 680, maxHeight: '90vh', display: 'flex', flexDirection: 'column',
    boxShadow: '0 24px 60px rgba(0,0,0,0.6)',
  },
  modalHeader: {
    display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start',
    padding: '20px 24px 0',
  },
  modalTitle: { fontSize: 18, fontWeight: 700, color: '#e8eaf0' },
  modalSub: { fontSize: 12, color: '#4a4f6a', marginTop: 3 },
  closeBtn: {
    background: 'none', border: 'none', color: '#4a4f6a', fontSize: 18,
    cursor: 'pointer', padding: '0 4px', lineHeight: 1,
  },
  tabs: { display: 'flex', gap: 0, padding: '14px 24px 0', borderBottom: '1px solid #1e2235', alignItems: 'center' },
  tab: {
    background: 'none', border: 'none', color: '#4a4f6a', fontSize: 13, fontWeight: 600,
    padding: '8px 14px', cursor: 'pointer', borderBottom: '2px solid transparent', marginBottom: -1,
  },
  tabActive: { color: '#4f7cff', borderBottomColor: '#4f7cff' },
  progressBg: { width: 80, height: 5, background: '#1e2235', borderRadius: 3, overflow: 'hidden' },
  progressFill: { height: '100%', borderRadius: 3, transition: 'width 0.3s' },
  body: { flex: 1, overflowY: 'auto', padding: '18px 24px' },
  grid: { display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '14px 18px' },
  field: {},
  fieldFull: { gridColumn: '1 / -1' },
  label: { display: 'block', fontSize: 10, color: '#4a4f6a', fontWeight: 700, letterSpacing: 0.8, marginBottom: 5, textTransform: 'uppercase' },
  input: {
    width: '100%', background: '#1a1d2e', border: '1px solid #1e2235', borderRadius: 8,
    padding: '9px 12px', fontSize: 13, color: '#c7d2ff', outline: 'none', boxSizing: 'border-box',
    fontFamily: 'inherit',
  },
  select: {
    width: '100%', background: '#1a1d2e', border: '1px solid #1e2235', borderRadius: 8,
    padding: '9px 12px', fontSize: 13, color: '#c7d2ff', outline: 'none', boxSizing: 'border-box',
    fontFamily: 'inherit', cursor: 'pointer',
  },
  checkInfo: { fontSize: 12, color: '#4a4f6a', marginBottom: 16, lineHeight: 1.5 },
  checkGroup: { marginBottom: 18 },
  checkGroupHeader: { display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 },
  checkItem: {
    display: 'flex', alignItems: 'center', gap: 10, padding: '8px 10px',
    borderRadius: 8, cursor: 'pointer', marginBottom: 2, color: '#c7d2ff',
    transition: 'background 0.1s',
  },
  checkItemDone: { color: '#4a4f6a' },
  checkbox: {
    width: 18, height: 18, borderRadius: 5, border: '2px solid #2a2d3e',
    display: 'flex', alignItems: 'center', justifyContent: 'center',
    cursor: 'pointer', flexShrink: 0, transition: 'all 0.15s',
  },
  checkboxDone: { background: '#4ade80', borderColor: '#4ade80' },
  footer: {
    display: 'flex', justifyContent: 'flex-end', gap: 10, padding: '14px 24px',
    borderTop: '1px solid #1e2235',
  },
  cancelBtn: {
    background: 'none', border: '1px solid #1e2235', borderRadius: 8,
    padding: '9px 20px', fontSize: 13, color: '#6b7194', cursor: 'pointer',
  },
  saveBtn: {
    background: '#4f7cff', border: 'none', borderRadius: 8,
    padding: '9px 22px', fontSize: 13, fontWeight: 700, color: '#fff', cursor: 'pointer',
  },
};

Object.assign(window, { LeadModal });
