let stockData = [];
let stockExitsData = [];
let stockEntriesData = [];
let stockBranches = [];
let stockCategories = [];
let stockView = 'items';
let stockFilters = {};

async function loadStockPage() {
    const content = document.getElementById('main-content');
    content.innerHTML = `
        <div class="space-y-6">
            <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
                <h1 class="text-2xl font-bold text-gray-900 dark:text-white">Estoque</h1>
                <div class="flex gap-2">
                    <button onclick="switchStockView('items')" id="stock-view-items" class="px-4 py-2 rounded-lg font-medium transition-colors bg-zinc-800 text-white" data-testid="button-view-items">
                        Itens
                    </button>
                    <button onclick="switchStockView('entries')" id="stock-view-entries" class="px-4 py-2 rounded-lg font-medium transition-colors bg-white text-black border border-gray-300" data-testid="button-view-entries">
                        Entradas
                    </button>
                    <button onclick="switchStockView('exits')" id="stock-view-exits" class="px-4 py-2 rounded-lg font-medium transition-colors bg-white text-black border border-gray-300" data-testid="button-view-exits">
                        Saídas
                    </button>
                </div>
            </div>

            <div id="stock-content"></div>
        </div>
    `;

    try {
        const branchRes = await fetch('api/branches.php', { credentials: 'include' });
        const branchData = await branchRes.json();
        stockBranches = branchData.branches || branchData || [];
    } catch (e) {
        stockBranches = [];
    }

    switchStockView('items');
}

function switchStockView(view) {
    stockView = view;
    const activeClass = 'px-4 py-2 rounded-lg font-medium transition-colors bg-zinc-800 text-white';
    const inactiveClass = 'px-4 py-2 rounded-lg font-medium transition-colors bg-white text-black border border-gray-300';
    document.getElementById('stock-view-items').className = view === 'items' ? activeClass : inactiveClass;
    document.getElementById('stock-view-entries').className = view === 'entries' ? activeClass : inactiveClass;
    document.getElementById('stock-view-exits').className = view === 'exits' ? activeClass : inactiveClass;

    if (view === 'items') {
        renderStockItems();
    } else if (view === 'entries') {
        renderStockEntries();
    } else {
        renderStockExits();
    }
}

async function renderStockItems() {
    const container = document.getElementById('stock-content');
    container.innerHTML = '<div class="flex justify-center items-center h-32"><div class="spinner"></div></div>';

    try {
        const params = new URLSearchParams();
        if (stockFilters.branch_id) params.append('branch_id', stockFilters.branch_id);
        if (stockFilters.category) params.append('category', stockFilters.category);
        if (stockFilters.item_type) params.append('item_type', stockFilters.item_type);
        if (stockFilters.search) params.append('search', stockFilters.search);
        if (stockFilters.low_stock) params.append('low_stock', stockFilters.low_stock);

        const res = await fetch(`api/stock-items.php?${params.toString()}`, { credentials: 'include' });
        const data = await res.json();
        stockData = data.items || [];
        stockCategories = data.categories || [];
    } catch (e) {
        stockData = [];
    }

    const branchOptions = stockBranches.map(b => `<option value="${b.id}" ${stockFilters.branch_id === b.id ? 'selected' : ''}>${b.name}</option>`).join('');
    const categoryOptions = stockCategories.map(c => `<option value="${c}" ${stockFilters.category === c ? 'selected' : ''}>${c}</option>`).join('');

    container.innerHTML = `
        <div class="bg-white dark:bg-zinc-800 rounded-lg shadow p-4 border border-gray-200 dark:border-zinc-700">
            <div class="flex flex-wrap gap-3 items-end">
                <div>
                    <label class="block text-xs font-medium text-gray-500 mb-1">Buscar</label>
                    <input type="text" id="stock-search" placeholder="Nome do item..." value="${stockFilters.search || ''}" onkeyup="if(event.key==='Enter')applyStockFilter()" class="px-3 py-2 border border-gray-300 dark:border-zinc-600 rounded-lg bg-white dark:bg-zinc-700 text-gray-900 dark:text-white text-sm" data-testid="input-stock-search">
                </div>
                <div>
                    <label class="block text-xs font-medium text-gray-500 mb-1">Filial</label>
                    <select id="stock-filter-branch" onchange="applyStockFilter()" class="px-3 py-2 border border-gray-300 dark:border-zinc-600 rounded-lg bg-white dark:bg-zinc-700 text-gray-900 dark:text-white text-sm" data-testid="select-stock-branch">
                        <option value="">Todas</option>
                        ${branchOptions}
                    </select>
                </div>
                <div>
                    <label class="block text-xs font-medium text-gray-500 mb-1">Categoria</label>
                    <select id="stock-filter-category" onchange="applyStockFilter()" class="px-3 py-2 border border-gray-300 dark:border-zinc-600 rounded-lg bg-white dark:bg-zinc-700 text-gray-900 dark:text-white text-sm" data-testid="select-stock-category">
                        <option value="">Todas</option>
                        ${categoryOptions}
                    </select>
                </div>
                <div>
                    <label class="block text-xs font-medium text-gray-500 mb-1">Tipo</label>
                    <select id="stock-filter-type" onchange="applyStockFilter()" class="px-3 py-2 border border-gray-300 dark:border-zinc-600 rounded-lg bg-white dark:bg-zinc-700 text-gray-900 dark:text-white text-sm" data-testid="select-stock-type">
                        <option value="">Todos</option>
                        <option value="unidade" ${stockFilters.item_type === 'unidade' ? 'selected' : ''}>Unidade</option>
                        <option value="caixa" ${stockFilters.item_type === 'caixa' ? 'selected' : ''}>Caixa</option>
                        <option value="kg" ${stockFilters.item_type === 'kg' ? 'selected' : ''}>Kg</option>
                        <option value="litro" ${stockFilters.item_type === 'litro' ? 'selected' : ''}>Litro</option>
                    </select>
                </div>
                <div>
                    <label class="block text-xs font-medium text-gray-500 mb-1">Estoque Baixo ≤</label>
                    <input type="number" id="stock-filter-low" placeholder="Qtd" value="${stockFilters.low_stock || ''}" onchange="applyStockFilter()" class="px-3 py-2 border border-gray-300 dark:border-zinc-600 rounded-lg bg-white dark:bg-zinc-700 text-gray-900 dark:text-white text-sm w-20" data-testid="input-stock-low">
                </div>
                <button onclick="clearStockFilters()" class="px-3 py-2 text-sm text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200" data-testid="button-clear-filters">
                    Limpar Filtros
                </button>
                <div class="ml-auto">
                    <button onclick="openStockItemModal()" class="bg-green-600 hover:bg-green-700 text-white font-medium py-2 px-4 rounded-lg transition-colors flex items-center gap-2" data-testid="button-new-stock-item">
                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path></svg>
                        Novo Item
                    </button>
                </div>
            </div>
        </div>

        <div class="bg-white dark:bg-zinc-800 rounded-lg shadow border border-gray-200 dark:border-zinc-700 overflow-x-auto mt-4">
            <table class="min-w-full divide-y divide-gray-200 dark:divide-zinc-700">
                <thead class="bg-gray-50 dark:bg-zinc-900">
                    <tr>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Nome</th>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Categoria</th>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Tipo</th>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Qtd</th>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Qtd Mín.</th>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">V. Compra</th>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">V. Venda</th>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Filial</th>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Cadastro</th>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Ações</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-200 dark:divide-zinc-700">
                    ${stockData.length === 0 ? `
                        <tr><td colspan="10" class="px-4 py-8 text-center text-gray-500">Nenhum item cadastrado</td></tr>
                    ` : stockData.map(item => `
                        <tr class="hover:bg-gray-50 dark:hover:bg-zinc-700/50" data-testid="row-stock-item-${item.id}">
                            <td class="px-4 py-3 font-medium text-gray-900 dark:text-white">${item.name}</td>
                            <td class="px-4 py-3 text-gray-600 dark:text-gray-300">${item.category || '-'}</td>
                            <td class="px-4 py-3 text-gray-600 dark:text-gray-300">${formatItemType(item.item_type)}</td>
                            <td class="px-4 py-3 font-medium ${parseFloat(item.min_quantity) > 0 && parseFloat(item.quantity) <= parseFloat(item.min_quantity) ? 'text-red-600' : 'text-gray-900 dark:text-white'}">${parseFloat(item.quantity).toLocaleString('pt-BR')}</td>
                            <td class="px-4 py-3 text-gray-600 dark:text-gray-300">${parseFloat(item.min_quantity || 0).toLocaleString('pt-BR')}</td>
                            <td class="px-4 py-3 text-gray-600 dark:text-gray-300">${formatMoney(item.purchase_price)}</td>
                            <td class="px-4 py-3 text-gray-600 dark:text-gray-300">${formatMoney(item.sale_price)}</td>
                            <td class="px-4 py-3 text-gray-600 dark:text-gray-300">${item.branch_name || '-'}</td>
                            <td class="px-4 py-3 text-gray-600 dark:text-gray-300">${formatDateTime(item.created_at)}</td>
                            <td class="px-4 py-3">
                                <div class="flex gap-2">
                                    <button onclick="openStockEntryModal('${item.id}')" class="text-green-500 hover:text-green-700" title="Registrar Entrada" data-testid="button-entry-${item.id}">
                                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 16l-4-4m0 0l4-4m-4 4h14m-5 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1"/></svg>
                                    </button>
                                    <button onclick="openStockExitModal('${item.id}')" class="text-orange-500 hover:text-orange-700" title="Registrar Saída" data-testid="button-exit-${item.id}">
                                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1"/></svg>
                                    </button>
                                    <button onclick="openStockItemModal('${item.id}')" class="text-blue-500 hover:text-blue-700" title="Editar" data-testid="button-edit-${item.id}">
                                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"/></svg>
                                    </button>
                                    <button onclick="deleteStockItem('${item.id}')" class="text-red-500 hover:text-red-700" title="Excluir" data-testid="button-delete-${item.id}">
                                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/></svg>
                                    </button>
                                </div>
                            </td>
                        </tr>
                    `).join('')}
                </tbody>
            </table>
        </div>

        <div class="flex flex-wrap gap-4 mt-4">
            <div class="bg-white dark:bg-zinc-800 rounded-lg shadow p-4 border border-gray-200 dark:border-zinc-700">
                <p class="text-sm text-gray-500">Total de Itens</p>
                <p class="text-2xl font-bold text-gray-900 dark:text-white">${stockData.length}</p>
            </div>
            <div class="bg-white dark:bg-zinc-800 rounded-lg shadow p-4 border border-gray-200 dark:border-zinc-700">
                <p class="text-sm text-gray-500">Valor Total (Compra)</p>
                <p class="text-2xl font-bold text-gray-900 dark:text-white">${formatMoney(stockData.reduce((s, i) => s + parseFloat(i.purchase_price) * parseFloat(i.quantity), 0))}</p>
            </div>
            <div class="bg-white dark:bg-zinc-800 rounded-lg shadow p-4 border border-gray-200 dark:border-zinc-700">
                <p class="text-sm text-gray-500">Valor Total (Venda)</p>
                <p class="text-2xl font-bold text-gray-900 dark:text-white">${formatMoney(stockData.reduce((s, i) => s + parseFloat(i.sale_price) * parseFloat(i.quantity), 0))}</p>
            </div>
            <div class="bg-white dark:bg-zinc-800 rounded-lg shadow p-4 border border-gray-200 dark:border-zinc-700">
                <p class="text-sm text-gray-500">Itens com Estoque Baixo</p>
                <p class="text-2xl font-bold text-red-600">${stockData.filter(i => parseFloat(i.min_quantity) > 0 && parseFloat(i.quantity) <= parseFloat(i.min_quantity)).length}</p>
            </div>
        </div>
    `;
}

function applyStockFilter() {
    stockFilters.search = document.getElementById('stock-search')?.value || '';
    stockFilters.branch_id = document.getElementById('stock-filter-branch')?.value || '';
    stockFilters.category = document.getElementById('stock-filter-category')?.value || '';
    stockFilters.item_type = document.getElementById('stock-filter-type')?.value || '';
    stockFilters.low_stock = document.getElementById('stock-filter-low')?.value || '';

    if (stockView === 'items') {
        renderStockItems();
    } else if (stockView === 'entries') {
        renderStockEntries();
    } else {
        renderStockExits();
    }
}

function clearStockFilters() {
    stockFilters = {};
    if (stockView === 'items') {
        renderStockItems();
    } else if (stockView === 'entries') {
        renderStockEntries();
    } else {
        renderStockExits();
    }
}

function formatItemType(type) {
    const types = { unidade: 'Unidade', caixa: 'Caixa', kg: 'Kg', litro: 'Litro' };
    return types[type] || type;
}

async function renderStockExits() {
    const container = document.getElementById('stock-content');
    container.innerHTML = '<div class="flex justify-center items-center h-32"><div class="spinner"></div></div>';

    try {
        const params = new URLSearchParams();
        if (stockFilters.branch_id) params.append('branch_id', stockFilters.branch_id);
        if (stockFilters.category) params.append('category', stockFilters.category);
        if (stockFilters.item_type) params.append('item_type', stockFilters.item_type);
        if (stockFilters.search) params.append('search', stockFilters.search);
        if (stockFilters.exit_date_start) params.append('date_start', stockFilters.exit_date_start);
        if (stockFilters.exit_date_end) params.append('date_end', stockFilters.exit_date_end);

        const res = await fetch(`api/stock-exits.php?${params.toString()}`, { credentials: 'include' });
        const data = await res.json();
        stockExitsData = data.exits || [];
    } catch (e) {
        stockExitsData = [];
    }

    const branchOptions = stockBranches.map(b => `<option value="${b.id}" ${stockFilters.branch_id === b.id ? 'selected' : ''}>${b.name}</option>`).join('');

    const today = new Date().toISOString().split('T')[0];
    const monthStart = today.substring(0, 8) + '01';

    container.innerHTML = `
        <div class="bg-white dark:bg-zinc-800 rounded-lg shadow p-4 border border-gray-200 dark:border-zinc-700">
            <div class="flex flex-wrap gap-3 items-end">
                <div>
                    <label class="block text-xs font-medium text-gray-500 mb-1">Buscar Item</label>
                    <input type="text" id="stock-search" placeholder="Nome do item..." value="${stockFilters.search || ''}" onkeyup="if(event.key==='Enter')applyStockExitFilter()" class="px-3 py-2 border border-gray-300 dark:border-zinc-600 rounded-lg bg-white dark:bg-zinc-700 text-gray-900 dark:text-white text-sm" data-testid="input-exit-search">
                </div>
                <div>
                    <label class="block text-xs font-medium text-gray-500 mb-1">Filial</label>
                    <select id="stock-filter-branch" onchange="applyStockExitFilter()" class="px-3 py-2 border border-gray-300 dark:border-zinc-600 rounded-lg bg-white dark:bg-zinc-700 text-gray-900 dark:text-white text-sm" data-testid="select-exit-branch">
                        <option value="">Todas</option>
                        ${branchOptions}
                    </select>
                </div>
                <div>
                    <label class="block text-xs font-medium text-gray-500 mb-1">Data Início</label>
                    <input type="date" id="exit-date-start" value="${stockFilters.exit_date_start || monthStart}" onchange="applyStockExitFilter()" class="px-3 py-2 border border-gray-300 dark:border-zinc-600 rounded-lg bg-white dark:bg-zinc-700 text-gray-900 dark:text-white text-sm" data-testid="input-exit-date-start">
                </div>
                <div>
                    <label class="block text-xs font-medium text-gray-500 mb-1">Data Fim</label>
                    <input type="date" id="exit-date-end" value="${stockFilters.exit_date_end || today}" onchange="applyStockExitFilter()" class="px-3 py-2 border border-gray-300 dark:border-zinc-600 rounded-lg bg-white dark:bg-zinc-700 text-gray-900 dark:text-white text-sm" data-testid="input-exit-date-end">
                </div>
                <button onclick="clearStockFilters()" class="px-3 py-2 text-sm text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200" data-testid="button-clear-exit-filters">
                    Limpar
                </button>
            </div>
        </div>

        <div class="bg-white dark:bg-zinc-800 rounded-lg shadow border border-gray-200 dark:border-zinc-700 overflow-x-auto mt-4">
            <table class="min-w-full divide-y divide-gray-200 dark:divide-zinc-700">
                <thead class="bg-gray-50 dark:bg-zinc-900">
                    <tr>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Data</th>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Item</th>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Categoria</th>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Tipo</th>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Quantidade</th>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">V. Unitário</th>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">V. Total</th>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Filial</th>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Obs</th>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Ações</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-200 dark:divide-zinc-700">
                    ${stockExitsData.length === 0 ? `
                        <tr><td colspan="10" class="px-4 py-8 text-center text-gray-500">Nenhuma saída registrada</td></tr>
                    ` : stockExitsData.map(exit => `
                        <tr class="hover:bg-gray-50 dark:hover:bg-zinc-700/50" data-testid="row-exit-${exit.id}">
                            <td class="px-4 py-3 text-gray-900 dark:text-white">${formatDate(exit.exit_date)}</td>
                            <td class="px-4 py-3 font-medium text-gray-900 dark:text-white">${exit.item_name}</td>
                            <td class="px-4 py-3 text-gray-600 dark:text-gray-300">${exit.category || '-'}</td>
                            <td class="px-4 py-3 text-gray-600 dark:text-gray-300">${formatItemType(exit.item_type)}</td>
                            <td class="px-4 py-3 font-medium text-orange-600">${parseFloat(exit.quantity).toLocaleString('pt-BR')}</td>
                            <td class="px-4 py-3 text-gray-600 dark:text-gray-300">${formatMoney(exit.sale_price)}</td>
                            <td class="px-4 py-3 font-medium text-red-600">${formatMoney(parseFloat(exit.sale_price) * parseFloat(exit.quantity))}</td>
                            <td class="px-4 py-3 text-gray-600 dark:text-gray-300">${exit.branch_name || '-'}</td>
                            <td class="px-4 py-3 text-gray-600 dark:text-gray-300">${exit.notes || '-'}</td>
                            <td class="px-4 py-3">
                                <button onclick="deleteStockExit('${exit.id}')" class="text-red-500 hover:text-red-700" title="Excluir (restaura estoque)" data-testid="button-delete-exit-${exit.id}">
                                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/></svg>
                                </button>
                            </td>
                        </tr>
                    `).join('')}
                </tbody>
            </table>
        </div>

        <div class="flex flex-wrap gap-4 mt-4">
            <div class="bg-white dark:bg-zinc-800 rounded-lg shadow p-4 border border-gray-200 dark:border-zinc-700">
                <p class="text-sm text-gray-500">Total de Saídas</p>
                <p class="text-2xl font-bold text-gray-900 dark:text-white">${stockExitsData.length}</p>
            </div>
            <div class="bg-white dark:bg-zinc-800 rounded-lg shadow p-4 border border-gray-200 dark:border-zinc-700">
                <p class="text-sm text-gray-500">Qtd Total Saída</p>
                <p class="text-2xl font-bold text-orange-600">${stockExitsData.reduce((s, e) => s + parseFloat(e.quantity), 0).toLocaleString('pt-BR')}</p>
            </div>
            <div class="bg-white dark:bg-zinc-800 rounded-lg shadow p-4 border border-gray-200 dark:border-zinc-700">
                <p class="text-sm text-gray-500">Valor Total Saídas</p>
                <p class="text-2xl font-bold text-red-600">${formatMoney(stockExitsData.reduce((s, e) => s + parseFloat(e.sale_price) * parseFloat(e.quantity), 0))}</p>
            </div>
        </div>
    `;
}

function applyStockExitFilter() {
    stockFilters.search = document.getElementById('stock-search')?.value || '';
    stockFilters.branch_id = document.getElementById('stock-filter-branch')?.value || '';
    stockFilters.exit_date_start = document.getElementById('exit-date-start')?.value || '';
    stockFilters.exit_date_end = document.getElementById('exit-date-end')?.value || '';
    renderStockExits();
}

async function renderStockEntries() {
    const container = document.getElementById('stock-content');
    container.innerHTML = '<div class="flex justify-center items-center h-32"><div class="spinner"></div></div>';

    try {
        const params = new URLSearchParams();
        if (stockFilters.branch_id) params.append('branch_id', stockFilters.branch_id);
        if (stockFilters.category) params.append('category', stockFilters.category);
        if (stockFilters.item_type) params.append('item_type', stockFilters.item_type);
        if (stockFilters.search) params.append('search', stockFilters.search);
        if (stockFilters.entry_date_start) params.append('date_start', stockFilters.entry_date_start);
        if (stockFilters.entry_date_end) params.append('date_end', stockFilters.entry_date_end);

        const res = await fetch(`api/stock-entries.php?${params.toString()}`, { credentials: 'include' });
        const data = await res.json();
        stockEntriesData = data.entries || [];
    } catch (e) {
        stockEntriesData = [];
    }

    const branchOptions = stockBranches.map(b => `<option value="${b.id}" ${stockFilters.branch_id === b.id ? 'selected' : ''}>${b.name}</option>`).join('');

    const today = new Date().toISOString().split('T')[0];
    const monthStart = today.substring(0, 8) + '01';

    container.innerHTML = `
        <div class="bg-white dark:bg-zinc-800 rounded-lg shadow p-4 border border-gray-200 dark:border-zinc-700">
            <div class="flex flex-wrap gap-3 items-end">
                <div>
                    <label class="block text-xs font-medium text-gray-500 mb-1">Buscar Item</label>
                    <input type="text" id="stock-search" placeholder="Nome do item..." value="${stockFilters.search || ''}" onkeyup="if(event.key==='Enter')applyStockEntryFilter()" class="px-3 py-2 border border-gray-300 dark:border-zinc-600 rounded-lg bg-white dark:bg-zinc-700 text-gray-900 dark:text-white text-sm" data-testid="input-entry-search">
                </div>
                <div>
                    <label class="block text-xs font-medium text-gray-500 mb-1">Filial</label>
                    <select id="stock-filter-branch" onchange="applyStockEntryFilter()" class="px-3 py-2 border border-gray-300 dark:border-zinc-600 rounded-lg bg-white dark:bg-zinc-700 text-gray-900 dark:text-white text-sm" data-testid="select-entry-branch">
                        <option value="">Todas</option>
                        ${branchOptions}
                    </select>
                </div>
                <div>
                    <label class="block text-xs font-medium text-gray-500 mb-1">Data Início</label>
                    <input type="date" id="entry-date-start" value="${stockFilters.entry_date_start || monthStart}" onchange="applyStockEntryFilter()" class="px-3 py-2 border border-gray-300 dark:border-zinc-600 rounded-lg bg-white dark:bg-zinc-700 text-gray-900 dark:text-white text-sm" data-testid="input-entry-date-start">
                </div>
                <div>
                    <label class="block text-xs font-medium text-gray-500 mb-1">Data Fim</label>
                    <input type="date" id="entry-date-end" value="${stockFilters.entry_date_end || today}" onchange="applyStockEntryFilter()" class="px-3 py-2 border border-gray-300 dark:border-zinc-600 rounded-lg bg-white dark:bg-zinc-700 text-gray-900 dark:text-white text-sm" data-testid="input-entry-date-end">
                </div>
                <button onclick="clearStockFilters()" class="px-3 py-2 text-sm text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200" data-testid="button-clear-entry-filters">
                    Limpar
                </button>
            </div>
        </div>

        <div class="bg-white dark:bg-zinc-800 rounded-lg shadow border border-gray-200 dark:border-zinc-700 overflow-x-auto mt-4">
            <table class="min-w-full divide-y divide-gray-200 dark:divide-zinc-700">
                <thead class="bg-gray-50 dark:bg-zinc-900">
                    <tr>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Data</th>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Item</th>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Categoria</th>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Tipo</th>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Quantidade</th>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">V. Unitário</th>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">V. Total</th>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Filial</th>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Obs</th>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Ações</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-200 dark:divide-zinc-700">
                    ${stockEntriesData.length === 0 ? `
                        <tr><td colspan="10" class="px-4 py-8 text-center text-gray-500">Nenhuma entrada registrada</td></tr>
                    ` : stockEntriesData.map(entry => `
                        <tr class="hover:bg-gray-50 dark:hover:bg-zinc-700/50" data-testid="row-entry-${entry.id}">
                            <td class="px-4 py-3 text-gray-900 dark:text-white">${formatDate(entry.entry_date)}</td>
                            <td class="px-4 py-3 font-medium text-gray-900 dark:text-white">${entry.item_name}</td>
                            <td class="px-4 py-3 text-gray-600 dark:text-gray-300">${entry.category || '-'}</td>
                            <td class="px-4 py-3 text-gray-600 dark:text-gray-300">${formatItemType(entry.item_type)}</td>
                            <td class="px-4 py-3 font-medium text-green-600">${parseFloat(entry.quantity).toLocaleString('pt-BR')}</td>
                            <td class="px-4 py-3 text-gray-600 dark:text-gray-300">${formatMoney(entry.purchase_price)}</td>
                            <td class="px-4 py-3 font-medium text-green-600">${formatMoney(parseFloat(entry.purchase_price) * parseFloat(entry.quantity))}</td>
                            <td class="px-4 py-3 text-gray-600 dark:text-gray-300">${entry.branch_name || '-'}</td>
                            <td class="px-4 py-3 text-gray-600 dark:text-gray-300">${entry.notes || '-'}</td>
                            <td class="px-4 py-3">
                                <button onclick="deleteStockEntry('${entry.id}')" class="text-red-500 hover:text-red-700" title="Excluir (ajusta estoque)" data-testid="button-delete-entry-${entry.id}">
                                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/></svg>
                                </button>
                            </td>
                        </tr>
                    `).join('')}
                </tbody>
            </table>
        </div>

        <div class="flex flex-wrap gap-4 mt-4">
            <div class="bg-white dark:bg-zinc-800 rounded-lg shadow p-4 border border-gray-200 dark:border-zinc-700">
                <p class="text-sm text-gray-500">Total de Entradas</p>
                <p class="text-2xl font-bold text-gray-900 dark:text-white">${stockEntriesData.length}</p>
            </div>
            <div class="bg-white dark:bg-zinc-800 rounded-lg shadow p-4 border border-gray-200 dark:border-zinc-700">
                <p class="text-sm text-gray-500">Qtd Total Entrada</p>
                <p class="text-2xl font-bold text-green-600">${stockEntriesData.reduce((s, e) => s + parseFloat(e.quantity), 0).toLocaleString('pt-BR')}</p>
            </div>
            <div class="bg-white dark:bg-zinc-800 rounded-lg shadow p-4 border border-gray-200 dark:border-zinc-700">
                <p class="text-sm text-gray-500">Valor Total Entradas</p>
                <p class="text-2xl font-bold text-green-600">${formatMoney(stockEntriesData.reduce((s, e) => s + parseFloat(e.purchase_price) * parseFloat(e.quantity), 0))}</p>
            </div>
        </div>
    `;
}

function applyStockEntryFilter() {
    stockFilters.search = document.getElementById('stock-search')?.value || '';
    stockFilters.branch_id = document.getElementById('stock-filter-branch')?.value || '';
    stockFilters.entry_date_start = document.getElementById('entry-date-start')?.value || '';
    stockFilters.entry_date_end = document.getElementById('entry-date-end')?.value || '';
    renderStockEntries();
}

function openStockEntryModal(itemId) {
    const item = stockData.find(i => i.id === itemId);
    if (!item) return;

    const modal = document.createElement('div');
    modal.id = 'stock-modal';
    modal.className = 'fixed inset-0 z-50 flex items-center justify-center bg-black/50';
    modal.innerHTML = `
        <div class="bg-white dark:bg-zinc-800 rounded-lg shadow-xl w-full max-w-md mx-4">
            <div class="p-6">
                <div class="flex items-center justify-between mb-4">
                    <h3 class="text-lg font-semibold text-gray-900 dark:text-white">Registrar Entrada</h3>
                    <button onclick="closeStockModal()" class="text-gray-500 hover:text-gray-700"><svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/></svg></button>
                </div>
                <div class="mb-4 p-3 bg-gray-50 dark:bg-zinc-700 rounded-lg">
                    <p class="font-medium text-gray-900 dark:text-white">${item.name}</p>
                    <p class="text-sm text-gray-500">Estoque atual: ${parseFloat(item.quantity).toLocaleString('pt-BR')} ${formatItemType(item.item_type)}</p>
                </div>
                <form onsubmit="saveStockEntry(event, '${itemId}')" class="space-y-4">
                    <div>
                        <label class="form-label">Data de Entrada *</label>
                        <input type="date" id="entry-date" value="${new Date().toISOString().split('T')[0]}" required class="form-input" data-testid="input-entry-date">
                    </div>
                    <div>
                        <label class="form-label">Quantidade *</label>
                        <input type="number" step="0.001" id="entry-quantity" required min="0.001" class="form-input" data-testid="input-entry-quantity">
                    </div>
                    <div>
                        <label class="form-label">Observações</label>
                        <input type="text" id="entry-notes" class="form-input" placeholder="Nota fiscal, fornecedor..." data-testid="input-entry-notes">
                    </div>
                    <div class="flex gap-3 pt-2">
                        <button type="submit" class="flex-1 bg-green-600 hover:bg-green-700 text-white font-medium py-2 px-4 rounded-lg" data-testid="button-save-entry">Registrar Entrada</button>
                        <button type="button" onclick="closeStockModal()" class="flex-1 bg-gray-300 hover:bg-gray-400 text-gray-800 font-medium py-2 px-4 rounded-lg">Cancelar</button>
                    </div>
                </form>
            </div>
        </div>
    `;
    document.body.appendChild(modal);
}

async function saveStockEntry(e, itemId) {
    e.preventDefault();
    const data = {
        stock_item_id: itemId,
        quantity: parseFloat(document.getElementById('entry-quantity').value),
        entry_date: document.getElementById('entry-date').value,
        notes: document.getElementById('entry-notes').value
    };

    try {
        const res = await fetch('api/stock-entries.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            credentials: 'include',
            body: JSON.stringify(data)
        });
        const result = await res.json();
        if (result.success) {
            closeStockModal();
            renderStockItems();
        } else {
            alert(result.error || 'Erro ao registrar entrada');
        }
    } catch (err) {
        alert('Erro de conexão');
    }
}

async function deleteStockEntry(id) {
    if (!confirm('Excluir esta entrada? O estoque será ajustado (quantidade reduzida).')) return;

    try {
        const res = await fetch(`api/stock-entries.php?id=${id}`, { method: 'DELETE', credentials: 'include' });
        const result = await res.json();
        if (result.success) {
            renderStockEntries();
        } else {
            alert(result.error || 'Erro ao excluir');
        }
    } catch (err) {
        alert('Erro de conexão');
    }
}

function openStockItemModal(id = null) {
    const item = id ? stockData.find(i => i.id === id) : null;
    const branchOptions = stockBranches.map(b => `<option value="${b.id}" ${item && item.branch_id === b.id ? 'selected' : ''}>${b.name}</option>`).join('');

    const modal = document.createElement('div');
    modal.id = 'stock-modal';
    modal.className = 'fixed inset-0 z-50 flex items-center justify-center bg-black/50';
    modal.innerHTML = `
        <div class="bg-white dark:bg-zinc-800 rounded-lg shadow-xl w-full max-w-lg mx-4 max-h-[90vh] overflow-y-auto">
            <div class="p-6">
                <div class="flex items-center justify-between mb-4">
                    <h3 class="text-lg font-semibold text-gray-900 dark:text-white">${item ? 'Editar Item' : 'Novo Item do Estoque'}</h3>
                    <button onclick="closeStockModal()" class="text-gray-500 hover:text-gray-700"><svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/></svg></button>
                </div>
                <form onsubmit="saveStockItem(event, '${id || ''}')" class="space-y-4">
                    <div>
                        <label class="form-label">Nome *</label>
                        <input type="text" id="stock-name" value="${item?.name || ''}" required class="form-input" data-testid="input-stock-name">
                    </div>
                    <div class="grid grid-cols-2 gap-4">
                        <div>
                            <label class="form-label">Valor Compra</label>
                            <input type="number" step="0.01" id="stock-purchase-price" value="${item?.purchase_price || '0'}" class="form-input" data-testid="input-purchase-price">
                        </div>
                        <div>
                            <label class="form-label">Valor Venda</label>
                            <input type="number" step="0.01" id="stock-sale-price" value="${item?.sale_price || '0'}" class="form-input" data-testid="input-sale-price">
                        </div>
                    </div>
                    <div class="grid grid-cols-3 gap-4">
                        <div>
                            <label class="form-label">Quantidade</label>
                            <input type="number" step="0.001" id="stock-quantity" value="${item?.quantity || '0'}" class="form-input" data-testid="input-stock-quantity">
                        </div>
                        <div>
                            <label class="form-label">Qtd Mínima</label>
                            <input type="number" step="0.001" id="stock-min-quantity" value="${item?.min_quantity || '0'}" class="form-input" data-testid="input-stock-min-quantity">
                        </div>
                        <div>
                            <label class="form-label">Tipo</label>
                            <select id="stock-item-type" class="form-input" data-testid="select-item-type">
                                <option value="unidade" ${item?.item_type === 'unidade' ? 'selected' : ''}>Unidade</option>
                                <option value="caixa" ${item?.item_type === 'caixa' ? 'selected' : ''}>Caixa</option>
                                <option value="kg" ${item?.item_type === 'kg' ? 'selected' : ''}>Kg</option>
                                <option value="litro" ${item?.item_type === 'litro' ? 'selected' : ''}>Litro</option>
                            </select>
                        </div>
                    </div>
                    <div>
                        <label class="form-label">Categoria</label>
                        <input type="text" id="stock-category" value="${item?.category || ''}" placeholder="Ex: Carnes, Bebidas, Embalagens..." class="form-input" data-testid="input-stock-category">
                    </div>
                    <div>
                        <label class="form-label">Filial</label>
                        <select id="stock-branch" class="form-input" data-testid="select-stock-branch-modal">
                            <option value="">Selecione</option>
                            ${branchOptions}
                        </select>
                    </div>
                    <div class="flex gap-3 pt-2">
                        <button type="submit" class="flex-1 bg-green-600 hover:bg-green-700 text-white font-medium py-2 px-4 rounded-lg" data-testid="button-save-stock-item">Salvar</button>
                        <button type="button" onclick="closeStockModal()" class="flex-1 bg-gray-300 hover:bg-gray-400 text-gray-800 font-medium py-2 px-4 rounded-lg">Cancelar</button>
                    </div>
                </form>
            </div>
        </div>
    `;
    document.body.appendChild(modal);
}

function closeStockModal() {
    document.getElementById('stock-modal')?.remove();
}

async function saveStockItem(e, id) {
    e.preventDefault();
    const data = {
        name: document.getElementById('stock-name').value,
        purchase_price: parseFloat(document.getElementById('stock-purchase-price').value) || 0,
        sale_price: parseFloat(document.getElementById('stock-sale-price').value) || 0,
        quantity: parseFloat(document.getElementById('stock-quantity').value) || 0,
        min_quantity: parseFloat(document.getElementById('stock-min-quantity').value) || 0,
        item_type: document.getElementById('stock-item-type').value,
        category: document.getElementById('stock-category').value,
        branch_id: document.getElementById('stock-branch').value || null
    };

    try {
        const url = id ? `api/stock-items.php?id=${id}` : 'api/stock-items.php';
        const method = id ? 'PUT' : 'POST';
        if (id) data.id = id;

        const res = await fetch(url, {
            method,
            headers: { 'Content-Type': 'application/json' },
            credentials: 'include',
            body: JSON.stringify(data)
        });
        const result = await res.json();
        if (result.success) {
            closeStockModal();
            renderStockItems();
        } else {
            alert(result.error || 'Erro ao salvar');
        }
    } catch (err) {
        alert('Erro de conexão');
    }
}

function openStockExitModal(itemId) {
    const item = stockData.find(i => i.id === itemId);
    if (!item) return;

    const modal = document.createElement('div');
    modal.id = 'stock-modal';
    modal.className = 'fixed inset-0 z-50 flex items-center justify-center bg-black/50';
    modal.innerHTML = `
        <div class="bg-white dark:bg-zinc-800 rounded-lg shadow-xl w-full max-w-md mx-4">
            <div class="p-6">
                <div class="flex items-center justify-between mb-4">
                    <h3 class="text-lg font-semibold text-gray-900 dark:text-white">Registrar Saída</h3>
                    <button onclick="closeStockModal()" class="text-gray-500 hover:text-gray-700"><svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/></svg></button>
                </div>
                <div class="mb-4 p-3 bg-gray-50 dark:bg-zinc-700 rounded-lg">
                    <p class="font-medium text-gray-900 dark:text-white">${item.name}</p>
                    <p class="text-sm text-gray-500">Estoque atual: ${parseFloat(item.quantity).toLocaleString('pt-BR')} ${formatItemType(item.item_type)}</p>
                </div>
                <form onsubmit="saveStockExit(event, '${itemId}')" class="space-y-4">
                    <div>
                        <label class="form-label">Data de Saída *</label>
                        <input type="date" id="exit-date" value="${new Date().toISOString().split('T')[0]}" required class="form-input" data-testid="input-exit-date">
                    </div>
                    <div>
                        <label class="form-label">Quantidade *</label>
                        <input type="number" step="0.001" id="exit-quantity" required max="${item.quantity}" class="form-input" data-testid="input-exit-quantity">
                    </div>
                    <div>
                        <label class="form-label">Observações</label>
                        <input type="text" id="exit-notes" class="form-input" placeholder="Motivo da saída..." data-testid="input-exit-notes">
                    </div>
                    <div class="flex gap-3 pt-2">
                        <button type="submit" class="flex-1 bg-orange-600 hover:bg-orange-700 text-white font-medium py-2 px-4 rounded-lg" data-testid="button-save-exit">Registrar Saída</button>
                        <button type="button" onclick="closeStockModal()" class="flex-1 bg-gray-300 hover:bg-gray-400 text-gray-800 font-medium py-2 px-4 rounded-lg">Cancelar</button>
                    </div>
                </form>
            </div>
        </div>
    `;
    document.body.appendChild(modal);
}

async function saveStockExit(e, itemId) {
    e.preventDefault();
    const data = {
        stock_item_id: itemId,
        quantity: parseFloat(document.getElementById('exit-quantity').value),
        exit_date: document.getElementById('exit-date').value,
        notes: document.getElementById('exit-notes').value
    };

    try {
        const res = await fetch('api/stock-exits.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            credentials: 'include',
            body: JSON.stringify(data)
        });
        const result = await res.json();
        if (result.success) {
            closeStockModal();
            renderStockItems();
        } else {
            alert(result.error || 'Erro ao registrar saída');
        }
    } catch (err) {
        alert('Erro de conexão');
    }
}

async function deleteStockItem(id) {
    if (!confirm('Excluir este item do estoque? Todas as saídas relacionadas também serão excluídas.')) return;

    try {
        const res = await fetch(`api/stock-items.php?id=${id}`, { method: 'DELETE', credentials: 'include' });
        const result = await res.json();
        if (result.success) {
            renderStockItems();
        } else {
            alert(result.error || 'Erro ao excluir');
        }
    } catch (err) {
        alert('Erro de conexão');
    }
}

async function deleteStockExit(id) {
    if (!confirm('Excluir esta saída? O estoque será restaurado.')) return;

    try {
        const res = await fetch(`api/stock-exits.php?id=${id}`, { method: 'DELETE', credentials: 'include' });
        const result = await res.json();
        if (result.success) {
            renderStockExits();
        } else {
            alert(result.error || 'Erro ao excluir');
        }
    } catch (err) {
        alert('Erro de conexão');
    }
}
