/* ============================================================
   PCP — Orçamento: calculadora de custo e preço de venda

   Modelo replicado da planilha "Tabela de Custo Impressão":
     custo material   = quantidade × preço unitário do item de estoque
     custo eletricidade = tempo impressão (h) × consumo (kWh/h) × custo energia (R$/kWh)
     custo máquina    = tempo impressão (h) × custo de hora da máquina
     custo trabalho   = tempo de mão de obra (h) × custo de trabalho (R$/h)
     subtotal         = material + eletricidade + máquina + trabalho + insumos + embalagem
     com taxa de falha= subtotal × (1 + taxa falha%)
     preço sugerido   = com taxa de falha × markup
     preço marketplace= (preço sugerido / (1 − taxa marketplace% − imposto%)) + taxa fixa
   (shares global scope; useState etc. from ui.jsx)
   ============================================================ */

const ORC_CFG_DEFAULT = {
  custoEnergiaKwh: 0.75,   // R$/kWh
  custoTrabalhoHora: 10,   // R$/h de mão de obra
  taxaFalhaPct: 10,        // % de perda/refação
  markupPadrao: 2,         // multiplicador de venda
  taxaMarketplacePct: 20,  // % comissão do canal de venda
  impostoPct: 5.5,         // % imposto sobre a venda
  taxaFixa: 4,             // R$ taxa fixa por venda
};

const orcConfig = (app) => ({ ...ORC_CFG_DEFAULT, ...((app.prefs && app.prefs.orcamentoConfig) || {}) });

// A etapa "Impressão 3D" precisa existir no catálogo (Configurações) pra
// aparecer selecionada no formulário de produto — se não existir ainda
// (nem uma variação de grafia), cadastra na hora.
const ETAPA_IMPRESSAO_NOME = "Impressão 3D";
function garantirEtapaImpressao3D(app) {
  const norm = (s) => String(s || "").toLowerCase().normalize("NFD").replace(/[̀-ͯ]/g, "");
  const existente = (app.etapasCatalogo || []).find((e) => norm(e.nome).replace(/\s+/g, "") === "impressao3d");
  if (existente) return existente.nome;
  app.etapasApi && app.etapasApi.add({ nome: ETAPA_IMPRESSAO_NOME }, true);
  return ETAPA_IMPRESSAO_NOME;
}

const numBR = (s) => {
  if (typeof s === "number") return s;
  const n = parseFloat(String(s == null ? "" : s).replace(",", "."));
  return isNaN(n) ? 0 : n;
};

// Tempo em horas a partir do que o formulario tem no campo. Aceita
// "05:20" (formato atual), decimal de orcamentos antigos ("5.5") e numero.
const horasBR = (v) => {
  if (typeof v === "number") return v;
  const t = String(v == null ? "" : v).trim();
  if (!t) return 0;
  if (t.indexOf(":") >= 0) return window.parseTempoHHMM ? window.parseTempoHHMM(t) : 0;
  if (t.indexOf(".") >= 0 || t.indexOf(",") >= 0) return numBR(t);   // decimal legado
  return window.parseTempoHHMM ? window.parseTempoHHMM(t) : numBR(t); // "40" = 00:40
};
const hhmm = (h) => (window.fmtTempoHHMM ? window.fmtTempoHHMM(h) : String(h));

const criarLinhaMaterial = (material) => ({
  sku: material && material.sku ? material.sku : "",
  quantidade: material && material.quantidade != null
    ? material.quantidade
    : material && material.qtd != null
      ? material.qtd
      : "",
});

function normalizarMateriaisOrcamento(origem) {
  const lista = Array.isArray(origem && origem.materiais) && origem.materiais.length
    ? origem.materiais.map((material) => criarLinhaMaterial(material))
    : [criarLinhaMaterial({
        sku: origem && origem.materialSku ? origem.materialSku : "",
        quantidade: origem && origem.quantidade != null ? origem.quantidade : "",
      })];
  return lista.length ? lista : [criarLinhaMaterial()];
}

function descricaoMateriaisOrcamento(orcamento) {
  const nomesLista = Array.isArray(orcamento && orcamento.materiais)
    ? orcamento.materiais.map((material) => material && material.nome).filter(Boolean)
    : [];
  if (nomesLista.length) return nomesLista.join(", ");
  return (orcamento && orcamento.materialNome) || "—";
}

// Calcula o breakdown completo a partir dos campos do formulário
function calcOrcamento(f, app, cfg) {
  const materiaisDetalhados = normalizarMateriaisOrcamento(f).map((material) => {
    const item = (app.estoque || []).find((x) => x.sku === material.sku) || null;
    const quantidade = numBR(material.quantidade);
    const custo = quantidade * (item ? +item.preco || 0 : 0);
    return {
      sku: material.sku || "",
      quantidade,
      item,
      custo,
    };
  });
  const materiaisValidos = materiaisDetalhados.filter((material) => material.sku);
  const materialPrincipal = materiaisValidos[0] || null;
  const item = materialPrincipal ? materialPrincipal.item : null;
  const maquina = (app.maquinas || []).find((x) => x._id === f.maquinaId) || null;

  const quantidade = materialPrincipal ? materialPrincipal.quantidade : 0;
  const quantidadeTotalMateriais = materiaisValidos.reduce((soma, material) => soma + material.quantidade, 0);
  const tempoImpressaoH = horasBR(f.tempoImpressaoH);
  const tempoTrabalhoH = horasBR(f.tempoTrabalhoH);
  const insumos = numBR(f.insumos);
  const embalagem = numBR(f.embalagem);
  const markup = numBR(f.markup) || cfg.markupPadrao || 1;

  const custoMaterial = materiaisValidos.reduce((soma, material) => soma + material.custo, 0);
  const custoEletricidade = tempoImpressaoH * (maquina ? +maquina.consumoEnergiaKwh || 0 : 0) * (+cfg.custoEnergiaKwh || 0);
  const custoMaquina = tempoImpressaoH * (maquina ? +maquina.custoHora || 0 : 0);
  const custoTrabalho = tempoTrabalhoH * (+cfg.custoTrabalhoHora || 0);

  const subtotal = custoMaterial + custoEletricidade + custoMaquina + custoTrabalho + insumos + embalagem;
  const comFalha = subtotal * (1 + (+cfg.taxaFalhaPct || 0) / 100);
  const precoSugerido = comFalha * markup;
  const denom = 1 - (+cfg.taxaMarketplacePct || 0) / 100 - (+cfg.impostoPct || 0) / 100;
  const precoMarketplace = denom > 0 ? precoSugerido / denom + (+cfg.taxaFixa || 0) : null;

  return {
    item, maquina, quantidade, quantidadeTotalMateriais, materiaisDetalhados, materiaisValidos,
    tempoImpressaoH, tempoTrabalhoH, insumos, embalagem, markup,
    custoMaterial, custoEletricidade, custoMaquina, custoTrabalho,
    subtotal, comFalha, precoSugerido, precoMarketplace,
  };
}

// Mesmo modelo de custo do orcamento, aplicado a um produto ja cadastrado:
// os materiais vem da BOM e o tempo vem das etapas — etapa com maquina conta
// como hora de maquina (energia + depreciacao), etapa sem maquina conta como
// mao de obra. Insumos/embalagem nao existem no cadastro do produto.
function calcProdutoPreco(produto, app, config) {
  const cfg = config || orcConfig(app);
  const estoque = app.estoque || [];
  const maquinas = app.maquinas || [];
  const bom = produto && Array.isArray(produto.bom) ? produto.bom : [];
  const etapas = produto && Array.isArray(produto.etapas) ? produto.etapas : [];

  const custoMaterial = bom.reduce((soma, linha) => {
    const item = estoque.find((x) => x.sku === linha.sku);
    return soma + (item ? (+item.preco || 0) * (+linha.qtd || 0) : 0);
  }, 0);

  let custoEletricidade = 0, custoMaquina = 0, horasMaquina = 0, horasTrabalho = 0;
  etapas.forEach((e) => {
    const h = +e.horas || 0;
    const maquina = e.maquinaId ? maquinas.find((m) => m._id === e.maquinaId) : null;
    if (maquina) {
      horasMaquina += h;
      custoEletricidade += h * (+maquina.consumoEnergiaKwh || 0) * (+cfg.custoEnergiaKwh || 0);
      custoMaquina += h * (+maquina.custoHora || 0);
    } else {
      horasTrabalho += h;
    }
  });
  const custoTrabalho = horasTrabalho * (+cfg.custoTrabalhoHora || 0);

  const subtotal = custoMaterial + custoEletricidade + custoMaquina + custoTrabalho;
  const comFalha = subtotal * (1 + (+cfg.taxaFalhaPct || 0) / 100);
  const markup = +cfg.markupPadrao || 1;
  const precoSugerido = comFalha * markup;
  const denom = 1 - (+cfg.taxaMarketplacePct || 0) / 100 - (+cfg.impostoPct || 0) / 100;
  const precoMarketplace = denom > 0 ? precoSugerido / denom + (+cfg.taxaFixa || 0) : null;
  const margem = precoSugerido > 0 ? (precoSugerido - comFalha) / precoSugerido : null;

  return {
    custoMaterial, custoEletricidade, custoMaquina, custoTrabalho,
    horasMaquina, horasTrabalho, subtotal, comFalha, markup,
    precoSugerido, precoMarketplace, margem,
    // sem BOM e sem etapas nao ha o que calcular — a tela cai no preco cadastrado
    calculavel: subtotal > 0,
  };
}

// ---------------- Configurações globais do cálculo ----------------
function OrcamentoConfigModal({ app, onClose }) {
  const atual = orcConfig(app);
  const [f, setF] = useState({ ...atual });
  const set = (k) => (e) => setF({ ...f, [k]: e.target.value });

  const submit = () => {
    app.setPref("orcamentoConfig", {
      custoEnergiaKwh: numBR(f.custoEnergiaKwh), custoTrabalhoHora: numBR(f.custoTrabalhoHora),
      taxaFalhaPct: numBR(f.taxaFalhaPct), markupPadrao: numBR(f.markupPadrao) || 1,
      taxaMarketplacePct: numBR(f.taxaMarketplacePct), impostoPct: numBR(f.impostoPct), taxaFixa: numBR(f.taxaFixa),
    });
    onClose();
    app.toast("Configurações do orçamento salvas", "ok");
  };

  return (
    <Modal size="md" icon="calculator" title="Configurações do orçamento" sub="Valores padrão usados no cálculo — vinculados à sua conta" onClose={onClose}
      footer={<><span className="spacer" /><Btn onClick={onClose}>Cancelar</Btn><Btn variant="primary" icon="check" onClick={submit}>Salvar</Btn></>}>
      <div className="field-grid c2" style={{ marginBottom: 14 }}>
        <Field label="Custo de energia"><div className="fld-wrap"><span className="pre">R$</span><input className="fld" type="number" step="0.01" value={f.custoEnergiaKwh} onChange={set("custoEnergiaKwh")} /><span className="pre">/kWh</span></div></Field>
        <Field label="Custo de trabalho"><div className="fld-wrap"><span className="pre">R$</span><input className="fld" type="number" step="0.5" value={f.custoTrabalhoHora} onChange={set("custoTrabalhoHora")} /><span className="pre">/h</span></div></Field>
      </div>
      <div className="field-grid c2" style={{ marginBottom: 14 }}>
        <Field label="Taxa de falha" help="% de perda/refação somado ao custo"><div className="fld-wrap"><input className="fld right" type="number" step="1" value={f.taxaFalhaPct} onChange={set("taxaFalhaPct")} /><span className="pre">%</span></div></Field>
        <Field label="Markup padrão" help="multiplicador — 2 = margem de 100%"><input className="fld" type="number" step="0.1" value={f.markupPadrao} onChange={set("markupPadrao")} /></Field>
      </div>
      <div className="form-sec">Preço no marketplace</div>
      <div className="field-grid c3" style={{ marginBottom: 6 }}>
        <Field label="Taxa marketplace"><div className="fld-wrap"><input className="fld right" type="number" step="1" value={f.taxaMarketplacePct} onChange={set("taxaMarketplacePct")} /><span className="pre">%</span></div></Field>
        <Field label="Imposto"><div className="fld-wrap"><input className="fld right" type="number" step="0.1" value={f.impostoPct} onChange={set("impostoPct")} /><span className="pre">%</span></div></Field>
        <Field label="Taxa fixa"><div className="fld-wrap"><span className="pre">R$</span><input className="fld" type="number" step="0.5" value={f.taxaFixa} onChange={set("taxaFixa")} /></div></Field>
      </div>
    </Modal>
  );
}

// ---------------- Novo / editar orçamento ----------------
function NovoOrcamentoForm({ app, onClose, edit }) {
  const cfg = orcConfig(app);
  const [f, setF] = useState(() => ({
    nome: edit ? edit.nome || "" : "",
    clienteId: edit ? edit.clienteId || "" : "",
    materiais: normalizarMateriaisOrcamento(edit),
    maquinaId: edit ? edit.maquinaId || "" : "",
    tempoImpressaoH: edit && edit.tempoImpressaoH ? hhmm(edit.tempoImpressaoH) : "",
    tempoTrabalhoH: edit && edit.tempoTrabalhoH ? hhmm(edit.tempoTrabalhoH) : "",
    insumos: edit && edit.insumos != null ? edit.insumos : "",
    embalagem: edit && edit.embalagem != null ? edit.embalagem : "",
    markup: edit && edit.markup != null ? edit.markup : cfg.markupPadrao,
  }));
  const set = (k) => (e) => setF({ ...f, [k]: e.target.value });
  const setNome = (v) => setF((cur) => ({ ...cur, nome: v }));

  // Sugestões pro nome do projeto: materiais do estoque e produtos já
  // cadastrados. Escolher um produto pré-preenche material/máquina/tempo
  // a partir da BOM e da etapa dele — útil pra reorçar algo que já existe.
  const sugestoesNome = useMemo(() => {
    const materiais = (app.estoque || []).map((e) => ({ tipo: "material", nome: e.nome, sku: e.sku, un: e.un, preco: e.preco }));
    const produtosList = (app.produtos || []).map((p) => ({ tipo: "produto", nome: p.nome, ref: p }));
    return [...materiais, ...produtosList];
  }, [app.estoque, app.produtos]);

  const onSelecionarNome = (i) => {
    if (i.tipo === "material") {
      setF((cur) => {
        const materiais = normalizarMateriaisOrcamento(cur);
        materiais[0] = { ...materiais[0], sku: i.sku };
        return { ...cur, nome: i.nome, materiais };
      });
      return;
    }
    const p = i.ref;
    const materiaisProduto = Array.isArray(p.bom) && p.bom.length
      ? p.bom.map((linha) => criarLinhaMaterial(linha))
      : materiaisFormulario;
    const etapaLocal = Array.isArray(p.etapas) ? p.etapas.find((e) => e.modo !== "terceirizado" && e.maquinaId) : null;
    setF((cur) => ({
      ...cur, nome: i.nome,
      materiais: materiaisProduto,
      maquinaId: etapaLocal ? etapaLocal.maquinaId : cur.maquinaId,
      tempoImpressaoH: etapaLocal ? hhmm(etapaLocal.horas) : cur.tempoImpressaoH,
    }));
    if (materiaisProduto.length || etapaLocal) app.toast("Materiais e máquina preenchidos a partir do produto", "info", { sub: i.nome });
  };

  const calc = useMemo(() => calcOrcamento(f, app, cfg), [f, app.estoque, app.maquinas, cfg]);
  const materiaisFormulario = normalizarMateriaisOrcamento(f);
  const material = calc.item;
  const maquina = calc.maquina;
  const margemPct = calc.markup > 0 ? Math.round((calc.markup - 1) * 100) : 0;

  const atualizarMaterialLinha = (idx, campo) => (e) => {
    const valor = e.target.value;
    setF((cur) => ({
      ...cur,
      materiais: (cur.materiais || []).map((materialLinha, linhaIdx) => (
        linhaIdx === idx ? { ...materialLinha, [campo]: valor } : materialLinha
      )),
    }));
  };

  const adicionarMaterialLinha = () => {
    setF((cur) => ({ ...cur, materiais: [...normalizarMateriaisOrcamento(cur), criarLinhaMaterial()] }));
  };

  const removerMaterialLinha = (idx) => {
    setF((cur) => {
      const materiais = normalizarMateriaisOrcamento(cur).filter((_, linhaIdx) => linhaIdx !== idx);
      return { ...cur, materiais: materiais.length ? materiais : [criarLinhaMaterial()] };
    });
  };

  const validar = () => {
    if (!f.nome.trim()) { app.toast("Informe o nome do projeto/peça", "crit"); return false; }
    if (!calc.materiaisValidos.length) { app.toast("Adicione pelo menos um material", "crit"); return false; }
    for (let i = 0; i < calc.materiaisDetalhados.length; i += 1) {
      const linha = calc.materiaisDetalhados[i];
      const quantidadeInformada = String((f.materiais && f.materiais[i] && f.materiais[i].quantidade) || "").trim();
      if (linha.sku && linha.quantidade <= 0) {
        app.toast(`Informe uma quantidade válida para o material ${i + 1}`, "crit");
        return false;
      }
      if (!linha.sku && quantidadeInformada) {
        app.toast(`Escolha o material da linha ${i + 1}`, "crit");
        return false;
      }
    }
    if (!f.maquinaId) { app.toast("Escolha a máquina", "crit"); return false; }
    if (calc.tempoImpressaoH <= 0) { app.toast("Informe o tempo de impressão", "crit"); return false; }
    return true;
  };

  const montarPayload = () => {
    const materiais = calc.materiaisValidos.map((materialLinha) => ({
      sku: materialLinha.sku,
      nome: materialLinha.item ? materialLinha.item.nome : "",
      un: materialLinha.item ? materialLinha.item.un : "",
      precoUnit: materialLinha.item ? (+materialLinha.item.preco || 0) : 0,
      quantidade: materialLinha.quantidade,
      custo: materialLinha.custo,
    }));
    const materialPrincipal = materiais[0] || null;
    return {
      nome: f.nome.trim(), clienteId: f.clienteId || null,
      clienteNome: f.clienteId ? ((app.clientes || []).find((c) => c._id === f.clienteId) || {}).nome || "" : "",
      materiais,
      materialSku: materialPrincipal ? materialPrincipal.sku : "",
      materialNome: materiais.map((materialLinha) => materialLinha.nome).filter(Boolean).join(", "),
      maquinaId: f.maquinaId, maquinaNome: maquina ? maquina.nome : "",
      quantidade: materialPrincipal ? materialPrincipal.quantidade : 0,
      quantidadeTotalMateriais: calc.quantidadeTotalMateriais,
      tempoImpressaoH: calc.tempoImpressaoH, tempoTrabalhoH: calc.tempoTrabalhoH,
      insumos: calc.insumos, embalagem: calc.embalagem, markup: calc.markup,
      custoMaterial: calc.custoMaterial, custoEletricidade: calc.custoEletricidade, custoMaquina: calc.custoMaquina, custoTrabalho: calc.custoTrabalho,
      subtotal: calc.subtotal, comFalha: calc.comFalha, precoSugerido: calc.precoSugerido, precoMarketplace: calc.precoMarketplace,
    };
  };

  const salvar = () => {
    if (!validar()) return;
    const payload = montarPayload();
    if (edit) app.orcamentosApi.update(edit._id, payload); else app.orcamentosApi.add(payload, true);
    app.logEvento && app.logEvento(edit ? "editar_orcamento" : "criar_orcamento", f.nome, { precoSugerido: Math.round(calc.precoSugerido) });
    onClose();
    app.toast(edit ? "Orçamento atualizado" : "Orçamento salvo", "ok", { sub: f.nome, icon: "calculator" });
  };

  const criarProduto = () => {
    if (!validar()) return;
    // salva/atualiza o orçamento também, pra não perder o cálculo
    const payload = montarPayload();
    if (edit) app.orcamentosApi.update(edit._id, payload); else app.orcamentosApi.add(payload, true);
    const etapaNome = maquina ? garantirEtapaImpressao3D(app) : null;
    const prefill = {
      nome: f.nome.trim(),
      preco: Math.round(calc.precoSugerido * 100) / 100,
      modo: "Sob demanda",
      lote: 1,
      bom: calc.materiaisValidos.map((materialLinha) => ({ sku: materialLinha.sku, qtd: materialLinha.quantidade })),
      etapas: maquina ? [{ nome: etapaNome, horas: calc.tempoImpressaoH, modo: "local", maquinaId: maquina._id }] : [],
    };
    onClose();
    app.openModal("novoProduto", { prefill });
  };

  // Cadastro rápido de material/cliente/máquina abre um modal ANINHADO local
  // (não via app.openModal) — o app só guarda um modal por vez, então abrir
  // pelo mecanismo global fecharia este orçamento e perderia tudo digitado.
  const [subModal, setSubModal] = useState(null); // "material" | "cliente" | "maquina" | "config" | null
  const fecharSub = () => setSubModal(null);

  const linha = (label, valor, opts) => (
    <div className={"srow" + (opts && opts.tot ? " tot" : "")}>
      <span className={opts && opts.tot ? "" : "muted"}>{label}</span>
      <span className="v">{valor}</span>
    </div>
  );

  return (
    <>
    <Modal size="lg" icon="calculator" title={edit ? "Editar orçamento" : "Novo orçamento"}
      sub="Custo de impressão 3D — material, máquina e mão de obra" onClose={onClose}
      footer={<>
        <Btn icon="package" onClick={criarProduto}>Criar produto a partir do orçamento</Btn>
        <span className="spacer" />
        <Btn onClick={onClose}>Cancelar</Btn>
        <Btn variant="primary" icon="check" onClick={salvar}>{edit ? "Salvar alterações" : "Salvar orçamento"}</Btn>
      </>}>

      <div className="field-grid c2" style={{ marginBottom: 14 }}>
        <Field label="Nome do projeto / peça" req help="digite pra ver materiais do estoque e produtos já cadastrados">
          <Autocomplete items={sugestoesNome} value={f.nome} onChange={setNome} onSelect={onSelecionarNome} autoFocus
            placeholder="Ex.: Conector L Metalon 20x20"
            render={(i) => (
              <>
                <span className="t">{i.nome}</span>
                <span className="s">{i.tipo === "material" ? `Material · ${DB.BRL(i.preco)}/${i.un}` : `Produto · ${i.ref.sku}`}</span>
              </>
            )} />
        </Field>
        <Field label="Cliente" opt help="salve o orçamento vinculado a um cliente, se quiser">
          <div className="row gap8">
            <select className="fld" style={{ flex: 1, minWidth: 0 }} value={f.clienteId} onChange={set("clienteId")}>
              <option value="">— sem cliente —</option>
              {(app.clientes || []).map((c) => <option key={c._id} value={c._id}>{c.nome}</option>)}
            </select>
            <Btn icon="plus" onClick={() => setSubModal("cliente")}>Novo</Btn>
          </div>
        </Field>
      </div>

      <div className="form-sec">Material e máquina</div>
      {materiaisFormulario.map((materialLinha, idx) => {
        const materialAtual = (app.estoque || []).find((it) => it.sku === materialLinha.sku) || null;
        return (
          <div className="field-grid c2" style={{ marginBottom: idx === materiaisFormulario.length - 1 ? 6 : 10 }} key={idx}>
            <Field
              label={idx === 0 ? "Material" : `Material ${idx + 1}`}
              req
              help={materialAtual ? `${DB.BRL(materialAtual.preco)} / ${materialAtual.un} em estoque` : (app.estoque || []).length === 0 ? "nenhum material cadastrado ainda" : "escolha um item do estoque"}
            >
              <div className="row gap8">
                <select className="fld" style={{ flex: 1, minWidth: 0 }} value={materialLinha.sku} onChange={atualizarMaterialLinha(idx, "sku")}>
                  <option value="">Selecione…</option>
                  {(app.estoque || []).map((it) => <option key={it.sku} value={it.sku}>{it.nome}</option>)}
                </select>
                {idx === 0 && <Btn icon="plus" onClick={() => setSubModal("material")}>Novo</Btn>}
                {materiaisFormulario.length > 1 && <Btn icon="trash" onClick={() => removerMaterialLinha(idx)}>Remover</Btn>}
              </div>
            </Field>
            <Field label={"Quantidade utilizada" + (materialAtual ? ` (${materialAtual.un})` : "")} req>
              <input
                className="fld right"
                type="number"
                step="0.01"
                min="0"
                value={materialLinha.quantidade}
                onChange={atualizarMaterialLinha(idx, "quantidade")}
                placeholder="0"
              />
            </Field>
          </div>
        );
      })}
      <div style={{ marginBottom: 14 }}>
        <Btn icon="plus" onClick={adicionarMaterialLinha}>Adicionar material</Btn>
      </div>
      <div className="field-grid c2" style={{ marginBottom: 14 }}>
        <Field label="Máquina" req help={maquina ? `${DB.BRL(maquina.custoHora || 0)}/h${maquina.consumoEnergiaKwh ? ` · ${maquina.consumoEnergiaKwh} kWh/h` : ""}` : (app.maquinas || []).length === 0 ? <>nenhuma cadastrada — <a style={{ color: "var(--accent)", cursor: "pointer" }} onClick={() => setSubModal("maquina")}>cadastrar</a></> : "escolha o equipamento"}>
          <div className="row gap8">
            <select className="fld" style={{ flex: 1, minWidth: 0 }} value={f.maquinaId} onChange={set("maquinaId")}>
              <option value="">Selecione…</option>
              {(app.maquinas || []).map((m) => <option key={m._id} value={m._id}>{m.nome}</option>)}
            </select>
            <Btn icon="plus" onClick={() => setSubModal("maquina")}>Nova</Btn>
          </div>
        </Field>
        <Field label="Tempo de impressão" req help="hh:mm — ex.: 05:20 para 5h20">
          <div className="fld-wrap">
            <input className="fld right mono" type="text" inputMode="numeric" placeholder="00:00"
              value={f.tempoImpressaoH} onChange={set("tempoImpressaoH")}
              onBlur={(e) => setF((cur) => ({ ...cur, tempoImpressaoH: e.target.value.trim() ? hhmm(horasBR(e.target.value)) : "" }))} />
            <span className="pre">hh:mm</span>
          </div>
        </Field>
      </div>

      <div className="form-sec">Mão de obra e outros custos</div>
      <div className="field-grid c3" style={{ marginBottom: 14 }}>
        <Field label="Trabalho manual" opt help="pós-processamento, montagem… · hh:mm">
          <div className="fld-wrap">
            <input className="fld right mono" type="text" inputMode="numeric" placeholder="00:00"
              value={f.tempoTrabalhoH} onChange={set("tempoTrabalhoH")}
              onBlur={(e) => setF((cur) => ({ ...cur, tempoTrabalhoH: e.target.value.trim() ? hhmm(horasBR(e.target.value)) : "" }))} />
            <span className="pre">hh:mm</span>
          </div>
        </Field>
        <Field label="Insumos extras" opt><div className="fld-wrap"><span className="pre">R$</span><input className="fld" type="number" step="0.01" min="0" value={f.insumos} onChange={set("insumos")} placeholder="0,00" /></div></Field>
        <Field label="Embalagem" opt><div className="fld-wrap"><span className="pre">R$</span><input className="fld" type="number" step="0.01" min="0" value={f.embalagem} onChange={set("embalagem")} placeholder="0,00" /></div></Field>
      </div>

      <div className="form-sec">Preço de venda</div>
      <div style={{ marginBottom: 14 }}>
        <Field label="Markup" help={`multiplicador sobre o custo · margem de ${margemPct}%`}>
          <input className="fld" type="number" step="0.1" min="0" value={f.markup} onChange={set("markup")} style={{ maxWidth: 160 }} />
        </Field>
        <a style={{ color: "var(--accent)", cursor: "pointer", fontSize: 12.5, display: "inline-flex", alignItems: "center", gap: 5, marginTop: 6 }} onClick={() => setSubModal("config")}>
          <Icon name="settings" size={12} /> ajustar taxas padrão (energia, falha, marketplace…)
        </a>
      </div>

      <div className="sumbox" style={{ marginBottom: 6 }}>
        {calc.materiaisValidos.length <= 1 && linha("Material" + (material ? ` (${material.nome})` : ""), DB.BRL(calc.custoMaterial))}
        {calc.materiaisValidos.length > 1 && calc.materiaisValidos.map((materialLinha, idx) => (
          <div key={materialLinha.sku + "-" + idx}>
            {linha(`Material ${idx + 1} (${materialLinha.item ? materialLinha.item.nome : materialLinha.sku})`, DB.BRL(materialLinha.custo))}
          </div>
        ))}
        {calc.materiaisValidos.length > 1 && linha("Materiais (total)", DB.BRL(calc.custoMaterial), { tot: true })}
        {linha("Eletricidade · " + hhmm(calc.tempoImpressaoH), DB.BRL(calc.custoEletricidade))}
        {linha("Máquina (depreciação) · " + hhmm(calc.tempoImpressaoH), DB.BRL(calc.custoMaquina))}
        {linha("Trabalho manual · " + hhmm(calc.tempoTrabalhoH), DB.BRL(calc.custoTrabalho))}
        {calc.insumos > 0 && linha("Insumos", DB.BRL(calc.insumos))}
        {calc.embalagem > 0 && linha("Embalagem", DB.BRL(calc.embalagem))}
        {linha(`Subtotal + falha (${cfg.taxaFalhaPct}%)`, DB.BRL(calc.comFalha), { tot: true })}
      </div>
      <div className="kv-big">
        <div className="b"><div className="l">Preço sugerido</div><div className="v">{DB.BRL(calc.precoSugerido)}</div></div>
        <div className="b"><div className="l">No marketplace</div><div className="v">{calc.precoMarketplace != null ? DB.BRL(calc.precoMarketplace) : "—"}</div></div>
        <div className="b"><div className="l">Margem</div><div className="v" style={{ color: "var(--ok)" }}>{margemPct}%</div></div>
      </div>
    </Modal>

    {/* onClose já fecha o submodal; onCreated só precisa preencher o campo */}
    {subModal === "material" && <NovoItemForm app={app} onClose={fecharSub}
      onCreated={(it) => setF((cur) => {
        const materiais = normalizarMateriaisOrcamento(cur);
        const idxLivre = materiais.findIndex((materialLinha) => !materialLinha.sku);
        if (idxLivre >= 0) materiais[idxLivre] = { ...materiais[idxLivre], sku: it.sku };
        else materiais.push(criarLinhaMaterial({ sku: it.sku }));
        return { ...cur, materiais };
      })} />}
    {subModal === "cliente" && <NovoClienteForm app={app} onClose={fecharSub}
      onCreated={(c) => setF((cur) => ({ ...cur, clienteId: c._id }))} />}
    {subModal === "maquina" && <NovaMaquinaForm app={app} onClose={fecharSub}
      onCreated={(m) => setF((cur) => ({ ...cur, maquinaId: m._id }))} />}
    {subModal === "config" && <OrcamentoConfigModal app={app} onClose={fecharSub} />}
    </>
  );
}

// ---------------- Tela ----------------
function Orcamentos({ app }) {
  const orcamentos = app.orcamentos || [];
  const [q, setQ] = useState("");

  const rows = useMemo(() => {
    const t = q.trim().toLowerCase();
    if (!t) return orcamentos;
    return orcamentos.filter((o) => (o.nome + " " + (o.clienteNome || "") + " " + descricaoMateriaisOrcamento(o)).toLowerCase().includes(t));
  }, [orcamentos, q]);

  const totalSugerido = orcamentos.reduce((s, o) => s + (o.precoSugerido || 0), 0);
  const margemMedia = orcamentos.length
    ? Math.round(orcamentos.reduce((s, o) => s + ((o.markup || 1) - 1) * 100, 0) / orcamentos.length)
    : 0;

  const excluir = (o) => app.openModal("confirm", {
    title: "Excluir orçamento?",
    message: <>O orçamento <b>{o.nome}</b> será removido.</>,
    successMsg: "Orçamento excluído",
    onConfirm: () => app.orcamentosApi.remove(o._id),
  });

  const criarProdutoDireto = (o) => {
    const materiais = Array.isArray(o.materiais) && o.materiais.length
      ? o.materiais.map((materialLinha) => ({ sku: materialLinha.sku, qtd: numBR(materialLinha.quantidade) }))
      : o.materialSku
        ? [{ sku: o.materialSku, qtd: numBR(o.quantidade) }]
        : [];
    const etapaNome = o.maquinaId ? garantirEtapaImpressao3D(app) : null;
    const prefill = {
      nome: o.nome, preco: Math.round((o.precoSugerido || 0) * 100) / 100, modo: "Sob demanda", lote: 1,
      bom: materiais,
      etapas: o.maquinaId ? [{ nome: etapaNome, horas: o.tempoImpressaoH || 0, modo: "local", maquinaId: o.maquinaId }] : [],
    };
    app.openModal("novoProduto", { prefill });
  };

  return (
    <div className="view-inner">
      <div className="page-head head-row">
        <div>
          <div className="crumb">Cadastros</div>
          <h1 className="page-title">Orçamento</h1>
          <p className="page-sub">{orcamentos.length} orçamento{orcamentos.length === 1 ? "" : "s"} · calculadora de custo de impressão 3D</p>
        </div>
        <div className="spacer" />
        <div className="row gap8">
          <IconBtn icon="settings" title="Configurações do orçamento" bordered onClick={() => app.openModal("configOrcamento")} />
          <Btn icon="plus" variant="primary" onClick={() => app.openModal("novoOrcamento")}>Novo orçamento</Btn>
        </div>
      </div>

      {orcamentos.length === 0 ? (
        <div className="card" style={{ padding: "30px 0" }}>
          <Empty icon="calculator" title="Nenhum orçamento ainda"
            action={<Btn icon="plus" variant="primary" onClick={() => app.openModal("novoOrcamento")}>Novo orçamento</Btn>}>
            Calcule o custo de uma peça a partir do material, da máquina e do tempo de produção, e veja o preço sugerido de venda.
          </Empty>
        </div>
      ) : (
        <>
          <div className="metrics" style={{ gridTemplateColumns: "repeat(3, 1fr)", marginBottom: 18 }}>
            <MetricCard icon="calculator" label="Orçamentos salvos" value={orcamentos.length} />
            <MetricCard icon="dollar" label="Soma sugerida" value={DB.BRL(totalSugerido)} />
            <MetricCard icon="percent" label="Margem média" value={margemMedia + "%"} />
          </div>

          <div className="toolbar" style={{ marginBottom: 14 }}>
            <div className="input" style={{ width: 260 }}>
              <Icon name="search" size={15} />
              <input value={q} onChange={(e) => setQ(e.target.value)} placeholder="Buscar por projeto, cliente ou material…" />
            </div>
            <span className="spacer" />
            <span className="small muted">{rows.length} de {orcamentos.length}</span>
          </div>

          <div className="card tbl-wrap">
            <table className="tbl">
              <thead><tr><th>Projeto</th><th>Cliente</th><th>Material</th><th>Máquina</th><th className="num">Custo</th><th className="num">Sugerido</th><th className="num">Marketplace</th><th></th></tr></thead>
              <tbody>
                {rows.length === 0 && (
                  <tr><td colSpan="8"><div className="muted small" style={{ padding: "18px 4px" }}>Nada encontrado.</div></td></tr>
                )}
                {rows.map((o) => (
                  <tr key={o._id} className="clickable" onClick={() => app.openModal("novoOrcamento", { edit: o })}>
                    <td className="strong">{o.nome}</td>
                    <td className="muted">{o.clienteNome || <span className="muted">—</span>}</td>
                    <td className="small">{descricaoMateriaisOrcamento(o)}</td>
                    <td className="small">{o.maquinaNome || "—"}</td>
                    <td className="num muted">{DB.BRL(o.comFalha || 0)}</td>
                    <td className="num strong">{DB.BRL(o.precoSugerido || 0)}</td>
                    <td className="num">{o.precoMarketplace != null ? DB.BRL(o.precoMarketplace) : "—"}</td>
                    <td onClick={(e) => e.stopPropagation()}>
                      <RowMenu items={[
                        { icon: "edit", label: "Editar orçamento", onClick: () => app.openModal("novoOrcamento", { edit: o }) },
                        { icon: "package", label: "Criar produto", onClick: () => criarProdutoDireto(o) },
                        { sep: true },
                        { icon: "trash", label: "Excluir", danger: true, onClick: () => excluir(o) },
                      ]} />
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </>
      )}
    </div>
  );
}

if (window.MODALS) {
  window.MODALS.novoOrcamento = NovoOrcamentoForm;
  window.MODALS.configOrcamento = OrcamentoConfigModal;
}
Object.assign(window, { Orcamentos, NovoOrcamentoForm, OrcamentoConfigModal, calcOrcamento, orcConfig, ORC_CFG_DEFAULT, horasBR, calcProdutoPreco });
