<?php /** @var string $title */ ?>
<main class="container">
  <style>
    /* Responsividade e consistência visual alinhadas ao layout de Orçamentos */
    .table-responsive{ overflow:auto; width:100%; }
    @media (max-width: 1280px){
      .grid.responsive-3{ grid-template-columns: 2fr auto !important; }
    }
    @media (max-width: 1024px){
      .grid.responsive-2{ grid-template-columns: 1fr !important; }
      .grid.responsive-3{ grid-template-columns: 1fr !important; }
      .card, .box{ margin-bottom:.75rem; }
      .page-header{ flex-direction: column; align-items: flex-start; gap:.5rem; }
    }
  </style>
  <header class="page-header" style="display:flex;align-items:center;justify-content:space-between;gap:1rem;">
    <div>
      <h1><?= htmlspecialchars($title ?? 'Novo Pedido') ?></h1>
      <div style="margin-top:.25rem; font-weight:600;">
        Nº do Pedido: <span id="orderNumber">N/A</span> · Status: <span id="orderStatusText">Pendente</span>
      </div>
    </div>
    <div style="display:flex;gap:.5rem;">
      <a href="/vendas/pedidos" class="btn btn-secondary">Cancelar</a>
      <button id="btnPreview" class="btn">Pré-visualizar</button>
      <button id="btnPrint" class="btn">Imprimir</button>
      <button id="btnEmail" class="btn" disabled>Enviar por e-mail</button>
      <button id="btnSave" class="btn btn-primary">Salvar Pedido</button>
    </div>
  </header>
  <div id="fromQuoteBanner" class="box" style="display:none; background:#eef6ff; border:1px solid #cbe2ff;">
    <strong>Pedido gerado a partir de Orçamento</strong>
    <div id="fromQuoteText" class="muted" style="margin-top:.25rem;"></div>
  </div>
  <script>
    (function(){
      try {
        const p = new URLSearchParams(window.location.search);
        const qid = p.get('from_quote');
        const qnum = p.get('quote_numero');
        const onum = p.get('order_numero');
        if (qid || qnum) {
          const el = document.getElementById('fromQuoteBanner');
          const tx = document.getElementById('fromQuoteText');
          const qLabel = qnum ? `Orçamento ${qnum}` : `Orçamento #${qid}`;
          const oLabel = onum ? `Pedido ${onum}` : 'Pedido gerado';
          tx.textContent = `${oLabel} replicado integralmente a partir de ${qLabel}. Apenas referências foram atualizadas (prefixo e numeração).`;
          // Link para lista de orçamentos
          const link = document.createElement('a');
          link.href = '/vendas/orcamentos';
          link.textContent = 'Abrir Orçamentos';
          link.style.marginLeft = '.5rem';
          link.className = 'btn btn-secondary';
          el.appendChild(link);
          el.style.display = 'block';
        }
      } catch (e) { /* noop */ }
    })();
  </script>

  <!-- 1. Informações Gerais do Pedido -->
  <section class="card">
    <h2>Informações Gerais do Pedido</h2>
    <div class="grid responsive-3" style="grid-template-columns: repeat(3, minmax(0,1fr)); gap:.75rem;">
      <div>
        <label class="muted">Situação</label>
        <select id="orderStatus">
          <option value="pendente" selected>Pendente</option>
          <option value="aprovado">Aprovado</option>
          <option value="faturado">Faturado</option>
          <option value="cancelado">Cancelado</option>
        </select>
      </div>
      <div>
        <label class="muted">Data de Emissão</label>
        <input id="issueDate" type="date" />
      </div>
      <div>
        <label class="muted">Previsão de Entrega</label>
        <input id="expectedDate" type="date" />
      </div>
      <div>
        <label class="muted">Vendedor Responsável</label>
        <div style="display:flex; gap:.5rem; align-items:center;">
          <input id="sellerSearch" type="text" placeholder="Filtrar vendedor" style="max-width:220px;" />
          <select id="sellerSelect" title="Selecione o vendedor" style="min-width:220px;"></select>
        </div>
        <small class="muted">Use o filtro para buscar e selecione na lista.</small>
      </div>
      <div>
        <label class="muted">Consumidor final</label>
        <div style="display:flex;align-items:center;gap:.5rem;">
          <input id="consumerFinal" type="checkbox" />
          <small class="muted">Marque se o cliente for consumidor final</small>
        </div>
      </div>
    </div>
    <hr style="margin:1rem 0;" />
    <div class="grid responsive-2" style="grid-template-columns: 2fr 1.3fr; gap:.75rem; align-items:start;">
      <div>
        <label class="muted">Cliente</label>
        <div style="display:flex; gap:.5rem;">
          <input id="clientSearch" type="text" placeholder="Nome, e-mail, CNPJ/CPF" />
          <button id="btnClientLookup" class="btn">Pesquisar</button>
          <button id="btnNewClient" class="btn btn-secondary">Novo Cliente</button>
        </div>
        <small class="muted">Selecione um cliente para prosseguir. Campo obrigatório.</small>
        <div id="clientResults" class="list" style="margin-top:.5rem;"></div>
      </div>
      <div>
        <div class="box">
          <strong>Resumo do Cliente</strong>
          <div id="clientSummary" class="muted">Nenhum cliente selecionado.</div>
        </div>
        <!-- Histórico removido por solicitação -->
      </div>
    </div>
  </section>

  <!-- 2. Itens do Pedido -->
  <section class="card">
    <div style="display:flex;justify-content:space-between;align-items:center;">
      <h2>Itens do Pedido</h2>
      <div style="display:flex; gap:.5rem; align-items:center;">
        <input id="itemsFilter" type="text" placeholder="Filtrar por nome/código" style="max-width:240px;" />
        <select id="itemsSort" title="Ordenar">
          <option value="nome">Nome</option>
          <option value="preco">Preço</option>
          <option value="estoque">Estoque</option>
        </select>
        <button id="btnOpenProductSearch" class="btn" title="Pesquisa avançada de produtos">Pesquisa de produtos</button>
      </div>
    </div>
    <div class="grid responsive-3" style="grid-template-columns: 2fr auto auto; gap:.5rem; align-items:end;">
      <div>
        <label class="muted">Buscar produto por nome/código/código de barras</label>
        <div style="display:flex; gap:.5rem; align-items:center;">
          <input id="productSearch" type="text" placeholder="Ex.: 789..., ABC123, Nome do produto" />
          <button id="btnClearProductSearch" class="btn btn-secondary" type="button">Limpar</button>
        </div>
      </div>
      <div>
        <label class="muted">Quantidade</label>
        <input id="itemQty" type="number" min="1" step="1" data-type="quantity" value="1" />
      </div>
      <div>
        <button id="btnAddItem" class="btn">Confirmar item</button>
      </div>
    </div>
    <div style="display:flex; gap:.5rem; align-items:center; margin-top:.5rem;">
      <input id="importFile" type="file" accept=".csv,.txt" style="display:none;" />
      <button id="btnImportItems" class="btn btn-outline" type="button">Importar planilha</button>
      <button id="btnTemplateCSV" class="btn btn-outline" type="button">Modelo de Planilha</button>
    </div>
    <div id="productResults" class="list" style="margin-top:.5rem;"></div>
    <div class="table-responsive">
    <table class="table" style="margin-top:.75rem; min-width:900px;">
      <thead>
        <tr>
          <th>Foto</th>
          <th>Código</th>
          <th>Nome</th>
          <th class="right">Estoque</th>
          <th>Embalagem</th>
          <th class="right">Preço Unit.</th>
          <th class="right">Qtd</th>
          <th class="right">ST (R$)</th>
          <th class="right">IPI (R$)</th>
          <th>Obs.</th>
          <th class="right">Subtotal</th>
          <th></th>
        </tr>
      </thead>
      <tbody id="itemsRows"><tr><td colspan="12" class="muted">Nenhum item</td></tr></tbody>
    </table>
    </div>
  </section>

  <!-- 3. Dados Financeiros -->
  <section class="card">
    <h2>Dados Financeiros</h2>
    <div class="grid responsive-3" style="grid-template-columns: 1fr 1fr 1fr; gap:.5rem; align-items:end;">
      <div>
        <label class="muted">Tabela de Preço</label>
        <select id="priceTable">
          <option value="padrao">Padrão</option>
          <option value="atacado">Atacado</option>
          <option value="varejo">Varejo</option>
        </select>
      </div>
      <div>
        <label class="muted">Desconto (%)</label>
        <input id="discountGlobal" type="number" min="0" max="100" step="0.01" value="0" />
      </div>
      <div>
        <label class="muted">Acréscimo (%)</label>
        <input id="markupGlobal" type="number" min="0" max="100" step="0.01" value="0" />
      </div>
    </div>
    <div class="grid" style="grid-template-columns: 1fr 1fr; gap:.5rem; align-items:end;">
      <div>
        <label class="muted">Condição de pagamento</label>
        <input id="payCondition" type="text" placeholder="Ex.: 10/20/30 | 0,00%" />
      </div>
      <div>
        <label class="muted">Forma de pagamento</label>
        <select id="payMethod">
          <option value="avista">À vista</option>
          <option value="parcelado">Parcelado</option>
          <option value="cartao">Cartão</option>
          <option value="pix">PIX</option>
          <option value="boleto">Boleto</option>
          <option value="transferencia">Transferência</option>
        </select>
      </div>
    </div>
    <div id="payFields" style="margin-top:.5rem;"></div>
    <div id="installmentsBox" class="card" style="margin-top:.75rem; display:none;">
      <strong>Parcelas</strong>
      <div class="table-responsive">
        <table class="table">
          <thead><tr><th>#</th><th>Vencimento</th><th class="right">Valor</th></tr></thead>
          <tbody></tbody>
        </table>
      </div>
      <small class="muted">Geradas automaticamente pela condição de pagamento e data de emissão.</small>
    </div>
    <div class="card" style="margin-top:.75rem;">
      <strong>Total do orçamento</strong>
      <div id="totalsBox" style="font-size:1.1rem; font-weight:600;">Subtotal: R$ 0,00 · Impostos: R$ 0,00 · Frete: R$ 0,00 · Total: R$ 0,00</div>
    </div>
  </section>

  <!-- 4. Logística/Transporte -->
  <section class="card">
    <h2>Logística/Transporte</h2>
    <div class="grid responsive-2" style="grid-template-columns: 1fr 2fr; gap:.75rem;">
      <div>
        <label class="muted">Opção</label>
        <select id="deliveryOption">
          <option value="retirada">Retirada</option>
          <option value="entrega">Entrega</option>
        </select>
      </div>
      <div>
        <div class="grid" style="grid-template-columns: repeat(2, minmax(0,1fr)); gap:.5rem;">
          <div>
            <label class="muted">Data</label>
            <input id="deliveryDate" type="date" />
          </div>
          <div>
            <label class="muted">Horário</label>
            <input id="deliveryTime" type="time" />
          </div>
        </div>
        <div id="deliveryAddrBox" style="margin-top:.5rem;">
          <label class="muted">Endereço de entrega</label>
          <input id="deliveryAddress" type="text" placeholder="Rua, número, bairro, cidade" />
        </div>
        <div class="grid" style="grid-template-columns: 1fr 1fr; gap:.5rem; margin-top:.5rem;">
          <div>
            <label class="muted">Modalidade de Frete</label>
            <select id="freteMode">
              <option value="cif">CIF</option>
              <option value="fob">FOB</option>
            </select>
          </div>
          <div>
            <label class="muted">Frete (R$)</label>
            <input id="freteValue" type="number" min="0" step="0.01" value="0" />
            <div style="margin-top:.25rem; display:flex; align-items:center; gap:.5rem;">
              <input id="freteSomar" type="checkbox" checked />
              <small class="muted">Somar ao total do pedido</small>
            </div>
          </div>
        </div>
        <div class="grid" style="grid-template-columns: 1fr auto; gap:.5rem; margin-top:.5rem; align-items:end;">
          <div>
            <label class="muted">Transportadora</label>
            <select id="carrierSelect" style="width:100%; min-width:220px;"></select>
          </div>
          <div>
            <label class="muted" style="visibility:hidden;">Nova</label>
            <button id="newCarrierBtn" type="button" class="btn btn-secondary">Nova</button>
          </div>
        </div>
        <div class="grid" style="grid-template-columns: 1fr 1fr; gap:.5rem; margin-top:.5rem;">
          <div>
            <label class="muted">Peso Bruto (kg)</label>
            <input id="pesoBruto" type="number" min="0" step="0.001" value="0" />
          </div>
          <div>
            <label class="muted">Peso Líquido (kg)</label>
            <input id="pesoLiquido" type="number" min="0" step="0.001" value="0" />
          </div>
        </div>
        <div class="grid" style="grid-template-columns: 1fr 1fr; gap:.5rem; margin-top:.5rem;">
          <div>
            <label class="muted">Quantidade de volumes</label>
            <input id="volumesQtd" type="number" min="0" step="1" value="0" />
          </div>
          <div>
            <label class="muted">Detalhes dos volumes</label>
            <input id="volumesDetalhes" type="text" placeholder="Espécie, marca, numeração" />
          </div>
        </div>
        <div class="grid" style="grid-template-columns: 1fr 1fr; gap:.5rem; margin-top:.5rem;">
          <div>
            <label class="muted">Observações</label>
            <input id="deliveryNotes" type="text" placeholder="Instruções de entrega/retirada" />
          </div>
          <div>
            <label class="muted">Volumes</label>
            <input id="deliveryVolumes" type="text" placeholder="Qtd/Notas sobre volumes" />
          </div>
        </div>
      </div>
    </div>
  </section>

  <!-- Diálogo: Nova Transportadora -->
  <dialog id="carrierNewDialog">
    <form method="dialog" id="carrierNewForm" style="min-width:520px;">
      <h3>Nova Transportadora</h3>
      <div id="carrierNewAlert" class="alert" style="display:none;"></div>
      <div class="grid" style="grid-template-columns: 1fr 1fr; gap:.5rem;">
        <div>
          <label class="muted">Nome *</label>
          <input id="carrier_nome" type="text" required placeholder="Informe o nome" />
        </div>
        <div>
          <label class="muted">CNPJ</label>
          <input id="carrier_cnpj" type="text" maxlength="18" placeholder="00.000.000/0000-00" />
        </div>
        <div>
          <label class="muted">E-mail</label>
          <input id="carrier_email" type="email" placeholder="email@transportadora.com" />
        </div>
        <div>
          <label class="muted">Telefone</label>
          <input id="carrier_telefone" type="text" placeholder="(00) 0000-0000" />
        </div>
      </div>
      <div style="display:flex;justify-content:flex-end;gap:.5rem;margin-top:.75rem;">
        <button type="submit" class="btn">Salvar</button>
        <button type="button" class="btn btn-secondary" onclick="document.getElementById('carrierNewDialog').close()">Cancelar</button>
      </div>
    </form>
  </dialog>

  <!-- 5. Observações -->
  <section class="card">
    <h2>Observações</h2>
    <div>
      <label class="muted">Observações do pedido</label>
      <textarea id="orderNotes" rows="4" placeholder="Informações adicionais, condições, garantias"></textarea>
    </div>
  </section>

  <dialog id="previewDialog">
    <form method="dialog">
      <h3>Pré-visualização</h3>
      <div id="previewContent" style="max-height:55vh; overflow:auto;"></div>
      <div style="margin-top:.75rem; display:flex; justify-content:flex-end; gap:.5rem;">
        <button class="btn btn-secondary">Fechar</button>
        <button type="button" class="btn" onclick="printPreview()">Imprimir</button>
      </div>
    </form>
  </dialog>

  <!-- Diálogo: Enviar por e-mail -->
  <dialog id="emailDialog">
    <form method="dialog" id="emailForm" style="min-width:460px;">
      <h3>Enviar Pedido por E-mail</h3>
      <div class="form-group">
        <label class="muted">Para</label>
        <input id="emailTo" type="email" placeholder="cliente@exemplo.com" />
        <p class="muted" style="margin-top:.25rem;">Pré-preenchido com o e-mail do cliente selecionado.</p>
      </div>
      <div style="display:flex;justify-content:flex-end;gap:.5rem;">
        <button id="btnEmailSend" type="button" class="btn">Enviar</button>
        <button type="submit" class="btn btn-secondary">Cancelar</button>
      </div>
    </form>
  </dialog>

  <!-- Diálogo: Pesquisa avançada de produtos -->
  <dialog id="productSearchDialog">
    <form method="dialog" style="min-width:720px;">
      <h3>Pesquisa de Produtos</h3>
      <div style="display:flex;gap:0.5rem;align-items:end;flex-wrap:wrap;">
        <div style="flex:1;min-width:280px;">
          <label class="muted">Termo</label>
          <input id="psdInput" type="text" placeholder="Nome, código, EAN" />
        </div>
        <div>
          <label class="muted">Qtd padrão</label>
          <input id="psdQty" type="number" min="1" value="1" />
        </div>
        <button id="psdSearchBtn" type="button" class="btn">Buscar</button>
        <button type="submit" class="btn btn-secondary">Fechar</button>
      </div>
      <div id="psdResults" style="margin-top:.75rem; max-height:50vh; overflow:auto; display:flex; flex-direction:column; gap:0.5rem;"></div>
    </form>
  </dialog>
</main>

<script>
function fmtBRL(n){ return (Number(n)||0).toLocaleString('pt-BR', { style:'currency', currency:'BRL' }); }
function showMsg(msg, type='info'){ if(window.showAlert) return showAlert(msg, type); alert(msg); }

let selectedClient = null;
let selectedClientEmail = '';
let items = [];
let createdOrderId = null;

const api = {
  clients: (q, per=5) => `/api/clientes?q=${encodeURIComponent(q)}&per_page=${per}`,
  clientById: (id) => `/api/clientes/${id}`,
  products: (q, per=10) => `/api/produtos?q=${encodeURIComponent(q)}&per_page=${per}`,
  orderCreate: '/api/vendas/pedidos',
  orderGet: (id) => `/api/vendas/pedidos/${id}`,
  orderEmail: (id) => `/api/vendas/pedidos/${id}/email`,
  ordersByClient: (cid) => `/api/vendas/pedidos?cliente_id=${cid}`,
  carriers: (limit=100) => `/api/cadastros/transportadoras?q=&limit=${limit}`,
  carrierCreate: '/api/cadastros/transportadoras'
};

document.getElementById('btnClientLookup').addEventListener('click', async () => {
  const q = document.getElementById('clientSearch').value.trim();
  if(!q){ showMsg('Informe um termo para buscar clientes', 'warning'); return; }
  const res = await apiRequest(api.clients(q)); const js = await res.json(); const list = (js.data||[]);
  const html = list.map(c => `<div class="list-item" style="display:flex;justify-content:space-between;align-items:center;gap:.5rem;">
    <div><strong>${c.nome||c.razao_social||'-'}</strong><div class="muted">${c.email||''} · ${c.cnpj||c.cpf||''}</div></div>
    <button onclick="selectClient(${c.id})">Selecionar</button></div>`).join('');
  document.getElementById('clientResults').innerHTML = html || '<div class="muted">Nenhum cliente encontrado</div>';
});

// Autocomplete de clientes ao digitar (≥3 caracteres)
let clientDebounce;
document.getElementById('clientSearch').addEventListener('input', () => {
  const q = document.getElementById('clientSearch').value.trim();
  clearTimeout(clientDebounce);
  clientDebounce = setTimeout(async () => {
    if(q.length < 3){ document.getElementById('clientResults').innerHTML = ''; return; }
    try {
      const res = await apiRequest(api.clients(q, 6));
      const js = await res.json();
      const list = js.data||[];
      const html = list.map(c => `<div class='list-item' style='display:flex;justify-content:space-between;align-items:center;gap:.5rem;'>
        <div><strong>${c.nome||c.razao_social||'-'}</strong><div class='muted'>${c.email||''} · ${c.cnpj||c.cpf||''}</div></div>
        <button onclick='selectClient(${c.id})'>Selecionar</button></div>`).join('');
      document.getElementById('clientResults').innerHTML = html || '<div class="muted">Nenhum cliente encontrado</div>';
    } catch(e){ document.getElementById('clientResults').innerHTML = '<div class="muted">Erro ao buscar clientes</div>'; }
  }, 300);
});

window.selectClient = async function(id){
  const res = await apiRequest(api.clientById(id)); const js = await res.json(); const c = js.data||{}; selectedClient = c; selectedClientEmail = c.email||'';
  const resumoHtml = `
    <div class='grid' style='grid-template-columns: 1fr 2fr; gap:.25rem;'>
      <div class='muted'>Razão Social</div><div>${c.razao_social||'-'}</div>
      <div class='muted'>Nome Fantasia</div><div>${c.nome||'-'}</div>
      <div class='muted'>CNPJ/CPF</div><div>${c.cnpj||c.cpf||'-'}</div>
      <div class='muted'>Inscrição Estadual</div><div>${c.inscricao_estadual||c.ie||'-'}</div>
      <div class='muted'>Telefone</div><div>${c.telefone||'-'}</div>
      <div class='muted'>E-mail</div><div>${c.email||'-'}</div>
      <div class='muted'>Endereço</div><div>${[c.endereco,c.numero,c.bairro,c.cidade,c.uf,c.cep].filter(Boolean).join(', ')||'-'}</div>
    </div>`;
  document.getElementById('clientSummary').innerHTML = resumoHtml;
  // Limpa sugestões e preenche o campo de busca com o nome
  document.getElementById('clientResults').innerHTML = '';
  if(c.nome||c.razao_social) document.getElementById('clientSearch').value = c.nome||c.razao_social;
  loadClientHistory(c.id);
  validateAll();
};

document.getElementById('btnNewClient').addEventListener('click', async () => {
  const nome = prompt('Nome do cliente'); if(!nome) return;
  const email = prompt('E-mail (opcional)')||'';
  try {
    const res = await apiRequest('/api/clientes', { method:'POST', body: JSON.stringify({ nome, email }) });
    if(!res.ok){ const er = await res.json().catch(()=>({})); showMsg('Falha ao criar cliente: ' + (er.error?.message||res.status), 'error'); return; }
    const js = await res.json(); const id = (js.data||{}).id; if(id) selectClient(id);
  } catch(e){ showMsg('Erro ao criar cliente', 'error'); }
});

async function loadClientHistory(cid){
  try{ const res = await apiRequest(api.ordersByClient(cid)); const js = await res.json(); const rows = (js.data||[]).slice(0,5);
    const html = rows.map(r => `<div class='muted'>#${r.id||r.numero} · ${fmtBRL((r.valor_total||0))} · ${r.status||''}</div>`).join('');
    document.getElementById('clientHistory').innerHTML = html || '<div class="muted">Sem histórico recente</div>';
  }catch(e){ document.getElementById('clientHistory').innerHTML = '<div class="muted">Erro ao carregar histórico</div>'; }
}

// Utilitário: converter produto em item do pedido
function productToItem(p, qty){
  return {
    product_id: Number(p.id),
    code: p.codigo||'',
    name: String(p.nome||'-'),
    unit_price: Number(p.preco||0),
    quantity: Math.max(1, Number(qty||1)),
    stock: Number(p.estoque ?? 0),
    packaging: p.embalagem||'',
    photo: p.foto||'',
    discount_percent: 0,
    st_value: 0,
    ipi_value: 0,
    obs: ''
  };
}

window.addProductObj = function(p, qty){
  const row = productToItem(p, qty);
  items.push(row); renderItems(); validateAll();
};

document.getElementById('btnAddItem').addEventListener('click', async () => {
  const q = document.getElementById('productSearch').value.trim();
  const qty = Number(document.getElementById('itemQty').value||'1');
  if(!q){ showMsg('Informe um termo para buscar produtos', 'warning'); return; }
  if(qty <= 0){ showMsg('Quantidade deve ser maior que zero', 'warning'); return; }
  const res = await apiRequest(api.products(q, 10)); const js = await res.json(); const list = (js.data||[]);
  const html = list.map(p => {
    const loc = [p.location_corredor, p.location_prateleira, p.location_posicao].filter(Boolean).join(' / ');
    const img = p.foto ? `<img src='${p.foto}' alt='' style='width:32px;height:32px;object-fit:cover;border-radius:4px;'/>` : `<div class='muted' style='width:32px;height:32px;display:flex;align-items:center;justify-content:center;border:1px solid #ccc;'>—</div>`;
    return `<div class='list-item' style='display:flex;justify-content:space-between;gap:.5rem;align-items:center;'>
      <div style='display:flex;align-items:center;gap:.5rem;'>${img}
        <div>
          <strong>${p.nome||'-'}</strong>
          <div class='muted'>${p.codigo||''} · ${p.codigo_barras||''}${loc?` · Localização: ${loc}`:''}</div>
        </div>
      </div>
      <div class='muted'>Estoque: ${p.estoque ?? '-'}</div>
      <div class='right' style='min-width:100px;'>${fmtBRL(p.preco||0)}</div>
      <button class='btn' data-role='add' data-p='${encodeURIComponent(JSON.stringify(p))}'>Adicionar</button>
    </div>`;
  }).join('');
  const box = document.getElementById('productResults');
  box.innerHTML = html || '<div class="muted">Nenhum produto encontrado</div>';
  box.querySelectorAll('[data-role="add"]').forEach(btn => {
    btn.addEventListener('click', () => {
      const p = JSON.parse(decodeURIComponent(btn.getAttribute('data-p')));
      addProductObj(p, qty);
    });
  });
});

// Usabilidade: Enter no campo de busca de produto aciona confirmar
document.getElementById('productSearch').addEventListener('keydown', (ev)=>{
  if(ev.key === 'Enter'){ ev.preventDefault(); document.getElementById('btnAddItem').click(); }
});

// Autocomplete de produto ao digitar (>=3 caracteres)
let prodDebounce;
document.getElementById('productSearch').addEventListener('input', ()=>{
  clearTimeout(prodDebounce);
  const q = document.getElementById('productSearch').value.trim();
  prodDebounce = setTimeout(async ()=>{
    if(q.length < 3){ document.getElementById('productResults').innerHTML = ''; return; }
    try{
      const res = await apiRequest(api.products(q, 10)); const js = await res.json(); const list = js.data||[];
      const qty = Number(document.getElementById('itemQty').value||'1');
      const html = list.map(p => {
        const loc = [p.location_corredor, p.location_prateleira, p.location_posicao].filter(Boolean).join(' / ');
        const img = p.foto ? `<img src='${p.foto}' alt='' style='width:32px;height:32px;object-fit:cover;border-radius:4px;'/>` : `<div class='muted' style='width:32px;height:32px;display:flex;align-items:center;justify-content:center;border:1px solid #ccc;'>—</div>`;
        return `<div class='list-item' style='display:flex;justify-content:space-between;gap:.5rem;align-items:center;'>
          <div style='display:flex;align-items:center;gap:.5rem;'>${img}
            <div>
              <strong>${p.nome||'-'}</strong>
              <div class='muted'>${p.codigo||''} · ${p.codigo_barras||''}${loc?` · Localização: ${loc}`:''}</div>
            </div>
          </div>
          <div class='muted'>Estoque: ${p.estoque ?? '-'}</div>
          <div class='right' style='min-width:100px;'>${fmtBRL(p.preco||0)}</div>
          <button class='btn' data-role='add' data-p='${encodeURIComponent(JSON.stringify(p))}'>Adicionar</button>
        </div>`;
      }).join('');
      const box = document.getElementById('productResults');
      box.innerHTML = html || '<div class="muted">Nenhum produto encontrado</div>';
      box.querySelectorAll('[data-role="add"]').forEach(btn => {
        btn.addEventListener('click', () => {
          const p = JSON.parse(decodeURIComponent(btn.getAttribute('data-p')));
          addProductObj(p, qty);
        });
      });
    }catch(e){ document.getElementById('productResults').innerHTML = '<div class="muted">Erro na busca</div>'; }
  }, 350);
});

document.getElementById('btnClearProductSearch').addEventListener('click', ()=>{
  document.getElementById('productSearch').value = '';
  document.getElementById('productResults').innerHTML = '';
});

// Pesquisa avançada: abrir modal
document.getElementById('btnOpenProductSearch').addEventListener('click', ()=>{
  const dlg = document.getElementById('productSearchDialog');
  document.getElementById('psdResults').innerHTML = '';
  dlg.showModal();
  document.getElementById('psdInput').focus();
});

async function psdQueryProducts(q){
  const res = await apiRequest(api.products(q, 20));
  const js = await res.json();
  const list = js.data||[];
  const html = list.map(p => {
    const img = p.foto ? `<img src='${p.foto}' alt='' style='width:40px;height:40px;object-fit:cover;border-radius:4px;'/>` : `<div class='muted' style='width:40px;height:40px;display:flex;align-items:center;justify-content:center;border:1px solid #ccc;'>—</div>`;
    const loc = [p.location_corredor, p.location_prateleira, p.location_posicao].filter(Boolean).join(' / ');
    return `<div class='card' style='padding:8px; display:flex; align-items:center; gap:8px;'>
      ${img}
      <div style='flex:1;'>
        <div><strong>${p.nome||'-'}</strong></div>
        <div class='muted'>${p.codigo||''} · ${p.codigo_barras||''}${loc?` · Localização: ${loc}`:''}</div>
      </div>
      <div class='right' style='min-width:120px;'>${fmtBRL(p.preco||0)}</div>
      <div class='muted' style='min-width:90px;'>Estoque: ${p.estoque ?? '-'}</div>
      <div><input type='number' min='1' value='${Number(document.getElementById('psdQty').value||1)}' data-role='qty' style='width:80px;' /></div>
      <div><button class='btn' data-role='add' data-p='${encodeURIComponent(JSON.stringify({ id:p.id, nome:p.nome, preco:p.preco }))}'>Adicionar</button></div>
    </div>`;
  }).join('');
  const box = document.getElementById('psdResults');
  box.innerHTML = html || '<div class="muted">Nenhum produto encontrado</div>';
  box.querySelectorAll('[data-role="add"]').forEach(btn => {
    btn.addEventListener('click', () => {
      const p = JSON.parse(decodeURIComponent(btn.getAttribute('data-p')));
      const qtyEl = btn.closest('.card').querySelector('[data-role="qty"]');
      const qty = Number(qtyEl?.value||document.getElementById('psdQty').value||1);
      addItemWithQty(p.id, p.nome, p.preco, qty);
    });
  });
}

document.getElementById('psdSearchBtn').addEventListener('click', ()=>{
  const q = document.getElementById('psdInput').value.trim();
  if(!q){ showMsg('Informe um termo para buscar produtos', 'warning'); return; }
  psdQueryProducts(q);
});

let psdDebounce;
document.getElementById('psdInput').addEventListener('input', ()=>{
  const q = document.getElementById('psdInput').value.trim();
  clearTimeout(psdDebounce);
  psdDebounce = setTimeout(()=>{ if(q.length >= 3) psdQueryProducts(q); else document.getElementById('psdResults').innerHTML = ''; }, 350);
});

// Adicionar item com quantidade específica (usado pelo modal)
window.addItemWithQty = function(pid, name, unitPrice, qty){
  const row = productToItem({ id: pid, nome: name, preco: unitPrice }, qty);
  items.push(row); renderItems(); validateAll();
};

window.addItem = function(pid, name, unitPrice){
  const qty = Number(document.getElementById('itemQty').value||'1');
  const row = productToItem({ id: pid, nome: name, preco: unitPrice }, qty);
  items.push(row); renderItems(); validateAll();
};

function getFilteredItems(){
  const filter = (document.getElementById('itemsFilter')?.value||'').trim().toLowerCase();
  const sort = (document.getElementById('itemsSort')?.value||'nome');
  let list = items.filter(it => {
    if(!filter) return true;
    const s = `${it.name||''} ${it.code||''}`.toLowerCase();
    return s.includes(filter);
  });
  if(sort === 'nome') list.sort((a,b)=> String(a.name||'').localeCompare(String(b.name||'')));
  else if(sort === 'preco') list.sort((a,b)=> Number(a.unit_price||0) - Number(b.unit_price||0));
  else if(sort === 'estoque') list.sort((a,b)=> Number(a.stock||0) - Number(b.stock||0));
  return list;
}

function renderItems(){
  const list = getFilteredItems();
  if(items.length === 0){ document.getElementById('itemsRows').innerHTML = '<tr><td colspan="12" class="muted">Nenhum item</td></tr>'; updateTotals(); return; }
  if(list.length === 0){ document.getElementById('itemsRows').innerHTML = '<tr><td colspan="12" class="muted">Nenhum item corresponde ao filtro</td></tr>'; updateTotals(); return; }
  const html = list.map((it, idx) => {
    const img = it.photo ? `<img src='${it.photo}' alt='' style='width:40px;height:40px;object-fit:cover;border-radius:4px;'/>` : `<div class='muted' style='width:40px;height:40px;display:flex;align-items:center;justify-content:center;border:1px solid #ccc;'>—</div>`;
    const base = (it.quantity * it.unit_price) * (1 - (Number(it.discount_percent||0)/100));
    const subtotal = base + Number(it.st_value||0) + Number(it.ipi_value||0);
    return `<tr>
      <td>${img}</td>
      <td>${it.code||''}</td>
      <td>${it.name||''}</td>
      <td class='right'>${it.stock ?? ''}</td>
      <td>${it.packaging||''}</td>
      <td class='right'><input class='cell-input' type='number' min='0' step='0.01' value='${it.unit_price}' onchange='updatePrice(${idx}, this.value)' /></td>
      <td class='right'><input class='cell-input' type='number' min='1' value='${it.quantity}' onchange='updateQty(${idx}, this.value)' /></td>
      <td class='right'><input class='cell-input' type='number' min='0' step='0.01' value='${it.st_value||0}' onchange='updateST(${idx}, this.value)' /></td>
      <td class='right'><input class='cell-input' type='number' min='0' step='0.01' value='${it.ipi_value||0}' onchange='updateIPI(${idx}, this.value)' /></td>
      <td><input class='cell-input' type='text' value='${it.obs||''}' onchange='updateObs(${idx}, this.value)' placeholder='Observação do item' /></td>
      <td class='right'>${fmtBRL(subtotal)}</td>
      <td><button class='btn btn-secondary' title='Remover item' onclick='removeItem(${idx})'>🗑️ Remover</button></td>
    </tr>`;
  }).join('');
  document.getElementById('itemsRows').innerHTML = html;
  updateTotals();
}

window.updateQty = function(idx, v){ items[idx].quantity = Math.max(1, Number(v||1)); renderItems(); };
window.updatePrice = function(idx, v){ items[idx].unit_price = Math.max(0, Number(v||0)); renderItems(); };
window.updateDiscount = function(idx, v){ items[idx].discount_percent = Math.min(100, Math.max(0, Number(v||0))); renderItems(); };
window.updateST = function(idx, v){ items[idx].st_value = Math.max(0, Number(v||0)); renderItems(); };
window.updateIPI = function(idx, v){ items[idx].ipi_value = Math.max(0, Number(v||0)); renderItems(); };
window.updateObs = function(idx, v){ items[idx].obs = String(v||''); };
window.removeItem = function(idx){ items.splice(idx,1); renderItems(); validateAll(); };

function updateTotals(){
  const subtotalBase = items.reduce((acc, it) => acc + (it.quantity * it.unit_price) * (1 - (Number(it.discount_percent||0)/100)), 0);
  const desc = Math.min(100, Math.max(0, Number(document.getElementById('discountGlobal')?.value||0)));
  const mark = Math.min(100, Math.max(0, Number(document.getElementById('markupGlobal')?.value||0)));
  const subtotal = round2(subtotalBase * (1 - desc/100) * (1 + mark/100));
  const freteVal = Number(document.getElementById('freteValue').value||0);
  const frete = (document.getElementById('freteSomar')?.checked ?? true) ? round2(freteVal) : 0;
  const impostos = round2(Math.max(0, subtotal * 0.12));
  const total = round2(subtotal + impostos + frete);
  document.getElementById('totalsBox').textContent = `Subtotal: ${fmtBRL(subtotal)} · Impostos: ${fmtBRL(impostos)} · Frete: ${fmtBRL(frete)} · Total: ${fmtBRL(total)}`;
  // Recalcula parcelas sempre que totais mudarem
  updateInstallmentsRealtime();
}

['discountGlobal','discountValue','markupGlobal','markupValue','freteValue','freteSomar'].forEach(id => {
  document.getElementById(id)?.addEventListener('input', updateTotals);
  document.getElementById(id)?.addEventListener('change', updateTotals);
});

['itemsFilter','itemsSort'].forEach(id => {
  document.getElementById(id)?.addEventListener('input', renderItems);
  document.getElementById(id)?.addEventListener('change', renderItems);
});

// Estilos de melhoria UX na tabela de itens
(function(){
  const css = `
    .table td input.cell-input{ width: 100%; max-width: 120px; }
    .table td input.cell-input[type=text]{ max-width: 160px; }
    .table td .btn.btn-secondary{ padding: .25rem .5rem; font-size: .9rem; }
    .table thead th{ white-space: nowrap; }
  `;
  const style = document.createElement('style'); style.textContent = css; document.head.appendChild(style);
})();

const payMethodEl = document.getElementById('payMethod');
payMethodEl.addEventListener('change', renderPayFields);
function renderPayFields(){
  const m = payMethodEl.value;
  let html = '';
  if(m === 'parcelado'){
    html = `<label class='muted'>Parcelas</label><input id='payInstallments' type='number' min='2' value='2' />`;
  } else if(m === 'cartao'){
    html = `<label class='muted'>Bandeira</label><input id='payCardBrand' type='text' placeholder='Visa, MasterCard...' />`;
  } else if(m === 'pix'){
    html = `<label class='muted'>Chave PIX</label><input id='payPixKey' type='text' placeholder='e-mail/telefone/aleatória' />`;
  } else if(m === 'boleto'){
    html = `<label class='muted'>Dias para vencimento</label><input id='payBoletoDays' type='number' min='1' value='7' />`;
  } else if(m === 'transferencia'){
    html = `<label class='muted'>Banco/Agência</label><input id='payBank' type='text' placeholder='Banco e agência para transferência' />`;
  } else {
    html = `<small class='muted'>Pagamento à vista.</small>`;
  }
  document.getElementById('payFields').innerHTML = html;
}
renderPayFields();

const deliveryOptionEl = document.getElementById('deliveryOption');
deliveryOptionEl.addEventListener('change', () => {
  document.getElementById('deliveryAddrBox').style.display = (deliveryOptionEl.value === 'entrega') ? 'block' : 'none';
});
document.getElementById('deliveryAddrBox').style.display = 'none';

// Transportadoras: carregar e cadastrar
function carrierAlert(msg, type='warning'){
  const box = document.getElementById('carrierNewAlert'); if(!box) return;
  box.textContent = msg||''; box.style.display = msg? 'block':'none';
  box.className = `alert ${type==='error'?'alert-error':type==='success'?'alert-success':'alert-warning'}`;
}

async function initCarriers(){
  try{
    const sel = document.getElementById('carrierSelect'); if(!sel) return;
    const res = await apiRequest(api.carriers(200)); const js = await res.json(); const list = js.data||[];
    sel.innerHTML = `<option value=''>— Selecionar —</option>` + list.map(c => `<option value='${c.id}'>${c.nome||'-'}</option>`).join('');
  }catch(e){ /* silencioso */ }
}

document.getElementById('newCarrierBtn')?.addEventListener('click', () => {
  document.getElementById('carrierNewDialog').showModal();
});

document.getElementById('carrierNewForm')?.addEventListener('submit', async (e) => {
  e.preventDefault(); carrierAlert('');
  const nome = (document.getElementById('carrier_nome').value||'').trim();
  const cnpj = (document.getElementById('carrier_cnpj').value||'').trim();
  const email = (document.getElementById('carrier_email').value||'').trim();
  const telefone = (document.getElementById('carrier_telefone').value||'').trim();
  if(!nome){ carrierAlert('Nome é obrigatório'); return; }
  try{
    const body = { nome };
    if(cnpj) body.cnpj = cnpj; if(email) body.email = email; if(telefone) body.telefone = telefone;
    const res = await apiRequest(api.carrierCreate, { method:'POST', body: JSON.stringify(body) });
    const js = await res.json().catch(()=>({})); if(!res.ok){ carrierAlert(js.error?.message || 'Falha ao salvar', 'error'); return; }
    const sel = document.getElementById('carrierSelect');
    const id = (js.data||{}).id || js.id;
    if(sel && id){ const opt = document.createElement('option'); opt.value = String(id); opt.textContent = nome; sel.appendChild(opt); sel.value = String(id); }
    document.getElementById('carrierNewDialog').close(); carrierAlert('');
  }catch(err){ carrierAlert('Erro ao salvar', 'error'); }
});

if(typeof apiRequest === 'function'){ initCarriers(); }

// ===== Parcelas: geração em tempo real a partir da condição de pagamento =====
function round2(n){ return Math.round((Number(n)||0) * 100) / 100; }
function formatDateBR(date){
  const d = new Date(date);
  const dd = String(d.getDate()).padStart(2,'0');
  const mm = String(d.getMonth()+1).padStart(2,'0');
  const yyyy = d.getFullYear();
  return `${dd}/${mm}/${yyyy}`;
}
function addDays(dateStr, days){
  if(!dateStr) return '';
  const d = new Date(dateStr);
  d.setDate(d.getDate() + Number(days||0));
  return formatDateBR(d);
}
function parsePayCondition(str){
  const parts = String(str||'').split('|');
  const daysPart = (parts[0]||'').trim();
  const percPart = (parts[1]||'').trim();
  const days = daysPart.split(/[\/;,\s]+/).map(s=>Number(s)).filter(n=>!isNaN(n) && n>=0);
  const discountPercent = parseFloat(percPart.replace('%','').replace(',','.')) || 0;
  return { days, discountPercent: Math.max(0, discountPercent) };
}
function getOrderTotal(){
  const subtotalBase = items.reduce((acc, it) => acc + (it.quantity * it.unit_price) * (1 - (Number(it.discount_percent||0)/100)), 0);
  const desc = Math.min(100, Math.max(0, Number(document.getElementById('discountGlobal')?.value||0)));
  const mark = Math.min(100, Math.max(0, Number(document.getElementById('markupGlobal')?.value||0)));
  const subtotal = round2(subtotalBase * (1 - desc/100) * (1 + mark/100));
  const freteVal = Number(document.getElementById('freteValue').value||0);
  const frete = (document.getElementById('freteSomar')?.checked ?? true) ? round2(freteVal) : 0;
  const impostos = round2(Math.max(0, subtotal * 0.12));
  return { subtotal, impostos, frete, total: round2(subtotal + frete + impostos) };
}
function updateInstallmentsRealtime(){
  const cond = parsePayCondition(document.getElementById('payCondition')?.value||'');
  const issue = document.getElementById('issueDate')?.value||'';
  const box = document.getElementById('installmentsBox');
  const tbody = document.querySelector('#installmentsBox tbody');
  if(!tbody || !box) return;
  if(!cond.days.length || !issue){ box.style.display='none'; tbody.innerHTML=''; return; }
  const totals = getOrderTotal();
  const base = totals.total * (1 - (cond.discountPercent/100));
  const per = cond.days.length ? round2(base/cond.days.length) : round2(base);
  const rows = cond.days.map((d,i)=>{
    const venc = addDays(issue, Number(d||0) + 1);
    return `<tr><td>${i+1}</td><td>${venc}</td><td class='right'>${fmtBRL(per)}</td></tr>`;
  }).join('');
  tbody.innerHTML = rows; box.style.display='block';
}
// Geração em tempo real durante digitação
document.getElementById('payCondition')?.addEventListener('input', updateInstallmentsRealtime);
// Também atualiza ao trocar forma de pagamento (por consistência de UI)
document.getElementById('payMethod')?.addEventListener('change', updateInstallmentsRealtime);
// Atualiza ao mudar data de emissão
document.getElementById('issueDate')?.addEventListener('change', updateInstallmentsRealtime);
// Inicializa data de emissão e cálculos
(function initIssueDateAndTotals(){
  const issueEl = document.getElementById('issueDate');
  if(issueEl && !issueEl.value){ issueEl.value = new Date().toISOString().slice(0,10); }
  updateTotals();
  updateInstallmentsRealtime();
})();

function validateAll(){
  const okClient = !!selectedClient?.id;
  const okItems = items.length > 0 && items.every(it => it.quantity > 0 && it.unit_price >= 0);
  document.getElementById('btnSave').disabled = !(okClient && okItems);
  document.getElementById('btnPreview').disabled = !okItems;
  document.getElementById('btnPrint').disabled = !okItems;
}
validateAll();

document.getElementById('btnPreview').addEventListener('click', () => {
  const html = generatePreviewHtml();
  document.getElementById('previewContent').innerHTML = html; document.getElementById('previewDialog').showModal();
});

function generatePreviewHtml(){
  const subtotal = items.reduce((acc, it) => acc + (it.quantity * it.unit_price) * (1 - (it.discount_percent||0)/100), 0);
  const impostos = subtotal * 0.12; const frete = Number(document.getElementById('freteValue').value||0); const total = subtotal+impostos+frete;
  const cliente = selectedClient||{};
  const issueRaw = document.getElementById('issueDate').value||'';
  const emissaoStr = issueRaw ? formatDateBR(issueRaw) : new Date().toLocaleDateString('pt-BR');
  const itensRows = items.map((it, i) => {
    const tot = (it.quantity * it.unit_price) * (1 - (it.discount_percent||0)/100);
    return `<tr>
      <td>${String(i+1).padStart(3,'0')}</td>
      <td>${it.code||''}</td>
      <td>${it.name}</td>
      <td class='right'>${it.quantity}</td>
      <td class='right'>${fmtBRL(it.unit_price)}</td>
      <td class='right'>${Number(it.discount_percent||0).toFixed(2)}%</td>
      <td class='right'>${fmtBRL(tot)}</td>
    </tr>`;
  }).join('');
  return `
  <style>
    @page { size: A4; margin: 10mm; }
    @media print { body { -webkit-print-color-adjust: exact; print-color-adjust: exact; } }
    .danfe-wrap{ width: 190mm; margin: 0 auto; }
    .danfe-box{border:1px solid #000;padding:6px;margin-bottom:6px;}
    .danfe-grid{display:grid;grid-template-columns:2fr 1fr;gap:6px;}
    .right{text-align:right;}
    .center{text-align:center;}
    .muted{color:#555;}
    .danfe-table{width:100%;border-collapse:collapse; table-layout: fixed;}
    .danfe-table th, .danfe-table td{border:1px solid #000;padding:4px;font-size:12px;}
    .danfe-table thead th{ background:#f2f2f2; }
    .danfe-table th:nth-child(1), .danfe-table td:nth-child(1){ width:8%; }
    .danfe-table th:nth-child(2), .danfe-table td:nth-child(2){ width:12%; }
    .danfe-table th:nth-child(3), .danfe-table td:nth-child(3){ width:44%; word-break: break-word; }
    .danfe-table th:nth-child(4), .danfe-table td:nth-child(4){ width:8%; }
    .danfe-table th:nth-child(5), .danfe-table td:nth-child(5){ width:12%; }
    .danfe-table th:nth-child(6), .danfe-table td:nth-child(6){ width:6%; }
    .danfe-table th:nth-child(7), .danfe-table td:nth-child(7){ width:10%; }
    .danfe-header{display:flex;justify-content:space-between;align-items:center;}
  </style>
  <div class='danfe-wrap'>
  <div class='danfe-box'>
    <div class='danfe-header'>
      <div>
        <div><strong>CÓPIA DO PEDIDO</strong></div>
        <div class='muted'>Layout inspirado em DANFE (NF-e)</div>
      </div>
      <div class='right'>
        <div><strong>Nº ${createdOrderId||'-'}</strong></div>
        <div>Emissão: ${emissaoStr}</div>
      </div>
    </div>
  </div>
  <div class='danfe-grid'>
    <div class='danfe-box'>
      <div><strong>Destinatário</strong></div>
      <div>${cliente.nome||cliente.razao_social||'-'}</div>
      <div class='muted'>${cliente.email||''}</div>
      <div class='muted'>${[cliente.endereco,cliente.numero,cliente.bairro,cliente.cidade,cliente.uf,cliente.cep].filter(Boolean).join(', ')}</div>
      <div class='muted'>${cliente.cnpj||cliente.cpf||''}</div>
    </div>
    <div class='danfe-box'>
      <div><strong>Transporte</strong></div>
      <div class='muted'>${document.getElementById('deliveryOption').value} · Frete: ${fmtBRL(frete)}</div>
      <div class='muted'>Entrega: ${document.getElementById('deliveryDate').value ? formatDateBR(document.getElementById('deliveryDate').value) : '-'}</div>
      <div class='muted'>Endereço: ${document.getElementById('deliveryAddress').value||'-'}</div>
    </div>
  </div>
  <div class='danfe-box'>
    <div><strong>Itens</strong></div>
    <table class='danfe-table'>
      <thead>
        <tr><th>Item</th><th>Código</th><th>Descrição</th><th>Qtd</th><th>Unitário</th><th>Desc%</th><th>Total</th></tr>
      </thead>
      <tbody>${itensRows}</tbody>
    </table>
  </div>
  <div class='danfe-grid'>
    <div class='danfe-box'>
      <div><strong>Observações</strong></div>
      <div class='muted'>${document.getElementById('orderNotes').value||''}</div>
    </div>
    <div class='danfe-box right'>
      <div><strong>Totais</strong></div>
      <div>Subtotal: ${fmtBRL(subtotal)}</div>
      <div>Impostos: ${fmtBRL(impostos)}</div>
      <div>Frete: ${fmtBRL(frete)}</div>
      <div><strong>Total: ${fmtBRL(total)}</strong></div>
    </div>
  </div>
  </div>`;
}

function printPreview(){
  // Gera HTML e imprime apenas o conteúdo da prévia com segurança
  const html = generatePreviewHtml();
  try {
    const w = window.open('', 'PRINT', 'width=900,height=700');
    w.document.write('<html><head><title>Imprimir Pedido</title><style>@media print { body{margin:0; } }</style></head><body>' + html + '</body></html>');
    w.document.close(); w.focus();
    if (window.PrintControl && typeof PrintControl.safeWindowPrint === 'function') {
      PrintControl.safeWindowPrint(w, { copies: 1 });
    } else {
      // Fallback
      try { w.print(); } catch(e){ try{ window.print(); }catch(__){} }
      try { w.close(); } catch(_){}
    }
  } catch(e){
    console.warn('Falha ao abrir janela de impressão', e);
    try { PrintControl.safePrint({ copies: 1 }); } catch(_){ try{ window.print(); }catch(__){} }
  }
}

// Botão principal de imprimir também usa a mesma rotina da prévia
document.getElementById('btnPrint').addEventListener('click', () => {
  printPreview();
});

// Importação de itens via CSV: codigo;nome;preco;quantidade
document.getElementById('btnImportItems').addEventListener('click', ()=>{
  document.getElementById('importFile').click();
});

async function matchProduct(q){
  try{
    const res = await apiRequest(api.products(q, 1));
    const js = await res.json();
    const p = (js.data||[])[0];
    return p || null;
  }catch(e){ return null; }
}

document.getElementById('importFile').addEventListener('change', async (ev)=>{
  const file = ev.target.files?.[0]; if(!file) return;
  const text = await file.text();
  const lines = text.split(/\r?\n/).filter(l=>l.trim().length>0);
  let added = 0, skipped = 0;
  for(const line of lines){
    const parts = line.split(/[;,\t]/);
    const codigo = (parts[0]||'').trim();
    const nome = (parts[1]||'').trim();
    const precoStr = (parts[2]||'0').trim();
    const qtyStr = (parts[3]||'1').trim();
    const qty = Math.max(1, Number(qtyStr||1));
    let p = null;
    if(codigo){ p = await matchProduct(codigo); }
    if(!p && nome){ p = await matchProduct(nome); }
    if(p){
      addItemWithQty(p.id, p.nome||nome||'-', Number(p.preco ?? precoStr ?? 0), qty);
      added++;
    } else {
      // Sem correspondência: por segurança, não adiciona item sem product_id
      skipped++;
    }
  }
  const msg = `Planilha processada. Itens adicionados: ${added}. Linhas sem produto: ${skipped}.`;
  showMsg(msg, skipped>0? 'warning':'success');
});

// Modelo de Planilha: gerar CSV com cabeçalhos e exemplos
document.getElementById('btnTemplateCSV').addEventListener('click', ()=>{
  const csv = [
    'codigo;nome;preco;quantidade',
    'SKU123;Produto Exemplo 1;49.90;2',
    'SKU456;Produto Exemplo 2;19.90;1'
  ].join('\n');
  const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url; a.download = 'modelo_itens.csv';
  document.body.appendChild(a); a.click(); document.body.removeChild(a);
  URL.revokeObjectURL(url);
});

document.getElementById('btnSave').addEventListener('click', async () => {
  try {
    if(!(selectedClient?.id) || items.length === 0){ showMsg('Selecione cliente e adicione itens', 'warning'); return; }
    const payload = {
      cliente_id: selectedClient.id,
      items: items.map(it => ({ product_id: it.product_id, quantity: it.quantity, unit_price: it.unit_price, discount_percent: it.discount_percent })),
      observacoes: document.getElementById('orderNotes').value || '',
      entrega: {
        tipo: document.getElementById('deliveryOption').value,
        data: document.getElementById('deliveryDate').value || null,
        hora: document.getElementById('deliveryTime').value || null,
        endereco: document.getElementById('deliveryAddress').value || null,
        frete: Number(document.getElementById('freteValue').value||0),
        observacoes: document.getElementById('deliveryNotes').value || '',
        transportadora: (document.getElementById('carrierSelect')?.selectedOptions[0]?.text || null),
        peso_bruto: Number(document.getElementById('pesoBruto').value||0)||0,
        peso_liquido: Number(document.getElementById('pesoLiquido').value||0)||0,
        volumes_qtd: Number(document.getElementById('volumesQtd').value||0)||0,
        volumes_detalhes: document.getElementById('volumesDetalhes').value || null
      },
      pagamento: {
        metodo: document.getElementById('payMethod').value,
        parcelas: Number(document.getElementById('payInstallments')?.value||0)||null,
        cartao_bandeira: document.getElementById('payCardBrand')?.value||null,
        pix_chave: document.getElementById('payPixKey')?.value||null,
        boleto_dias: Number(document.getElementById('payBoletoDays')?.value||0)||null,
        transferencia_banco: document.getElementById('payBank')?.value||null
      }
    };
    const res = await apiRequest(api.orderCreate, { method:'POST', body: JSON.stringify(payload) });
    const js = await res.json().catch(()=>({}));
    if(!res.ok){ showMsg(js.error?.message || 'Falha ao salvar pedido', 'error'); return; }
    createdOrderId = (js.data||{}).id || (js.order?.id);
    showMsg('Pedido salvo com sucesso!', 'success');
    document.getElementById('btnEmail').disabled = !createdOrderId;
  } catch(e){ showMsg('Erro ao salvar pedido', 'error'); }
});

// E-mail: abrir modal e enviar
document.getElementById('btnEmail').addEventListener('click', () => {
  if(!createdOrderId){ showMsg('Salve o pedido antes de enviar por e-mail', 'warning'); return; }
  const dlg = document.getElementById('emailDialog'); const input = document.getElementById('emailTo');
  input.value = selectedClientEmail||'';
  dlg.showModal();
});

document.getElementById('btnEmailSend').addEventListener('click', async () => {
  if(!createdOrderId){ showMsg('Salve o pedido antes de enviar por e-mail', 'warning'); return; }
  const to = (document.getElementById('emailTo').value||'').trim();
  const emailOk = /.+@.+\..+/.test(to);
  if(!emailOk){ showMsg('Informe um e-mail válido', 'warning'); return; }
  const subject = `Pedido ${createdOrderId}`;
  const body = `Olá ${selectedClient?.nome||''},\nSegue seu pedido. Total: consulte o documento.\nObrigado.`;
  try {
    const res = await apiRequest(api.orderEmail(createdOrderId), { method:'POST', body: JSON.stringify({ to, subject, body }) });
    if(!res.ok){ const er = await res.json().catch(()=>({})); showMsg(er.error?.message||'Falha ao enviar e-mail','error'); return; }
    const dlgClose = document.getElementById('emailDialog'); if(dlgClose && typeof dlgClose.close === 'function'){ dlgClose.close(); }
    showMsg('E-mail enviado.', 'success');
  } catch(e){ showMsg('Erro no envio de e-mail', 'error'); }
});
</script>