var ResponsiveHelper = {
    registros: {},
    _estiloEl: null,

    registrar: function(pageId, opts) {
        opts = opts || {};
        this.registros[pageId] = opts;
        var el = document.getElementById(pageId);
        if (el && el.classList.contains('visible')) {
            this._aplicar(pageId);
        }
    },

    _aplicar: function(pageId) {
        var opts = this.registros[pageId];
        if (!opts) return;
        var isMobile = window.innerWidth < 768;
        if (isMobile) {
            this._limpiarInlineWidths(pageId);
            if (opts.hideCols) this._toggleCols(pageId, opts.hideCols, true);
        } else {
            this._limpiarInlineWidths(pageId);
            if (opts.hideCols && opts._colsOcultas) this._toggleCols(pageId, opts.hideCols, false);
        }
    },

    _limpiarInlineWidths: function(pageId) {
        var ths = document.querySelectorAll('#' + pageId + ' th');
        ths.forEach(function(th) {
            if (window.innerWidth < 768) {
                th.style.setProperty('width', 'auto', 'important');
                th.style.removeProperty('max-width');
                th.style.removeProperty('min-width');
            } else {
                th.style.removeProperty('width');
                th.style.removeProperty('max-width');
                th.style.removeProperty('min-width');
            }
        });
    },

    _toggleCols: function(pageId, colIndices, hide) {
        var self = this;
        var opts = this.registros[pageId];
        colIndices.forEach(function(idx) {
            var n = idx + 1;
            document.querySelectorAll('#' + pageId + ' th:nth-child(' + n + '), #' + pageId + ' td:nth-child(' + n + ')').forEach(function(el) {
                el.style.display = hide ? 'none' : '';
            });
        });
        if (opts) opts._colsOcultas = hide;
    },

    aplicarActual: function() {
        for (var id in this.registros) {
            this._aplicar(id);
        }
    },

    // ============================================================
    // adaptar(pageId, selectores) — Inyecta CSS responsive para
    // módulos con clases propias (distintas a .prov-*).
    // Uso: ResponsiveHelper.adaptar('pageClientes', {
    //        toolbar: '.cli-toolbar', header: '.cli-header',
    //        buscador: '.cli-buscador',
    //        grids: ['.cli-form', '.cli-detalle-grid'],
    //        fields: ['.cli-field'],
    //        detalleToolbar: '.mi-add-bar'
    //      });
    // ============================================================
    adaptar: function(pageId, sel) {
        var css = '';
        var base = '#' + pageId + ' ';
        var isMobile = '@media (max-width: 768px)';

        css += isMobile + '{\n';

        function addRule(selector, rule) {
            css += selector + ' { ' + rule + ' }\n';
        }

        if (sel.header) {
            addRule(base + sel.header, 'flex-direction:column !important; align-items:flex-start !important; gap:12px !important');
        }
        if (sel.toolbar) {
            addRule(base + sel.toolbar, 'flex-direction:column !important; align-items:stretch !important');
            addRule(base + sel.toolbar + ' > *', 'width:100% !important');
        }
        if (sel.buscador) {
            addRule(base + sel.buscador, 'max-width:100% !important');
        }
        if (sel.grids) {
            sel.grids.forEach(function(g) {
                addRule(base + g, 'grid-template-columns:1fr !important');
                addRule(g, 'grid-template-columns:1fr !important'); // versión global para modales
            });
        }
        if (sel.fields) {
            sel.fields.forEach(function(f) {
                addRule(base + f, 'width:100% !important; min-width:auto !important; flex:1 1 100% !important');
                addRule(f, 'width:100% !important; min-width:auto !important; flex:1 1 100% !important');
            });
        }
        if (sel.form) {
            addRule(base + sel.form, 'width:100% !important');
        }
        if (sel.detalleToolbar) {
            addRule(base + sel.detalleToolbar, 'flex-wrap:wrap !important; gap:8px !important');
            addRule(base + sel.detalleToolbar + ' > *', 'flex:1 1 100% !important; min-width:auto !important; width:100% !important');
            addRule(sel.detalleToolbar, 'flex-wrap:wrap !important; gap:8px !important');
            addRule(sel.detalleToolbar + ' > *', 'flex:1 1 100% !important; min-width:auto !important; width:100% !important');
        }
        if (sel.paginacion) {
            addRule(base + sel.paginacion, 'flex-direction:column !important; gap:10px !important; align-items:center !important');
        }

        css += '}\n';

        this._inyectarCSS(css);
        this.registrar(pageId, { hideCols: sel.hideCols || null });
    },

    _inyectarCSS: function(css) {
        if (!this._estiloEl) {
            this._estiloEl = document.createElement('style');
            this._estiloEl.id = 'responsive-adapt-css';
            document.head.appendChild(this._estiloEl);
        }
        this._estiloEl.textContent += css;
    },

    init: function() {
        var self = this;
        var timer;
        window.addEventListener('resize', function() {
            clearTimeout(timer);
            timer = setTimeout(function() { self.aplicarActual(); }, 250);
        });
        document.addEventListener('pageChanged', function() { self.aplicarActual(); });

        // ============================================================
        // Adaptaciones para módulos con clases propias
        // ============================================================

        /* ── Clientes ── */
        this.adaptar('pageClientes', {
            toolbar: '.cli-toolbar',
            header: '.cli-header',
            buscador: '.cli-buscador',
            grids: ['.cli-form', '.cli-detalle-grid'],
            fields: ['.cli-field', '.cli-tercio'],
            hideCols: [5, 6]
        });

        /* ── Saldos Iniciales ── */
        this.adaptar('pageSaldosIniciales', {
            header: '.sdi-header',
            toolbar: '.sdi-filtros',
            form: '.sdi-form-cab',
            grids: ['.sdi-form-row'],
            paginacion: '.sdi-paginacion'
        });

        /* ── Costos Iniciales ── */
        this.adaptar('pageCostosIniciales', {
            header: '.ci-header',
            toolbar: '.ci-filtros',
            grids: ['.ci-form-row']
        });

        /* ── Pedidos ── */
        this.adaptar('pagePedidos', {
            grids: ['.ped-grid', '.ped-detalle-grid'],
            detalleToolbar: '.ped-add-bar',
            fields: ['.ped-field-art', '.ped-field-qty']
        });

        /* ── Ordenes Compra ── */
        this.adaptar('pageOrdenesCompra', {
            grids: ['.oc-grid-3', '.oc-grid-4'],
            detalleToolbar: '.oc-detalle-toolbar',
            fields: ['.oc-field-art', '.oc-field-qty', '.oc-field-price']
        });

        /* ── Guías Compra ── */
        this.adaptar('pageGuiasCompras', {
            grids: ['.gc-grid-4'],
            detalleToolbar: '.gc-detalle-toolbar',
            fields: ['.gc-field-art', '.gc-field-qty', '.gc-field-costo']
        });

        /* ── Guías Salida ── */
        this.adaptar('pageGuiasSalida', {
            grids: ['.gc-grid-4'],
            detalleToolbar: '.gc-detalle-toolbar',
            fields: ['.gc-field-art', '.gc-field-qty', '.gc-field-costo']
        });

        /* ── Tipo Cambio ── */
        this.adaptar('pageTipoCambio', {
            toolbar: '.tc-filtros',
            grids: ['.tc-form-row'],
            fields: ['.tc-field']
        });
    }
};

ResponsiveHelper.init();
