/**
 * app.js — Application entry point and state management
 */

const App = {
    currentPage: 1,
    currentQuery: '',
    currentLugarId: null,
    currentFecha: null,
    currentUpdateFilter: 'all',
    limit: 10,

    async init() {
        // Load locations dropdown
        await this.loadLocations();

        // Load initial products
        await this.loadProducts();

        // Init modal
        Modals.init();

        // Setup search with debounce
        const searchBar = document.getElementById('searchBar');
        const debouncedSearch = debounce((val) => {
            this.currentQuery = val;
            this.currentPage = 1;
            this.loadProducts();
        }, 400);

        searchBar.addEventListener('input', (e) => {
            debouncedSearch(e.target.value.trim());
        });

        // Location filter
        document.getElementById('globalLugar').addEventListener('change', (e) => {
            this.currentLugarId = e.target.value ? parseInt(e.target.value) : null;
            this.currentPage = 1;
            this.loadProducts();
            // Always keep costs editable
            Products._setCostsEditable(true);
        });

        // Update status filter
        document.getElementById('filterUpdate').addEventListener('change', (e) => {
            this.currentUpdateFilter = e.target.value;
            this.currentPage = 1;
            this.loadProducts();
        });

        // Add location button
        document.getElementById('btnAddLocation').addEventListener('click', async () => {
            const nombre = prompt('Nombre del nuevo lugar de compra:');
            if (nombre && nombre.trim()) {
                try {
                    await API.createLocation(nombre.trim());
                    showToast('Lugar creado: ' + nombre.trim(), 'success');
                    await this.loadLocations();
                } catch (err) {
                    showToast('Error: ' + err.message, 'error');
                }
            }
        });

        // Init date picker
        if (typeof flatpickr !== 'undefined') {
            flatpickr('#globalFecha', {
                dateFormat: 'Y-m-d',
                altInput: true,
                altFormat: 'd-m-Y',
                defaultDate: new Date(),
                locale: 'es',
                onChange: (dates, dateStr) => {
                    this.currentFecha = dateStr;
                },
            });
            this.currentFecha = new Date().toISOString().split('T')[0];
        }
    },

    async loadLocations() {
        try {
            const res = await API.getLocations();
            const select = document.getElementById('globalLugar');
            const currentVal = select.value;
            select.innerHTML = '<option value="">Todos los lugares</option>';
            if (res && res.data) {
                res.data.forEach(l => {
                    select.innerHTML += `<option value="${l.id}">${escapeHtml(l.nombre)}</option>`;
                });
            }
            select.value = currentVal;
        } catch (err) {
            console.error('Error loading locations', err);
        }
    },

    async loadProducts() {
        const spinner = document.getElementById('searchSpinner');
        spinner.style.display = 'block';

        try {
            const res = await API.searchProducts(
                this.currentQuery,
                this.currentPage,
                this.limit,
                this.currentLugarId,
                this.currentUpdateFilter
            );
            if (res) {
                Products.render(res.data);
            }
        } catch (err) {
            showToast('Error cargando productos: ' + err.message, 'error');
            document.getElementById('productTable').innerHTML = `
                <div class="empty-state">
                    <i class="fas fa-exclamation-triangle"></i>
                    <p>Error al cargar productos</p>
                    <small>${escapeHtml(err.message)}</small>
                </div>`;
        } finally {
            spinner.style.display = 'none';
        }
    },
};

// Boot
document.addEventListener('DOMContentLoaded', () => App.init());
