/* FrontCall Hub — Clientes: FUNIL (negociação) e CARTEIRA (relacionamento),
   duas visões de primeiro nível, cada uma com sua própria cara:
   · Funil — pipeline por etapa, cotação, qualidade e PRÓXIMO PASSO de cada lead
   · Carteira — clientes com LTV, recorrência, último job e inativos */

const clientByCall = (callId) => D.clients.find((c) => c.callId === callId);

const FUNNEL_STAGES = [
  { value: "new", label: "Novo" },
  { value: "contacted", label: "Em contato" },
  { value: "scheduled", label: "Visita marcada" },
  { value: "proposal", label: "Proposta" },
];
const funnelStageLabel = (v) => (FUNNEL_STAGES.find((s) => s.value === v) || {}).label || v;

function relationBadge(c) {
  if (c.relation === "ativo") return <Badge tone="success" dot>Cliente ativo</Badge>;
  if (c.relation === "inativo") return <Badge tone="neutral">Inativo</Badge>;
  return <Badge tone="info" dot>No funil</Badge>;
}
function typeBadge(c) {
  if (c.type === "recorrente") return <Badge tone="brand">Recorrente · {c.freq}</Badge>;
  if (c.type === "avulso") return <Badge tone="neutral">Avulso</Badge>;
  return null;
}

/* ---- busca (escala: listas grandes) ---- */
const matchQ = (c, q) => !q || (c.name + " " + (c.phone || "") + " " + (c.address || "")).toLowerCase().includes(q.toLowerCase());

function SearchBox({ q, setQ, placeholder }) {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 9, background: "var(--surface-card)", border: "1px solid var(--border-default)", borderRadius: "var(--radius-md)", padding: "0 12px", height: 42, marginBottom: 14 }}>
      <Icon name="search" size={16} color="var(--text-faint)" />
      <input value={q} onChange={(e) => setQ(e.target.value)} placeholder={placeholder}
        style={{ flex: 1, border: "none", outline: "none", background: "transparent", fontFamily: "var(--font-sans)", fontSize: "var(--fs-sm)", color: "var(--text-strong)", height: "100%", minWidth: 0 }} />
      {q && <button onClick={() => setQ("")} style={{ border: "none", background: "none", cursor: "pointer", display: "flex", padding: 2 }}><Icon name="x" size={14} color="var(--text-faint)" /></button>}
    </div>
  );
}

/* ================= FUNIL ================= */
function nextStep(c) {
  if (c.stage === "scheduled" && c.apptId) {
    const a = D.appointments.find((x) => x.id === c.apptId);
    return { icon: "calendar", color: "var(--brand)", text: a ? `Visita de orçamento · ${a.date} · ${a.time}` : "Visita marcada" };
  }
  if (c.stage === "proposal") return { icon: "clock", color: "var(--warm-600)", text: `Aguardando resposta · cotação ${money(c.price)}` };
  if (c.stage === "contacted") return { icon: "phone-outgoing", color: "var(--text-secondary)", text: "Retomar conversa" };
  return { icon: "zap", color: c.quality === "hot" ? "var(--hot-500)" : "var(--text-secondary)", text: c.quality === "hot" ? "Ligar agora — lead quente" : "Fazer primeiro contato" };
}

function FunnelCard({ c, onClick }) {
  const ns = nextStep(c);
  return (
    <Card interactive onClick={onClick} style={{ padding: "13px 16px" }}>
      <div style={{ display: "flex", alignItems: "center", gap: 11 }}>
        <Avatar name={c.name} size={38} />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
            <span style={{ fontWeight: "var(--fw-semibold)", color: "var(--text-strong)", fontSize: "var(--fs-body)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{c.name}</span>
            <LeadQualityBadge quality={c.quality} size="sm" showIcon={false} />
          </div>
          <div style={{ fontSize: "var(--fs-caption)", color: "var(--text-muted)", marginTop: 2 }}>
            {c.service} · {c.price && c.price !== "—" ? <span style={{ color: "var(--brand)", fontWeight: "var(--fw-semibold)" }}>{money(c.price)}</span> : <span>sem cotação</span>} · via {c.source}
          </div>
        </div>
        <span style={{ fontSize: 10.5, color: "var(--text-faint)", flex: "none" }}>{c.when}</span>
      </div>
      <div style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 10, paddingTop: 10, borderTop: "1px dashed var(--border-subtle)" }}>
        <Icon name={ns.icon} size={14} color={ns.color} />
        <span style={{ fontSize: "var(--fs-caption)", fontWeight: "var(--fw-semibold)", color: ns.color }}>{ns.text}</span>
      </div>
    </Card>
  );
}

function FunilView({ go, q }) {
  const [expanded, setExpanded] = React.useState({});
  const LIMIT = 4;
  const leads = D.clients.filter((c) => c.relation === "lead" && matchQ(c, q));
  const totalQuote = leads.reduce((s, c) => s + (parseInt(c.price, 10) || 0), 0);
  return (
    <div>
      {!q && (
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10, marginBottom: 18 }}>
        <Card style={{ padding: "12px 14px" }}>
          <div style={{ fontSize: 24, fontWeight: "var(--fw-bold)", letterSpacing: "var(--ls-tight)", color: "var(--text-strong)", lineHeight: 1 }}>{leads.length}</div>
          <div style={{ fontSize: "var(--fs-micro)", fontWeight: "var(--fw-bold)", letterSpacing: "var(--ls-eyebrow)", textTransform: "uppercase", color: "var(--text-muted)", marginTop: 5 }}>Em negociação</div>
        </Card>
        <Card style={{ padding: "12px 14px" }}>
          <div style={{ fontSize: 24, fontWeight: "var(--fw-bold)", letterSpacing: "var(--ls-tight)", color: "var(--brand)", lineHeight: 1 }}>${totalQuote.toLocaleString("pt-BR")}</div>
          <div style={{ fontSize: "var(--fs-micro)", fontWeight: "var(--fw-bold)", letterSpacing: "var(--ls-eyebrow)", textTransform: "uppercase", color: "var(--text-muted)", marginTop: 5 }}>Em cotações</div>
        </Card>
      </div>
      )}
      {FUNNEL_STAGES.map((s) => {
        const items = leads.filter((c) => c.stage === s.value);
        if (items.length === 0) return null;
        const open = expanded[s.value] || !!q;
        const shown = open ? items : items.slice(0, LIMIT);
        return (
          <div key={s.value} style={{ marginBottom: 18 }}>
            <SectionLabel action={<span style={{ fontSize: "var(--fs-caption)", color: "var(--text-faint)" }}>{items.length}</span>}>{s.label}</SectionLabel>
            <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
              {shown.map((c) => <FunnelCard key={c.id} c={c} onClick={() => go("client", c.id)} />)}
              {items.length > LIMIT && !open && (
                <button onClick={() => setExpanded({ ...expanded, [s.value]: true })} style={{ border: "1px dashed var(--border-default)", background: "transparent", borderRadius: "var(--radius-md)", padding: "11px", fontSize: "var(--fs-sm)", fontWeight: "var(--fw-semibold)", color: "var(--text-link)", cursor: "pointer", fontFamily: "var(--font-sans)" }}>
                  Mostrar mais {items.length - LIMIT}
                </button>
              )}
            </div>
          </div>
        );
      })}
      {leads.length === 0 && (
        <Card inset><EmptyState art={<WaveBars />} title="Nenhum lead encontrado" description={q ? "Tenta outro nome ou telefone." : "Divulgue seu número — cada ligação vira lead aqui."} /></Card>
      )}
      <Button block variant="secondary" onClick={() => go("addlead")} style={{ marginTop: 4 }} iconLeft={<Icon name="plus" size={17} color="var(--text-strong)" />}>Adicionar lead de fora</Button>
    </div>
  );
}

/* ================= CARTEIRA ================= */
function lastJob(c) {
  const j = (c.history || []).find((h) => h.kind === "job");
  return j ? j.date : null;
}

function CarteiraCard({ c, onClick }) {
  const inativo = c.relation === "inativo";
  const lj = lastJob(c);
  return (
    <Card interactive onClick={onClick} style={{ padding: "13px 16px", opacity: inativo ? 0.75 : 1 }}>
      <div style={{ display: "flex", alignItems: "center", gap: 11 }}>
        <Avatar name={c.name} size={42} />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontWeight: "var(--fw-semibold)", color: "var(--text-strong)", fontSize: "var(--fs-body)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{c.name}</div>
          <div style={{ display: "flex", alignItems: "center", gap: 7, marginTop: 4, flexWrap: "wrap" }}>
            {inativo ? <Badge tone="neutral">Inativo</Badge> : typeBadge(c)}
            {!inativo && lj && <span style={{ fontSize: "var(--fs-micro)", color: "var(--text-faint)" }}>último job: {lj}</span>}
            {inativo && <span style={{ fontSize: "var(--fs-micro)", color: "var(--text-faint)" }}>{(c.history && c.history[0] && c.history[0].sub) || ""}</span>}
          </div>
        </div>
        {!inativo && (
          c.firstJob
            ? <Badge tone="brand">1º job agendado</Badge>
            : c.jobsCount === 0
              ? <Badge tone="neutral">Sem jobs ainda</Badge>
              : <div style={{ flex: "none", textAlign: "right" }}>
                  <div style={{ fontSize: "var(--fs-body)", fontWeight: "var(--fw-bold)", color: "var(--brand)" }}>{money(c.ltv)}</div>
                  <div style={{ fontSize: 10.5, color: "var(--text-faint)" }}>{c.jobsCount} jobs</div>
                </div>
        )}
      </div>
    </Card>
  );
}

function CarteiraView({ go, q }) {
  const [filter, setFilter] = React.useState("all");
  const base = D.clients.filter((c) => c.relation !== "lead" && matchQ(c, q));
  const ativos = base.filter((c) => c.relation === "ativo");
  const receita = ativos.reduce((s, c) => s + (parseInt(String(c.ltv).replace(/\./g, ""), 10) || 0), 0);
  const match = (c) =>
    filter === "all" ? true :
    filter === "rec" ? c.type === "recorrente" :
    filter === "avulso" ? c.type === "avulso" :
    c.relation === "inativo";
  const items = base.filter(match);
  return (
    <div>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10, marginBottom: 16 }}>
        <Card style={{ padding: "12px 14px" }}>
          <div style={{ fontSize: 24, fontWeight: "var(--fw-bold)", letterSpacing: "var(--ls-tight)", color: "var(--text-strong)", lineHeight: 1 }}>{ativos.length}</div>
          <div style={{ fontSize: "var(--fs-micro)", fontWeight: "var(--fw-bold)", letterSpacing: "var(--ls-eyebrow)", textTransform: "uppercase", color: "var(--text-muted)", marginTop: 5 }}>Clientes ativos</div>
        </Card>
        <Card style={{ padding: "12px 14px" }}>
          <div style={{ fontSize: 24, fontWeight: "var(--fw-bold)", letterSpacing: "var(--ls-tight)", color: "var(--brand)", lineHeight: 1 }}>${receita.toLocaleString("pt-BR")}</div>
          <div style={{ fontSize: "var(--fs-micro)", fontWeight: "var(--fw-bold)", letterSpacing: "var(--ls-eyebrow)", textTransform: "uppercase", color: "var(--text-muted)", marginTop: 5 }}>Receita da carteira</div>
        </Card>
      </div>
      <div style={{ marginBottom: 14 }}>
        <SegmentedTabs scroll value={filter} onChange={setFilter} size="sm" style={{ width: "100%" }} items={[
          { value: "all", label: "Todos", count: base.length },
          { value: "rec", label: "Recorrentes", count: base.filter((c) => c.type === "recorrente").length },
          { value: "avulso", label: "Avulsos", count: base.filter((c) => c.type === "avulso").length },
          { value: "inativo", label: "Inativos", count: base.filter((c) => c.relation === "inativo").length },
        ]} />
      </div>
      {items.length === 0
        ? <Card inset><EmptyState art={<WaveBars />} title="Nada por aqui" description="Nenhum cliente nesse filtro agora." /></Card>
        : <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
            {items.map((c) => <CarteiraCard key={c.id} c={c} onClick={() => go("client", c.id)} />)}
          </div>}
      <Button block variant="secondary" onClick={() => go("addlead", "cliente")} style={{ marginTop: 14 }} iconLeft={<Icon name="plus" size={17} color="var(--text-strong)" />}>Cadastrar cliente</Button>
    </div>
  );
}

/* ================= wrapper (mobile) ================= */
function ClientsScreen({ go }) {
  const [view, setViewRaw] = React.useState(() => (window.__clientsView === "carteira" ? "carteira" : "funil"));
  const setView = (v) => { window.__clientsView = v; setViewRaw(v); };
  const [q, setQ] = React.useState("");
  const leads = D.clients.filter((c) => c.relation === "lead").length;
  const cart = D.clients.filter((c) => c.relation !== "lead").length;
  return (
    <div style={{ padding: "12px 16px 24px" }}>
      <div style={{ marginBottom: 12 }}>
        <SegmentedTabs value={view} onChange={setView} style={{ width: "100%" }} items={[
          { value: "funil", label: "Funil", count: leads },
          { value: "carteira", label: "Carteira", count: cart },
        ]} />
      </div>
      <SearchBox q={q} setQ={setQ} placeholder={view === "funil" ? "Buscar lead por nome ou telefone…" : "Buscar cliente por nome ou telefone…"} />
      {view === "funil" ? <FunilView go={go} q={q} /> : <CarteiraView go={go} q={q} />}
    </div>
  );
}

/* ================= histórico ================= */
const HIST_ICON = { job: { name: "calendar-check", bg: "var(--success-bg)", fg: "var(--success-600)" }, call: { name: "phone-incoming", bg: "var(--surface-brand-subtle)", fg: "var(--brand)" }, note: { name: "file-text", bg: "var(--surface-sunken)", fg: "var(--text-muted)" } };

function HistoryItem({ h, go, last }) {
  const ic = HIST_ICON[h.kind] || HIST_ICON.note;
  const clickable = h.kind === "call" && h.callId;
  return (
    <div onClick={clickable ? () => go("call", h.callId) : undefined}
      style={{ display: "flex", gap: 12, padding: "11px 0", borderBottom: last ? "none" : "1px dashed var(--border-subtle)", cursor: clickable ? "pointer" : "default", alignItems: "flex-start" }}>
      <div style={{ width: 34, height: 34, borderRadius: "var(--radius-full)", background: ic.bg, display: "flex", alignItems: "center", justifyContent: "center", flex: "none" }}>
        <Icon name={ic.name} size={15} color={ic.fg} />
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: "flex", justifyContent: "space-between", gap: 10, alignItems: "baseline" }}>
          <span style={{ fontSize: "var(--fs-sm)", fontWeight: "var(--fw-semibold)", color: "var(--text-strong)" }}>{h.label}</span>
          {h.price && <span style={{ fontSize: "var(--fs-sm)", fontWeight: "var(--fw-bold)", color: "var(--brand)", flex: "none" }}>{money(h.price)}</span>}
        </div>
        <div style={{ fontSize: "var(--fs-caption)", color: "var(--text-muted)", marginTop: 2, display: "flex", gap: 6, alignItems: "center", flexWrap: "wrap" }}>
          <span>{h.date}</span>{h.sub && <React.Fragment><span>·</span><span>{h.sub}</span></React.Fragment>}
          {clickable && <Icon name="chevron-right" size={13} color="var(--text-faint)" />}
        </div>
      </div>
    </div>
  );
}

/* ================= detalhe ================= */
function ClientDetailScreen({ id, go }) {
  const c = D.clients.find((x) => x.id === id);
  if (!c) return null;
  const isLead = c.relation === "lead";
  const isAtivo = c.relation === "ativo";

  let mainAction;
  if (isLead) {
    if (c.apptId) mainAction = <Button block size="lg" onClick={() => go("job", c.apptId)} iconLeft={<Icon name="calendar" size={18} color="#fff" />}>Ver visita de orçamento</Button>;
    else if (c.stage === "proposal") mainAction = <Button block size="lg" iconLeft={<Icon name="circle-check-big" size={18} color="#fff" />}>Fechou? Agendar serviço</Button>;
    else mainAction = <Button block size="lg" iconLeft={<Icon name="calendar" size={18} color="#fff" />}>Agendar visita de orçamento</Button>;
  } else if (isAtivo) {
    mainAction = <Button block size="lg" onClick={() => go("agenda")} iconLeft={<Icon name="calendar" size={18} color="#fff" />}>Agendar próximo serviço</Button>;
  } else {
    mainAction = <Button block size="lg" variant="secondary" iconLeft={<Icon name="phone-outgoing" size={18} color="var(--text-strong)" />}>Tentar reativar</Button>;
  }

  return (
    <div style={{ padding: "16px 16px 28px", display: "flex", flexDirection: "column", gap: 18 }}>
      {/* header */}
      <Card>
        <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
          <Avatar name={c.name} size={56} />
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: "var(--fs-h3)", fontWeight: "var(--fw-bold)", letterSpacing: "var(--ls-tight)", color: "var(--text-strong)" }}>{c.name}</div>
            <div style={{ display: "flex", gap: 7, marginTop: 7, alignItems: "center", flexWrap: "wrap" }}>
              {relationBadge(c)}
              {typeBadge(c)}
              {isLead && <LeadQualityBadge quality={c.quality} size="sm" />}
            </div>
            <div style={{ fontSize: "var(--fs-caption)", color: "var(--text-muted)", marginTop: 7 }}>
              {isAtivo ? `Cliente desde ${c.since}` : `Chegou ${c.when}`} · via {c.source}
            </div>
          </div>
        </div>
        <div style={{ display: "flex", gap: 10, marginTop: 16 }}>
          <Button block variant="primary" iconLeft={<Icon name="phone-outgoing" size={18} color="#fff" />}>Ligar</Button>
          <Button block variant="secondary" iconLeft={<Icon name="message-circle" size={18} color="var(--text-strong)" />}>SMS</Button>
        </div>
      </Card>

      {/* stats (ativos) */}
      {isAtivo && (
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 10 }}>
          {[{ k: "Total gasto", v: money(c.ltv) }, { k: "Jobs", v: c.jobsCount }, { k: "Ticket médio", v: money(c.avgTicket) }].map((s) => (
            <Card key={s.k} style={{ padding: "12px 12px", textAlign: "center" }}>
              <div style={{ fontSize: "var(--fs-h4)", fontWeight: "var(--fw-bold)", letterSpacing: "var(--ls-tight)", color: s.k === "Total gasto" ? "var(--brand)" : "var(--text-strong)" }}>{s.v}</div>
              <div style={{ fontSize: "var(--fs-micro)", fontWeight: "var(--fw-bold)", letterSpacing: "var(--ls-eyebrow)", textTransform: "uppercase", color: "var(--text-muted)", marginTop: 3 }}>{s.k}</div>
            </Card>
          ))}
        </div>
      )}

      {/* negociação (leads) */}
      {isLead && (
        <Card>
          <SectionLabel>Negociação</SectionLabel>
          <KV k="Serviço desejado" v={c.service} />
          <KV k="Cotação da Riley" v={<span style={{ color: "var(--brand)", fontWeight: "var(--fw-bold)" }}>{money(c.price)}</span>} big />
          <KV k="Etapa" v={funnelStageLabel(c.stage)} />
        </Card>
      )}

      {/* a casa */}
      <Card>
        <SectionLabel>A casa</SectionLabel>
        <KV k="Imóvel" v={`${c.house.type} · ${c.house.beds}q ${c.house.baths}b · ${c.house.sqft.toLocaleString("en-US")} sqft`} />
        <KV k="Endereço" v={c.address} />
        <KV k="Telefone" v={<span style={{ fontFamily: "var(--font-mono)", fontSize: "var(--fs-sm)" }}>{c.phone}</span>} />
        {c.house.notes.length > 0 && (
          <div style={{ display: "flex", flexWrap: "wrap", gap: 7, marginTop: 12 }}>
            {c.house.notes.map((n) => (
              <span key={n} style={{ fontSize: "var(--fs-caption)", fontWeight: "var(--fw-medium)", color: "var(--text-secondary)", background: "var(--surface-sunken)", borderRadius: "var(--radius-full)", padding: "5px 11px" }}>{n}</span>
            ))}
          </div>
        )}
      </Card>

      {/* plano de recorrência (recorrentes) */}
      {c.type === "recorrente" && <window.PlanCard clientId={c.id} go={go} />}

      {/* histórico */}
      {c.history && c.history.length > 0 && (
        <Card>
          <SectionLabel>Histórico</SectionLabel>
          {c.history.map((h, i) => <HistoryItem key={i} h={h} go={go} last={i === c.history.length - 1} />)}
        </Card>
      )}

      {mainAction}
    </div>
  );
}

/* ================= cadastrar lead manual ================= */
function PickChips({ options, value, onChange }) {
  return (
    <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
      {options.map((o) => {
        const on = o.value === value;
        return (
          <button key={o.value} onClick={() => onChange(o.value)} style={{
            border: on ? "1.5px solid var(--brand)" : "1px solid var(--border-default)",
            background: on ? "var(--surface-brand-subtle)" : "var(--surface-card)",
            color: on ? "var(--brand)" : "var(--text-secondary)",
            borderRadius: "var(--radius-full)", padding: "11px 16px", fontSize: "var(--fs-sm)",
            fontWeight: "var(--fw-semibold)", cursor: "pointer", fontFamily: "var(--font-sans)",
          }}>{o.label}</button>
        );
      })}
    </div>
  );
}

function FormField({ label, children }) {
  return (
    <div style={{ marginBottom: 16 }}>
      <div style={{ fontSize: "var(--fs-caption)", fontWeight: "var(--fw-semibold)", color: "var(--text-secondary)", marginBottom: 7 }}>{label}</div>
      {children}
    </div>
  );
}

const leadInputStyle = {
  width: "100%", boxSizing: "border-box", height: 46, borderRadius: "var(--radius-md)",
  border: "1px solid var(--border-default)", background: "var(--surface-card)",
  padding: "0 14px", fontFamily: "var(--font-sans)", fontSize: "var(--fs-body)",
  color: "var(--text-strong)", outline: "none",
  transition: "border-color var(--dur-fast) var(--ease-standard), box-shadow var(--dur-fast) var(--ease-standard)",
};
const leadInputFocus = {
  onFocus: (e) => { e.target.style.borderColor = "var(--brand)"; e.target.style.boxShadow = "var(--focus-shadow)"; },
  onBlur: (e) => { e.target.style.borderColor = "var(--border-default)"; e.target.style.boxShadow = "none"; },
};

function AddLeadScreen({ go, initialMode }) {
  const [mode, setMode] = React.useState(initialMode === "cliente" ? "cliente" : "lead");
  const [f, setF] = React.useState({ name: "", phone: "", source: "Indicação", service: "Deep Clean", quality: "warm", price: "", note: "", type: "recorrente", freq: "Quinzenal", houseType: "House" });
  const set = (k, v) => setF((p) => ({ ...p, [k]: v }));
  const canSave = f.name.trim().length > 1;
  const save = () => {
    const base = {
      id: "x" + Math.floor(Math.random() * 90000 + 1000),
      name: f.name.trim(), phone: f.phone.trim() || "—", address: "—",
      service: f.service, source: f.source, callId: null,
      house: { type: f.houseType, beds: 0, baths: 0, sqft: 0, notes: f.note.trim() ? [f.note.trim()] : [] },
    };
    if (mode === "lead") {
      D.clients.unshift({ ...base, relation: "lead", stage: "new", quality: f.quality, price: f.price.trim() || "—", when: "agora",
        history: [{ kind: "note", date: "Hoje", label: "Lead cadastrado manualmente", sub: `Origem: ${f.source}` }] });
    } else {
      D.clients.unshift({ ...base, relation: "ativo", type: f.type, freq: f.type === "recorrente" ? f.freq : undefined,
        since: "Jun 2025", ltv: "0", jobsCount: 0, avgTicket: "—",
        prefs: { service: f.service, day: "—", window: "—" },
        history: [{ kind: "note", date: "Hoje", label: "Cliente cadastrado manualmente", sub: `Origem: ${f.source} · ${f.type === "recorrente" ? "Recorrente · " + f.freq : "Avulso"}` }] });
    }
    window.__clientsView = mode === "lead" ? "funil" : "carteira";
    go("leads");
  };
  return (
    <div style={{ padding: "16px 16px 28px" }}>
      <div style={{ marginBottom: 14 }}>
        <SegmentedTabs value={mode} onChange={setMode} style={{ width: "100%" }} items={[
          { value: "lead", label: "Lead (negociando)" },
          { value: "cliente", label: "Cliente (já fechou)" },
        ]} />
      </div>
      <Card>
        <FormField label="Nome *">
          <input {...leadInputFocus} style={leadInputStyle} value={f.name} onChange={(e) => set("name", e.target.value)} placeholder="Ex: John Miller" />
        </FormField>
        <FormField label="Telefone">
          <input {...leadInputFocus} style={{ ...leadInputStyle, fontFamily: "var(--font-mono)" }} type="tel" value={f.phone} onChange={(e) => set("phone", e.target.value)} placeholder="+1 (___) ___-____" />
        </FormField>
        <FormField label="De onde veio">
          <PickChips value={f.source} onChange={(v) => set("source", v)} options={["Indicação", "Na rua", "Cliente antigo", "Google", "Yelp", "Instagram", "Facebook", "Outro"].map((s) => ({ value: s, label: s }))} />
        </FormField>
        <FormField label={mode === "lead" ? "Serviço desejado" : "Serviço contratado"}>
          <PickChips value={f.service} onChange={(v) => set("service", v)} options={D.catalog.map((s) => ({ value: s.name, label: s.name }))} />
        </FormField>
        {mode === "lead" ? (
          <React.Fragment>
            <FormField label="Qualidade do lead">
              <PickChips value={f.quality} onChange={(v) => set("quality", v)} options={[{ value: "hot", label: "🔥 Quente" }, { value: "warm", label: "Morno" }, { value: "cold", label: "Frio" }]} />
            </FormField>
            <FormField label="Cotação estimada (US$)">
              <input {...leadInputFocus} style={leadInputStyle} type="number" value={f.price} onChange={(e) => set("price", e.target.value)} placeholder="Ex: 250" />
            </FormField>
          </React.Fragment>
        ) : (
          <React.Fragment>
            <FormField label="Tipo de cliente">
              <PickChips value={f.type} onChange={(v) => set("type", v)} options={[{ value: "recorrente", label: "Recorrente" }, { value: "avulso", label: "Avulso" }]} />
            </FormField>
            {f.type === "recorrente" && (
              <FormField label="Frequência">
                <PickChips value={f.freq} onChange={(v) => set("freq", v)} options={["Semanal", "Quinzenal", "Mensal"].map((s) => ({ value: s, label: s }))} />
              </FormField>
            )}
            <FormField label="Imóvel">
              <PickChips value={f.houseType} onChange={(v) => set("houseType", v)} options={["House", "Apartment", "Townhouse", "Condo"].map((s) => ({ value: s, label: s }))} />
            </FormField>
          </React.Fragment>
        )}
        <FormField label="Observações">
          <textarea {...leadInputFocus} value={f.note} onChange={(e) => set("note", e.target.value)} placeholder={mode === "lead" ? "Ex: vizinho da Emily, quer orçamento semana que vem" : "Ex: cliente desde antes do FrontCall · chave no lockbox"}
            style={{ ...leadInputStyle, height: 84, padding: "12px 14px", resize: "none", lineHeight: 1.45 }} />
        </FormField>
        <Button block size="lg" disabled={!canSave} onClick={save} iconLeft={<Icon name="plus" size={18} color="#fff" />}>
          {mode === "lead" ? "Salvar lead no funil" : "Salvar cliente na carteira"}
        </Button>
      </Card>
    </div>
  );
}

Object.assign(window, { ClientsScreen, FunilView, CarteiraView, FunnelCard, CarteiraCard, ClientDetailScreen, AddLeadScreen, clientByCall, relationBadge, typeBadge, FUNNEL_STAGES, funnelStageLabel });
