/* ============================================================
   KeS Metas — CRM (Funil de Vendas / Kanban)
   ============================================================ */
const { useState, useRef } = React;

const ORIGENS = ["Instagram", "LinkedIn", "WhatsApp", "Indicação", "Site", "Outbound", "Evento", "Outro"];

// Ordem das colunas no CSV de import/export (modelo da planilha).
const CSV_COLS = ["nome", "empresa", "socios", "porte", "telefone", "telefone2", "telefone3", "email", "endereco", "instagram", "linkedin", "google", "origem", "valor", "responsavel", "tags", "observacoes", "etapa"];
function csvExampleRows(viewer, stages) {
  return [
    { nome: "Maria Souza", empresa: "Loja Exemplo", socios: "Carlos Andrade; Marina Costa", porte: "Pequena", telefone: "(54) 9 9999-0000", telefone2: "(54) 3221-0000", telefone3: "", email: "maria@exemplo.com.br", endereco: "Av. Brasil, 1200 — Caxias do Sul/RS", instagram: "@lojaexemplo", linkedin: "linkedin.com/company/lojaexemplo", google: "g.page/lojaexemplo", origem: "Instagram", valor: "8500", responsavel: viewer.email, tags: "Quente;Inbound", observacoes: "Pediu proposta", etapa: stages[0].nome },
    { nome: "João Lima", empresa: "Empresa XYZ", socios: "Roberto Lima", porte: "Média", telefone: "(54) 9 8888-1111", telefone2: "", telefone3: "", email: "joao@xyz.com.br", endereco: "Rua Os Dezoito do Forte, 800 — Bento Gonçalves/RS", instagram: "@empresaxyz", linkedin: "linkedin.com/company/xyz", google: "xyz.com.br", origem: "Indicação", valor: "15000", responsavel: viewer.email, tags: "Morno", observacoes: "", etapa: stages[1] ? stages[1].nome : stages[0].nome },
  ];
}

function tagClass(t) {
  const k = t.toLowerCase();
  if (k === "quente") return "tag t-quente";
  if (k === "morno") return "tag t-morno";
  if (k === "frio") return "tag t-frio";
  return "tag";
}
function stageColor(tipo) { return tipo === "won" ? "var(--ok)" : tipo === "lost" ? "var(--kes-red)" : "var(--info)"; }
function parseMoney(s) {
  if (typeof s === "number") return s;
  const n = String(s).replace(/[^\d,.-]/g, "").replace(/\.(?=\d{3}(\D|$))/g, "").replace(",", ".");
  return Math.max(0, Math.round(parseFloat(n) || 0));
}

/* ---------------- Card de lead ---------------- */
function LeadCard({ lead, user, onOpen, onAgendar, onDragStart, onDragEnd, dragging }) {
  const K = window.KES;
  return (
    <div className={"kcard" + (dragging ? " dragging" : "")} draggable
      onDragStart={(e) => onDragStart(e, lead)} onDragEnd={onDragEnd} onClick={onOpen}>
      <div className="kc-top">
        <div style={{ minWidth: 0 }}>
          <div className="kc-nm">{lead.nome}</div>
          <div className="kc-emp">{lead.empresa}</div>
        </div>
        <div className="kc-val">{lead.valor ? K.fmtMoeda(lead.valor) : "—"}</div>
      </div>
      {lead.tags && lead.tags.length > 0 && (
        <div className="kc-tags">{lead.tags.map((t) => <span key={t} className={tagClass(t)}>{t}</span>)}</div>
      )}
      <div className="kc-foot">
        <span className="origem"><Icon name="funnel" size={12} />{lead.origem}{lead.porte ? ` · ${lead.porte}` : ""}</span>
        <div className="kc-actions" onClick={(e) => e.stopPropagation()}>
          <button title="Agendar reunião" onClick={onAgendar}><Icon name="calendar" size={14} /></button>
          {user && <span title={user.nome} style={{ marginLeft: 2 }}><Avatar user={user} size={26} /></span>}
        </div>
      </div>
    </div>
  );
}

/* ---------------- Coluna do funil ---------------- */
function KanbanColumn({ stage, leads, usersById, onDropLead, onOpen, onAgendar, drag }) {
  const K = window.KES;
  const [over, setOver] = useState(false);
  const total = leads.reduce((t, l) => t + (l.valor || 0), 0);
  return (
    <div className={"kcol" + (over ? " dragover" : "")}
      onDragOver={(e) => { e.preventDefault(); setOver(true); }}
      onDragLeave={() => setOver(false)}
      onDrop={(e) => { e.preventDefault(); setOver(false); onDropLead(stage.id); }}>
      <div className="kcol-head">
        <div className="kh-top">
          <span className="dot" style={{ background: stageColor(stage.tipo) }} />
          <span className="knm">{stage.nome}</span>
          <span className="kct">{leads.length}</span>
        </div>
        <div className="kval">{K.fmtMoeda(total)}</div>
      </div>
      <div className="kcol-body">
        {leads.length === 0 ? (
          <div className="kcol-empty">Arraste leads para cá</div>
        ) : leads.map((l) => (
          <LeadCard key={l.id} lead={l} user={usersById[l.responsavelId]}
            dragging={drag.id === l.id}
            onOpen={() => onOpen(l)} onAgendar={() => onAgendar(l)}
            onDragStart={drag.start} onDragEnd={drag.end} />
        ))}
      </div>
    </div>
  );
}

/* ---------------- Modal de lead (cadastro completo) ---------------- */
function LeadModal({ initial, stages, users, viewer, onClose, onSave, onDelete, onAgendar }) {
  const editing = !!(initial && initial.id);
  const isAdmin = viewer.papel === "admin";
  const [f, setF] = useState(initial || {
    nome: "", empresa: "", telefone: "", telefone2: "", telefone3: "", email: "", socios: "",
    instagram: "", google: "", linkedin: "", porte: "", endereco: "",
    origem: "Instagram", valor: "", responsavelId: viewer.id, tags: [], observacoes: "", stageId: stages[0].id,
  });
  const [tagInput, setTagInput] = useState("");
  const [err, setErr] = useState("");
  const set = (k, v) => setF((s) => ({ ...s, [k]: v }));
  function addTag(v) { const t = v.trim(); if (t && !f.tags.includes(t)) set("tags", [...f.tags, t]); setTagInput(""); }
  function save() {
    if (!f.nome.trim()) return setErr("Informe o nome do contato.");
    onSave({ ...f, valor: parseMoney(f.valor) });
  }
  return (
    <Modal title={editing ? "Editar lead" : "Novo lead"} onClose={onClose} wide
      footer={
        <>
          {editing && onDelete && <Btn variant="danger" icon="trash" onClick={onDelete} style={{ marginRight: "auto" }}>Excluir</Btn>}
          <Btn variant="ghost" onClick={onClose}>Cancelar</Btn>
          <Btn variant="primary" icon="check" onClick={save}>{editing ? "Salvar" : "Cadastrar"}</Btn>
        </>
      }>
      <div className="form-row">
        <Field label="Nome do contato"><input className="field" value={f.nome} onChange={(e) => set("nome", e.target.value)} placeholder="Nome e sobrenome" /></Field>
        <Field label="Empresa"><input className="field" value={f.empresa} onChange={(e) => set("empresa", e.target.value)} placeholder="Empresa" /></Field>
      </div>
      <div className="form-row">
        <Field label="Sócios"><input className="field" value={f.socios} onChange={(e) => set("socios", e.target.value)} placeholder="Nomes dos sócios (separe por vírgula)" /></Field>
        <Field label="Porte da empresa">
          <select className="field" value={f.porte} onChange={(e) => set("porte", e.target.value)}>
            <option value="">Selecione…</option>
            {["MEI", "Microempresa", "Pequena", "Média", "Grande"].map((p) => <option key={p} value={p}>{p}</option>)}
          </select>
        </Field>
      </div>
      <div className="section-label" style={{ margin: "4px 0 0" }}><span className="eyebrow">Contato</span><span className="rule" /></div>
      <div className="form-row">
        <Field label="Telefone 1 / WhatsApp"><input className="field" value={f.telefone} onChange={(e) => set("telefone", e.target.value)} placeholder="(54) 9 9999-9999" /></Field>
        <Field label="Telefone 2"><input className="field" value={f.telefone2} onChange={(e) => set("telefone2", e.target.value)} placeholder="(54) 9 9999-9999" /></Field>
      </div>
      <div className="form-row">
        <Field label="Telefone 3"><input className="field" value={f.telefone3} onChange={(e) => set("telefone3", e.target.value)} placeholder="(54) 9 9999-9999" /></Field>
        <Field label="E-mail"><input className="field" type="email" value={f.email} onChange={(e) => set("email", e.target.value)} placeholder="contato@empresa.com.br" /></Field>
      </div>
      <Field label="Endereço"><input className="field" value={f.endereco} onChange={(e) => set("endereco", e.target.value)} placeholder="Rua, número — Cidade/UF" /></Field>
      <div className="section-label" style={{ margin: "4px 0 0" }}><span className="eyebrow">Presença digital</span><span className="rule" /></div>
      <div className="form-row">
        <Field label="Instagram"><input className="field" value={f.instagram} onChange={(e) => set("instagram", e.target.value)} placeholder="@perfil" /></Field>
        <Field label="LinkedIn"><input className="field" value={f.linkedin} onChange={(e) => set("linkedin", e.target.value)} placeholder="linkedin.com/company/…" /></Field>
      </div>
      <Field label="Google (perfil / site)"><input className="field" value={f.google} onChange={(e) => set("google", e.target.value)} placeholder="g.page/… ou site da empresa" /></Field>
      <div className="section-label" style={{ margin: "4px 0 0" }}><span className="eyebrow">Negócio</span><span className="rule" /></div>
      <div className="form-row">
        <Field label="Origem">
          <select className="field" value={f.origem} onChange={(e) => set("origem", e.target.value)}>
            {ORIGENS.map((o) => <option key={o} value={o}>{o}</option>)}
          </select>
        </Field>
        <Field label="Valor potencial (R$)"><input className="field" type="number" min="0" value={f.valor} onChange={(e) => set("valor", e.target.value)} placeholder="0" /></Field>
      </div>
      <div className="form-row">
        <Field label="Etapa do funil">
          <select className="field" value={f.stageId} onChange={(e) => set("stageId", e.target.value)}>
            {stages.map((s) => <option key={s.id} value={s.id}>{s.nome}</option>)}
          </select>
        </Field>
        <Field label="Responsável">
          <select className="field" value={f.responsavelId} disabled={!isAdmin} onChange={(e) => set("responsavelId", e.target.value)}>
            {users.map((u) => <option key={u.id} value={u.id}>{u.nome}{u.id === viewer.id ? " (você)" : ""}</option>)}
          </select>
        </Field>
      </div>
      <Field label="Tags / etiquetas">
        <div className="tagedit">
          {f.tags.map((t) => (
            <span key={t} className="tg">{t}<button onClick={() => set("tags", f.tags.filter((x) => x !== t))}><Icon name="x" size={13} /></button></span>
          ))}
          <input className="field" style={{ width: 150, flex: 1, minWidth: 120 }} value={tagInput}
            placeholder="Digite e Enter"
            onChange={(e) => setTagInput(e.target.value)}
            onKeyDown={(e) => { if (e.key === "Enter" || e.key === ",") { e.preventDefault(); addTag(tagInput); } }} />
        </div>
      </Field>
      <Field label="Observações / histórico" error={err || null}>
        <textarea className="field" value={f.observacoes} onChange={(e) => set("observacoes", e.target.value)} placeholder="Anotações, próximos passos, histórico de contato…" />
      </Field>
      {editing && (
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12, padding: "12px 14px", background: "var(--kes-navy-700)", borderRadius: "var(--radius-md)" }}>
          <div style={{ fontSize: 12.5, color: "var(--fg2)", display: "flex", alignItems: "center", gap: 8 }}>
            <Icon name="calendarCheck" size={16} /> Agende uma reunião com este lead e conte em "Reuniões Agendadas".
          </div>
          <Btn variant="subtle" size="sm" icon="calendar" onClick={() => onAgendar(f)}>Agendar reunião</Btn>
        </div>
      )}
    </Modal>
  );
}

/* ---------------- Modal de importação CSV ---------------- */
const HEADER_MAP = {
  nome: ["nome", "contato", "nome do contato", "lead", "name"],
  empresa: ["empresa", "company", "cliente"],
  telefone: ["telefone", "telefone1", "telefone 1", "whatsapp", "telefone / whatsapp", "fone", "celular", "phone"],
  telefone2: ["telefone2", "telefone 2", "telefone secundario", "fone2"],
  telefone3: ["telefone3", "telefone 3", "fone3"],
  email: ["email", "e-mail", "mail"],
  socios: ["socios", "socio", "nomes dos socios", "partners"],
  instagram: ["instagram", "insta", "ig"],
  google: ["google", "google business", "site", "website", "g.page"],
  linkedin: ["linkedin", "linked in"],
  porte: ["porte", "porte da empresa", "tamanho", "size"],
  endereco: ["endereco", "endereço", "address", "localizacao"],
  origem: ["origem", "fonte", "source", "canal"],
  valor: ["valor", "valor potencial", "valor potencial (r$)", "valor (r$)", "valor potencial r$", "value"],
  responsavel: ["responsavel", "responsavel email", "email responsavel", "responsavel (email)", "owner", "dono"],
  tags: ["tags", "etiquetas", "labels"],
  observacoes: ["observacoes", "observacoes / historico", "notas", "obs", "historico", "notes"],
  etapa: ["etapa", "stage", "funil", "status", "fase"],
};
function normKey(h) { return String(h).toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g, "").trim(); }
function buildColIndex(headers) {
  const idx = {};
  headers.forEach((h) => {
    const n = normKey(h);
    for (const field in HEADER_MAP) if (HEADER_MAP[field].includes(n)) idx[field] = h;
  });
  return idx;
}
function ImportModal({ stages, users, viewer, onClose, onImport }) {
  const K = window.KES;
  const isAdmin = viewer.papel === "admin";
  const fileRef = useRef(null);
  const [parsed, setParsed] = useState(null); // {headers, rows, idx, leads}
  const [assignTo, setAssignTo] = useState("csv"); // 'csv' = conforme planilha | userId
  const [erro, setErro] = useState("");

  const applyAssign = (leads) => assignTo === "csv" ? leads : leads.map((l) => ({ ...l, responsavelId: assignTo }));

  function handleText(text) {
    try {
      const { headers, rows } = window.CSVUtil.parse(text);
      if (!rows.length) { setErro("Nenhuma linha encontrada no arquivo."); return; }
      const idx = buildColIndex(headers);
      if (!idx.nome) { setErro("Coluna obrigatória 'nome' não encontrada no cabeçalho."); return; }
      const stageByName = {}; stages.forEach((s) => { stageByName[normKey(s.nome)] = s.id; });
      const userByEmail = {}; users.forEach((u) => { userByEmail[u.email.toLowerCase()] = u.id; });
      const leads = rows.map((r, i) => {
        const g = (field) => (idx[field] ? r[idx[field]] : "");
        const respEmail = (g("responsavel") || "").toLowerCase();
        const stg = stageByName[normKey(g("etapa") || "")] || stages[0].id;
        const tags = (g("tags") || "").split(/[;,/]/).map((t) => t.trim()).filter(Boolean);
        return {
          id: "l" + Date.now() + "_" + i,
          nome: g("nome"), empresa: g("empresa"),
          telefone: g("telefone"), telefone2: g("telefone2"), telefone3: g("telefone3"),
          email: g("email"), socios: g("socios"),
          instagram: g("instagram"), google: g("google"), linkedin: g("linkedin"),
          porte: g("porte"), endereco: g("endereco"),
          origem: g("origem") || "Outro", valor: parseMoney(g("valor")),
          responsavelId: userByEmail[respEmail] || viewer.id,
          tags, observacoes: g("observacoes"), stageId: stg, createdAt: K.iso(K.SIM_TODAY),
        };
      }).filter((l) => l.nome);
      setErro(""); setParsed({ headers, count: leads.length, leads, idx });
    } catch (e) { setErro("Não foi possível ler o arquivo. Verifique o formato CSV."); }
  }
  function onFile(e) {
    const file = e.target.files[0]; if (!file) return;
    const reader = new FileReader();
    reader.onload = () => handleText(reader.result);
    reader.readAsText(file, "UTF-8");
  }
  function baixarModelo() {
    const rows = csvExampleRows(viewer, stages).map((r) => CSV_COLS.map((c) => r[c]));
    window.CSVUtil.download("modelo-leads-kes.csv", window.CSVUtil.serialize(CSV_COLS, rows, ";"));
  }
  return (
    <Modal title="Importar leads (CSV)" onClose={onClose} wide
      footer={
        <>
          <Btn variant="ghost" onClick={onClose}>Cancelar</Btn>
          <Btn variant="primary" icon="upload" disabled={!parsed || !parsed.count} onClick={() => onImport(applyAssign(parsed.leads))}>
            {parsed ? `Importar ${parsed.count} leads` : "Importar"}
          </Btn>
        </>
      }>
      {/* Modelo visual da planilha */}
      <div>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 10, marginBottom: 9, flexWrap: "wrap" }}>
          <div className="eyebrow" style={{ margin: 0 }}>Modelo da planilha</div>
          <Btn variant="subtle" size="sm" icon="download" onClick={baixarModelo}>Baixar modelo (.csv)</Btn>
        </div>
        <div style={{ overflowX: "auto", border: "1px solid var(--border-dark)", borderRadius: "var(--radius-md)" }}>
          <table className="model-tbl">
            <thead>
              <tr>{CSV_COLS.map((h) => <th key={h}>{h}</th>)}</tr>
            </thead>
            <tbody>
              {csvExampleRows(viewer, stages).map((r, i) => (
                <tr key={i}>{CSV_COLS.map((c) => <td key={c}>{r[c] || "—"}</td>)}</tr>
              ))}
            </tbody>
          </table>
        </div>
        <p className="muted" style={{ fontSize: 11.5, margin: "8px 0 0" }}>
          A 1ª linha deve ser o cabeçalho com esses nomes de coluna. Só <strong>nome</strong> é obrigatório. Separe <strong>tags</strong> e <strong>sócios</strong> por ponto-e-vírgula (;). Aceita separador "," ou ";".
        </p>
      </div>

      <div className="dropzone" onClick={() => fileRef.current.click()}>
        <Icon name="spreadsheet" size={34} />
        <div style={{ fontWeight: 700, fontSize: 14 }}>Selecione um arquivo .CSV</div>
        <div className="muted" style={{ fontSize: 12.5, marginTop: 4 }}>Exportado do Excel ou Google Sheets</div>
        <input ref={fileRef} type="file" accept=".csv,text/csv" style={{ display: "none" }} onChange={onFile} />
      </div>

      {/* Atribuição individual (admin) */}
      {isAdmin && (
        <Field label="Atribuir os leads importados a">
          <select className="field" value={assignTo} onChange={(e) => setAssignTo(e.target.value)}>
            <option value="csv">Conforme a coluna "responsavel" da planilha</option>
            {users.map((u) => <option key={u.id} value={u.id}>{u.nome}{u.id === viewer.id ? " (você)" : ""} — todos para esta pessoa</option>)}
          </select>
        </Field>
      )}

      {erro && <div className="form-err"><Icon name="alert" size={14} />{erro}</div>}
      {parsed && (
        <div className="card" style={{ background: "var(--kes-navy-700)", padding: 14 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 9, fontWeight: 700, fontSize: 13.5 }}>
            <span style={{ color: "var(--ok)", display: "grid", placeItems: "center" }}><Icon name="checkCircle" size={18} /></span>
            {parsed.count} leads prontos para importar
          </div>
          <div className="muted" style={{ fontSize: 12, marginTop: 8 }}>
            Colunas reconhecidas: {Object.keys(parsed.idx).join(", ") || "—"}
            {isAdmin && assignTo !== "csv" && <> · todos serão atribuídos a <strong style={{ color: "var(--fg2)" }}>{(users.find((u) => u.id === assignTo) || {}).nome}</strong></>}
          </div>
        </div>
      )}
    </Modal>
  );
}

/* ---------------- Modal: configurar etapas ---------------- */
function StagesModal({ stages, onClose, onSave }) {
  const [list, setList] = useState(() => stages.map((s) => ({ ...s })));
  const [novo, setNovo] = useState("");
  function rename(i, v) { setList((l) => l.map((s, j) => j === i ? { ...s, nome: v } : s)); }
  function move(i, dir) {
    const j = i + dir; if (j < 0 || j >= list.length) return;
    const l = list.slice(); const t = l[i]; l[i] = l[j]; l[j] = t; setList(l);
  }
  function remove(i) { if (list.length <= 2) return; setList((l) => l.filter((_, j) => j !== i)); }
  function add() {
    const n = novo.trim(); if (!n) return;
    setList((l) => [...l, { id: "s" + Date.now(), nome: n, tipo: "open" }]); setNovo("");
  }
  return (
    <Modal title="Configurar etapas do funil" onClose={onClose}
      footer={<><Btn variant="ghost" onClick={onClose}>Cancelar</Btn><Btn variant="primary" icon="check" onClick={() => onSave(list)}>Salvar etapas</Btn></>}>
      <div>
        {list.map((s, i) => (
          <div key={s.id} className="stage-row">
            <span className="dot" style={{ width: 9, height: 9, borderRadius: "50%", background: stageColor(s.tipo) }} />
            <input className="field" value={s.nome} onChange={(e) => rename(i, e.target.value)} style={{ flex: 1 }} />
            <div className="ord">
              <button onClick={() => move(i, -1)} disabled={i === 0} title="Subir"><Icon name="chevronLeft" size={15} style={{ transform: "rotate(90deg)" }} /></button>
              <button onClick={() => move(i, 1)} disabled={i === list.length - 1} title="Descer"><Icon name="chevronRight" size={15} style={{ transform: "rotate(90deg)" }} /></button>
              <button onClick={() => remove(i)} disabled={list.length <= 2} title="Remover" style={{ color: "var(--kes-red-400)" }}><Icon name="trash" size={15} /></button>
            </div>
          </div>
        ))}
      </div>
      <div style={{ display: "flex", gap: 9 }}>
        <input className="field" placeholder="Nova etapa…" value={novo}
          onChange={(e) => setNovo(e.target.value)} onKeyDown={(e) => { if (e.key === "Enter") { e.preventDefault(); add(); } }} />
        <Btn variant="subtle" icon="plus" onClick={add}>Adicionar</Btn>
      </div>
      <p className="muted" style={{ fontSize: 11.5, margin: 0 }}>Ao remover uma etapa, os leads dela vão para a primeira etapa.</p>
    </Modal>
  );
}

/* ---------------- Tela CRM ---------------- */
function CRMScreen({ state, dispatch, viewer }) {
  const K = window.KES;
  const isAdmin = viewer.papel === "admin";
  const usersById = {}; state.users.forEach((u) => { usersById[u.id] = u; });

  const [modal, setModal] = useState(null);   // lead em edição/criação
  const [importing, setImporting] = useState(false);
  const [stagesCfg, setStagesCfg] = useState(false);
  const [q, setQ] = useState("");
  const [fResp, setFResp] = useState("all");
  const [fOrig, setFOrig] = useState("all");
  const dragId = useRef(null);
  const [, force] = useState(0);

  // leads visíveis conforme permissão + filtros
  let leads = state.leads.filter((l) => isAdmin || l.responsavelId === viewer.id);
  if (isAdmin && fResp !== "all") leads = leads.filter((l) => l.responsavelId === fResp);
  if (fOrig !== "all") leads = leads.filter((l) => l.origem === fOrig);
  if (q.trim()) {
    const s = q.toLowerCase();
    leads = leads.filter((l) => (l.nome + " " + l.empresa + " " + l.email).toLowerCase().includes(s));
  }

  const totalValor = leads.reduce((t, l) => t + (l.valor || 0), 0);

  const drag = {
    id: dragId.current,
    start: (e, lead) => { dragId.current = lead.id; e.dataTransfer.effectAllowed = "move"; force((n) => n + 1); },
    end: () => { dragId.current = null; force((n) => n + 1); },
  };
  function dropOn(stageId) {
    if (dragId.current) { dispatch({ type: "MOVE_LEAD", id: dragId.current, stageId }); dragId.current = null; force((n) => n + 1); }
  }
  function agendar(lead) { dispatch({ type: "AGENDAR_LEAD", lead }); }

  function saveLead(data) {
    if (modal && modal.id) dispatch({ type: "UPDATE_LEAD", id: modal.id, patch: data });
    else dispatch({ type: "ADD_LEAD", lead: data });
    dispatch({ type: "TOAST", msg: modal && modal.id ? "Lead atualizado." : "Lead cadastrado." });
    setModal(null);
  }
  function exportar() {
    const stageById = {}; state.stages.forEach((s) => { stageById[s.id] = s.nome; });
    const val = (l, c) => {
      if (c === "responsavel") return (usersById[l.responsavelId] || {}).email || "";
      if (c === "tags") return (l.tags || []).join(";");
      if (c === "etapa") return stageById[l.stageId] || "";
      return l[c] != null ? l[c] : "";
    };
    const rows = leads.map((l) => CSV_COLS.map((c) => val(l, c)));
    window.CSVUtil.download("leads-kes.csv", window.CSVUtil.serialize(CSV_COLS, rows, ";"));
    dispatch({ type: "TOAST", msg: `${rows.length} leads exportados (CSV).` });
  }

  return (
    <div className="content">
      <div className="topbar">
        <div className="ttl">
          <h1>CRM — Funil de Vendas</h1>
          <p>{leads.length} leads · {K.fmtMoeda(totalValor)} em oportunidades{isAdmin ? "" : " · seus leads"}</p>
        </div>
        <div className="actions">
          <Btn variant="subtle" size="sm" icon="upload" onClick={() => setImporting(true)}>Importar</Btn>
          <Btn variant="subtle" size="sm" icon="download" onClick={exportar}>Exportar</Btn>
          {isAdmin && <Btn variant="subtle" size="sm" icon="sliders" onClick={() => setStagesCfg(true)}>Etapas</Btn>}
          <Btn variant="primary" size="sm" icon="plus" onClick={() => setModal({})}>Novo lead</Btn>
        </div>
      </div>

      <div className="crm-toolbar">
        <div className="search-box">
          <Icon name="search" />
          <input className="field" placeholder="Buscar por nome, empresa ou e-mail…" value={q} onChange={(e) => setQ(e.target.value)} />
        </div>
        {isAdmin && (
          <select className="field" value={fResp} onChange={(e) => setFResp(e.target.value)}>
            <option value="all">Todos os responsáveis</option>
            {state.users.map((u) => <option key={u.id} value={u.id}>{u.nome}</option>)}
          </select>
        )}
        <select className="field" value={fOrig} onChange={(e) => setFOrig(e.target.value)}>
          <option value="all">Todas as origens</option>
          {ORIGENS.map((o) => <option key={o} value={o}>{o}</option>)}
        </select>
      </div>

      <div className="kanban">
        {state.stages.map((stage) => (
          <KanbanColumn key={stage.id} stage={stage}
            leads={leads.filter((l) => l.stageId === stage.id)}
            usersById={usersById} drag={drag}
            onDropLead={dropOn} onOpen={(l) => setModal(l)} onAgendar={agendar} />
        ))}
      </div>

      {modal && (
        <LeadModal initial={modal.id ? modal : null} stages={state.stages} users={state.users} viewer={viewer}
          onClose={() => setModal(null)} onSave={saveLead} onAgendar={(l) => { setModal(null); agendar(l); }}
          onDelete={modal.id ? () => { dispatch({ type: "DELETE_LEAD", id: modal.id }); dispatch({ type: "TOAST", msg: "Lead excluído." }); setModal(null); } : null} />
      )}
      {importing && (
        <ImportModal stages={state.stages} users={state.users} viewer={viewer}
          onClose={() => setImporting(false)}
          onImport={(leads) => { dispatch({ type: "IMPORT_LEADS", leads }); dispatch({ type: "TOAST", msg: `${leads.length} leads importados.` }); setImporting(false); }} />
      )}
      {stagesCfg && (
        <StagesModal stages={state.stages} onClose={() => setStagesCfg(false)}
          onSave={(list) => { dispatch({ type: "SET_STAGES", stages: list }); dispatch({ type: "TOAST", msg: "Etapas atualizadas." }); setStagesCfg(false); }} />
      )}
    </div>
  );
}

window.CRMScreen = CRMScreen;
