/**
 * Settings — Fully dynamic catalog administration
 * Handles: Species, Breeds, Vaccines, Medications, Diseases,
 *          Inventory Categories, Disposal Reasons, Ranch Locations,
 *          Custom Fields, and General settings.
 */
const Settings = {
    speciesList: [],

    /* ═══ Catalog definitions ═══
     * Each key matches the data-tab id in the HTML.
     * api: base endpoint for CRUD
     * body: HTML table body id
     * label: singular Spanish name
     * cols: number of table columns (for empty-row colspan)
     * fields: array of form field definitions rendered inside the universal modal
     * row: function that returns a <tr> string for each record
     */
    catalogs: {
        species: {
            api: '/species',
            body: 'speciesBody',
            label: 'Especie',
            cols: 4,
            fields: [
                { key: 'name', label: 'Nombre *', type: 'text', required: true },
                { key: 'scientific_name', label: 'Nombre Científico', type: 'text' },
                { key: 'gestation_days', label: 'Días de Gestación', type: 'number', min: 0 },
            ],
            row(s) {
                return `<tr>
                    <td><strong>${s.name}</strong></td>
                    <td>${s.scientific_name || '—'}</td>
                    <td class="cfg-hide-sm">${s.animal_count || 0}</td>
                    <td>${Settings.actionBtns(s.id, 'species')}</td>
                </tr>`;
            },
            afterLoad(rows) {
                Settings.speciesList = rows;
            }
        },
        breed: {
            api: '/breeds',
            body: 'breedsBody',
            label: 'Raza',
            cols: 4,
            fields: [
                { key: 'species_id', label: 'Especie *', type: 'species-select', required: true },
                { key: 'name', label: 'Nombre *', type: 'text', required: true },
                { key: 'description', label: 'Descripción', type: 'textarea' },
            ],
            row(b) {
                return `<tr>
                    <td><strong>${b.name}</strong></td>
                    <td>${b.species_name || '—'}</td>
                    <td class="cfg-hide-sm">${b.animal_count || 0}</td>
                    <td>${Settings.actionBtns(b.id, 'breed')}</td>
                </tr>`;
            }
        },
        vaccine: {
            api: '/catalogs/vaccines',
            body: 'vaccinesBody',
            label: 'Vacuna',
            cols: 6,
            fields: [
                { key: 'name', label: 'Nombre *', type: 'text', required: true },
                { key: 'manufacturer', label: 'Fabricante', type: 'text' },
                { key: 'species_id', label: 'Especie', type: 'species-select' },
                { key: 'route', label: 'Vía de aplicación', type: 'select', options: [
                    { v: '', t: '— Seleccionar —' },
                    { v: 'intramuscular', t: 'Intramuscular' },
                    { v: 'subcutaneous', t: 'Subcutánea' },
                    { v: 'oral', t: 'Oral' },
                    { v: 'nasal', t: 'Nasal' },
                    { v: 'topical', t: 'Tópica' },
                    { v: 'other', t: 'Otra' },
                ]},
                { key: 'dose_ml', label: 'Dosis (ml)', type: 'number', step: '0.01', min: 0 },
                { key: 'booster_days', label: 'Refuerzo (días)', type: 'number', min: 0 },
                { key: 'withdrawal_days', label: 'Retiro (días)', type: 'number', min: 0 },
                { key: 'description', label: 'Descripción', type: 'textarea' },
            ],
            row(v) {
                return `<tr>
                    <td><strong>${v.name}</strong></td>
                    <td class="cfg-hide-sm">${v.manufacturer || '—'}</td>
                    <td class="cfg-hide-sm">${v.species_name || 'Todas'}</td>
                    <td class="cfg-hide-sm">${v.route || '—'}</td>
                    <td class="cfg-hide-sm">${v.booster_days || '—'}</td>
                    <td>${Settings.actionBtns(v.id, 'vaccine')}</td>
                </tr>`;
            }
        },
        medication: {
            api: '/catalogs/medications',
            body: 'medicationsBody',
            label: 'Medicamento',
            cols: 5,
            fields: [
                { key: 'name', label: 'Nombre *', type: 'text', required: true },
                { key: 'active_ingredient', label: 'Ingrediente Activo', type: 'text' },
                { key: 'manufacturer', label: 'Fabricante', type: 'text' },
                { key: 'presentation', label: 'Presentación', type: 'text' },
                { key: 'withdrawal_days', label: 'Retiro (días)', type: 'number', min: 0 },
                { key: 'dose_instructions', label: 'Instrucciones de dosis', type: 'textarea' },
            ],
            row(m) {
                return `<tr>
                    <td><strong>${m.name}</strong></td>
                    <td class="cfg-hide-sm">${m.active_ingredient || '—'}</td>
                    <td class="cfg-hide-sm">${m.manufacturer || '—'}</td>
                    <td class="cfg-hide-sm">${m.presentation || '—'}</td>
                    <td>${Settings.actionBtns(m.id, 'medication')}</td>
                </tr>`;
            }
        },
        disease: {
            api: '/catalogs/diseases',
            body: 'diseasesBody',
            label: 'Enfermedad',
            cols: 5,
            fields: [
                { key: 'name', label: 'Nombre *', type: 'text', required: true },
                { key: 'common_name', label: 'Nombre Común', type: 'text' },
                { key: 'severity', label: 'Severidad', type: 'select', options: [
                    { v: 'mild', t: 'Leve' },
                    { v: 'moderate', t: 'Moderada' },
                    { v: 'severe', t: 'Severa' },
                    { v: 'critical', t: 'Crítica' },
                ]},
                { key: 'species_id', label: 'Especie (opcional)', type: 'species-select' },
                { key: 'description', label: 'Descripción', type: 'textarea' },
            ],
            row(d) {
                const sevLabels = { mild: 'Leve', moderate: 'Moderada', severe: 'Severa', critical: 'Crítica' };
                const sevClass = d.severity ? `cfg-severity cfg-severity-${d.severity}` : '';
                return `<tr>
                    <td><strong>${d.name}</strong></td>
                    <td class="cfg-hide-sm">${d.common_name || '—'}</td>
                    <td class="cfg-hide-sm">${d.severity ? `<span class="${sevClass}">${sevLabels[d.severity] || d.severity}</span>` : '—'}</td>
                    <td class="cfg-hide-sm">${d.species_name || 'Todas'}</td>
                    <td>${Settings.actionBtns(d.id, 'disease')}</td>
                </tr>`;
            }
        },
        invCategory: {
            api: '/catalogs/inventory-categories',
            body: 'invCategoriesBody',
            label: 'Categoría de Inventario',
            cols: 4,
            fields: [
                { key: 'name', label: 'Nombre *', type: 'text', required: true },
                { key: 'icon', label: 'Icono (emoji o clase)', type: 'text', placeholder: 'ej: 💊 o fas fa-box' },
                { key: 'color', label: 'Color', type: 'color' },
            ],
            row(c) {
                return `<tr>
                    <td><strong>${c.name}</strong></td>
                    <td class="cfg-hide-sm">${c.icon || '—'}</td>
                    <td class="cfg-hide-sm">${c.color ? `<span class="cfg-color-preview" style="background:${c.color}"></span>${c.color}` : '—'}</td>
                    <td>${Settings.actionBtns(c.id, 'invCategory')}</td>
                </tr>`;
            }
        },
        disposalReason: {
            api: '/catalogs/disposal-reasons',
            body: 'disposalReasonsBody',
            label: 'Motivo de Baja',
            cols: 4,
            fields: [
                { key: 'name', label: 'Nombre *', type: 'text', required: true },
                { key: 'type', label: 'Tipo *', type: 'select', required: true, options: [
                    { v: 'death', t: 'Muerte' },
                    { v: 'disease', t: 'Enfermedad' },
                    { v: 'accident', t: 'Accidente' },
                    { v: 'culling', t: 'Descarte' },
                    { v: 'administrative', t: 'Administrativa' },
                    { v: 'other', t: 'Otro' },
                ]},
                { key: 'description', label: 'Descripción', type: 'textarea' },
            ],
            row(r) {
                const typeLabels = { death: 'Muerte', disease: 'Enfermedad', accident: 'Accidente', culling: 'Descarte', administrative: 'Administrativa', other: 'Otro' };
                return `<tr>
                    <td><strong>${r.name}</strong></td>
                    <td>${typeLabels[r.type] || r.type || '—'}</td>
                    <td class="cfg-hide-sm">${r.description || '—'}</td>
                    <td>${Settings.actionBtns(r.id, 'disposalReason')}</td>
                </tr>`;
            }
        },
        location: {
            api: '/catalogs/ranch-locations',
            body: 'locationsBody',
            label: 'Ubicación',
            cols: 4,
            fields: [
                { key: 'name', label: 'Nombre *', type: 'text', required: true },
                { key: 'type', label: 'Tipo *', type: 'select', required: true, options: [
                    { v: 'corral', t: 'Corral' },
                    { v: 'potrero', t: 'Potrero' },
                    { v: 'nave', t: 'Nave' },
                    { v: 'galpon', t: 'Galpón' },
                    { v: 'maternidad', t: 'Maternidad' },
                    { v: 'cuarentena', t: 'Cuarentena' },
                    { v: 'engorda', t: 'Engorda' },
                    { v: 'reproduccion', t: 'Reproducción' },
                    { v: 'incubacion', t: 'Incubación' },
                    { v: 'almacen', t: 'Almacén' },
                    { v: 'veterinaria', t: 'Veterinaria' },
                    { v: 'area', t: 'Área' },
                    { v: 'otro', t: 'Otro' },
                ]},
                { key: 'capacity', label: 'Capacidad', type: 'number', min: 0 },
                { key: 'description', label: 'Descripción', type: 'textarea' },
            ],
            row(l) {
                const typeLabels = { corral:'Corral', potrero:'Potrero', nave:'Nave', galpon:'Galpón', maternidad:'Maternidad', cuarentena:'Cuarentena', engorda:'Engorda', reproduccion:'Reproducción', incubacion:'Incubación', almacen:'Almacén', veterinaria:'Veterinaria', area:'Área', otro:'Otro' };
                return `<tr>
                    <td><strong>${l.name}</strong></td>
                    <td>${typeLabels[l.type] || l.type || '—'}</td>
                    <td class="cfg-hide-sm">${l.capacity || '—'}</td>
                    <td>${Settings.actionBtns(l.id, 'location')}</td>
                </tr>`;
            }
        },
        client: {
            api: '/catalogs/clients',
            body: 'clientsBody',
            label: 'Cliente',
            cols: 5,
            fields: [
                { key: 'name', label: 'Nombre / Razón Social *', type: 'text', required: true },
                { key: 'contact_name', label: 'Contacto', type: 'text' },
                { key: 'phone', label: 'Teléfono', type: 'text' },
                { key: 'email', label: 'Email', type: 'text' },
                { key: 'address', label: 'Dirección', type: 'textarea' },
                { key: 'tax_id', label: 'RFC', type: 'text' },
                { key: 'notes', label: 'Notas', type: 'textarea' },
            ],
            row(c) {
                return `<tr>
                    <td><strong>${c.name}</strong></td>
                    <td>${c.contact_name || '—'}</td>
                    <td class="cfg-hide-sm">${c.phone || '—'}</td>
                    <td class="cfg-hide-sm">${c.email || '—'}</td>
                    <td>${Settings.actionBtns(c.id, 'client')}</td>
                </tr>`;
            }
        },
        customField: {
            api: '/custom-fields',
            body: 'fieldsBody',
            label: 'Campo Personalizado',
            cols: 4,
            fields: [
                { key: 'field_name', label: 'Nombre del campo *', type: 'text', required: true },
                { key: 'entity_type', label: 'Módulo *', type: 'select', required: true, options: [
                    { v: 'animals', t: 'Animales' },
                    { v: 'lots', t: 'Lotes' },
                    { v: 'health', t: 'Sanidad' },
                ]},
                { key: 'field_type', label: 'Tipo de campo *', type: 'select', required: true, options: [
                    { v: 'text', t: 'Texto' },
                    { v: 'number', t: 'Número' },
                    { v: 'date', t: 'Fecha' },
                    { v: 'select', t: 'Lista' },
                    { v: 'boolean', t: 'Sí/No' },
                ]},
                { key: 'options', label: 'Opciones (para lista, separar con comas)', type: 'text' },
            ],
            /* Custom fields store field_name not name.
               The key sent to the API must use field_name as "name" equivalent */
            nameKey: 'field_name',
            row(f) {
                const modules = { animals: 'Animales', lots: 'Lotes', health: 'Sanidad' };
                const types = { text: 'Texto', number: 'Número', date: 'Fecha', select: 'Lista', boolean: 'Sí/No' };
                return `<tr>
                    <td><strong>${f.field_name || f.field_label || f.name || ''}</strong></td>
                    <td>${modules[f.entity_type] || f.entity_type || '—'}</td>
                    <td>${types[f.field_type] || f.field_type || 'text'}</td>
                    <td>${Settings.actionBtns(f.id, 'customField')}</td>
                </tr>`;
            },
            /* Custom fields use different POST body shape */
            beforeSave(data) {
                if (!data.field_label) data.field_label = data.field_name;
                return data;
            }
        }
    },

    /* ═══ Init ═══ */
    async init() {
        this.bindTabs();
        this.bindForm();
        await this.loadSettings();
        // Load species first (needed for species-select fields in other catalogs)
        await this.loadCatalog('species');
        // Load the visible tab data
        this.loadActiveTab();
    },

    /* ═══ Tab Navigation ═══ */
    bindTabs() {
        $('#cfgTabs').on('click', '.cfg-tab', (e) => {
            const tab = $(e.currentTarget).data('tab');
            $('.cfg-tab').removeClass('active');
            $(e.currentTarget).addClass('active');
            $('.cfg-panel').removeClass('active');
            $(`#panel-${tab}`).addClass('active');
            this.loadActiveTab();
        });
    },

    loadActiveTab() {
        const tab = $('.cfg-tab.active').data('tab');
        if (!tab || tab === 'general') return;

        // PWA panel
        if (tab === 'app') {
            this.initPWAPanel();
            return;
        }

        // Map tab ids to catalog keys
        const tabMap = {
            'species': 'species',
            'breeds': 'breed',
            'vaccines': 'vaccine',
            'medications': 'medication',
            'diseases': 'disease',
            'inv-categories': 'invCategory',
            'disposal-reasons': 'disposalReason',
            'locations': 'location',
            'custom-fields': 'customField',
        };
        const key = tabMap[tab];
        if (key) this.loadCatalog(key);
    },

    /* ═══ Form submission ═══ */
    bindForm() {
        $('#settingsForm').on('submit', (e) => { e.preventDefault(); this.saveSettings(); });
        $('#catalogForm').on('submit', (e) => { e.preventDefault(); this.saveCatalogItem(); });
    },

    /* ═══ General Settings ═══ */
    async loadSettings() {
        try {
            const res = await API.get('/settings');
            const rows = res.data || [];
            const map = {};
            rows.forEach(r => { map[r.setting_key] = r.setting_value; });
            if (map.ranch_name) $('#settRanchName').val(map.ranch_name);
            if (map.timezone) $('#settTimezone').val(map.timezone);
            if (map.currency) $('#settCurrency').val(map.currency);
        } catch(e) {}
    },

    async saveSettings() {
        const settings = [
            { key: 'ranch_name', value: $('#settRanchName').val(), type: 'string' },
            { key: 'timezone', value: $('#settTimezone').val(), type: 'string' },
            { key: 'currency', value: $('#settCurrency').val(), type: 'string' },
            { key: 'language', value: $('#settLang').val(), type: 'string' },
        ];
        try {
            await API.put('/settings', { settings });
            Toast.success('Configuración guardada');
        } catch(e) { Toast.danger('Error al guardar'); }
    },

    /* ═══ Action buttons helper ═══ */
    actionBtns(id, catalogKey) {
        return `<div class="cfg-actions">
            <button class="cfg-btn-edit" onclick="Settings.editItem(${id},'${catalogKey}')" title="Editar">${typeof Icons !== 'undefined' ? Icons.edit(13) : '✏️'}</button>
            <button class="cfg-btn-del" onclick="Settings.deleteItem(${id},'${catalogKey}')" title="Eliminar">${typeof Icons !== 'undefined' ? Icons.trash(13) : '🗑️'}</button>
        </div>`;
    },

    /* ═══ Generic Catalog CRUD ═══ */
    _cache: {},

    async loadCatalog(key) {
        const cfg = this.catalogs[key];
        if (!cfg) return;
        try {
            const res = await API.get(cfg.api);
            const rows = res.data || [];
            this._cache[key] = rows;

            if (cfg.afterLoad) cfg.afterLoad(rows);

            const html = rows.map(r => cfg.row(r)).join('');
            $(`#${cfg.body}`).html(html || `<tr><td colspan="${cfg.cols}" class="cfg-empty">Sin registros — haz clic en el botón para agregar</td></tr>`);
        } catch(e) {
            $(`#${cfg.body}`).html(`<tr><td colspan="${cfg.cols}" class="cfg-empty">Error al cargar datos</td></tr>`);
        }
    },

    /* Open the universal modal for creating a new item */
    openModal(catalogKey) {
        const cfg = this.catalogs[catalogKey];
        if (!cfg) return;

        $('#catalogModalTitle').text(`Nuevo/a ${cfg.label}`);
        $('#catItemId').val('');
        $('#catType').val(catalogKey);
        this.renderFormFields(cfg.fields, {});
        Modal.open('catalogModal');
    },

    /* Open the universal modal pre-filled for editing */
    async editItem(id, catalogKey) {
        const cfg = this.catalogs[catalogKey];
        if (!cfg) return;

        // Find the item from cache
        let item = (this._cache[catalogKey] || []).find(r => r.id == id);

        // If not in cache, try fetching individually
        if (!item) {
            try {
                const res = await API.get(`${cfg.api}/${id}`);
                item = res.data;
            } catch(e) {
                Toast.danger('No se pudo cargar el registro');
                return;
            }
        }

        if (!item) { Toast.danger('Registro no encontrado'); return; }

        $('#catalogModalTitle').text(`Editar ${cfg.label}`);
        $('#catItemId').val(id);
        $('#catType').val(catalogKey);
        this.renderFormFields(cfg.fields, item);
        Modal.open('catalogModal');
    },

    /* Render form fields dynamically */
    renderFormFields(fields, data) {
        let html = '';
        for (const f of fields) {
            const val = data[f.key] ?? '';
            const req = f.required ? 'required' : '';
            html += `<div class="form-group">`;
            html += `<label class="form-label">${f.label}</label>`;

            if (f.type === 'text') {
                html += `<input type="text" class="form-input" name="${f.key}" value="${this.esc(val)}" ${req} ${f.placeholder ? `placeholder="${f.placeholder}"` : ''}>`;
            } else if (f.type === 'number') {
                html += `<input type="number" class="form-input" name="${f.key}" value="${this.esc(val)}" ${f.min !== undefined ? `min="${f.min}"` : ''} ${f.step ? `step="${f.step}"` : ''} ${req}>`;
            } else if (f.type === 'color') {
                html += `<input type="color" class="form-input" name="${f.key}" value="${val || '#047857'}" style="height:40px;padding:4px">`;
            } else if (f.type === 'textarea') {
                html += `<textarea class="form-input" name="${f.key}" rows="2" ${req}>${this.esc(val)}</textarea>`;
            } else if (f.type === 'select') {
                html += `<select class="form-input" name="${f.key}" ${req}>`;
                (f.options || []).forEach(o => {
                    html += `<option value="${o.v}" ${val == o.v ? 'selected' : ''}>${o.t}</option>`;
                });
                html += `</select>`;
            } else if (f.type === 'species-select') {
                html += `<select class="form-input" name="${f.key}" ${req}>`;
                if (!f.required) html += `<option value="">— Todas —</option>`;
                this.speciesList.forEach(s => {
                    html += `<option value="${s.id}" ${val == s.id ? 'selected' : ''}>${s.name}</option>`;
                });
                html += `</select>`;
            }
            html += `</div>`;
        }
        $('#catalogFormFields').html(html);
    },

    /* Save (create or update) */
    async saveCatalogItem() {
        const catalogKey = $('#catType').val();
        const cfg = this.catalogs[catalogKey];
        if (!cfg) return;

        const id = $('#catItemId').val();
        const data = {};
        cfg.fields.forEach(f => {
            const $el = $(`#catalogForm [name="${f.key}"]`);
            const v = $el.val();
            data[f.key] = (v === '' || v === null) ? null : v;
        });

        // Run beforeSave hook if exists
        if (cfg.beforeSave) cfg.beforeSave(data);

        try {
            if (id) {
                await API.put(`${cfg.api}/${id}`, data);
                Toast.success(`${cfg.label} actualizado/a`);
            } else {
                await API.post(cfg.api, data);
                Toast.success(`${cfg.label} creado/a`);
            }
            Modal.close('catalogModal');
            this.loadCatalog(catalogKey);
            // If species changed, also reload breeds (they depend on species list)
            if (catalogKey === 'species') {
                this.loadCatalog('breed');
            }
        } catch(e) {
            const msg = e?.responseJSON?.message || e?.responseJSON?.errors?.name?.[0] || 'Error al guardar';
            Toast.danger(msg);
        }
    },

    /* Delete with confirmation */
    async deleteItem(id, catalogKey) {
        const cfg = this.catalogs[catalogKey];
        if (!cfg) return;
        if (!confirm(`¿Eliminar ${cfg.label.toLowerCase()}?`)) return;
        try {
            await API.delete(`${cfg.api}/${id}`);
            Toast.success(`${cfg.label} eliminado/a`);
            this.loadCatalog(catalogKey);
        } catch(e) {
            Toast.danger('Error al eliminar');
        }
    },

    /* HTML escape helper */
    esc(v) {
        if (v === null || v === undefined) return '';
        return String(v).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
    },

    // ─── PWA / APP SETTINGS ──────────────────────────────────

    initPWAPanel() {
        // Update display mode
        const isStandalone = window.matchMedia('(display-mode: standalone)').matches || window.navigator.standalone;
        $('#pwaDisplayMode').text(isStandalone ? 'App instalada' : 'Navegador');

        // SW status
        if ('serviceWorker' in navigator) {
            navigator.serviceWorker.getRegistration().then(reg => {
                $('#pwaSWStatus').text(reg ? 'Activo ✓' : 'No registrado');
            });
        } else {
            $('#pwaSWStatus').text('No soportado');
        }

        // Notification permission
        if ('Notification' in window) {
            const perm = Notification.permission;
            const labels = { granted: 'Activadas ✓', denied: 'Bloqueadas ✗', default: 'Sin configurar' };
            $('#pwaNotifPerm').text(labels[perm] || perm);
            if (perm === 'granted') {
                $('#settingsNotifBtn').prop('disabled', true);
                $('#notifBtnText').text('Activadas');
                $('#notifStatus').addClass('success').text('Las notificaciones están activas en este dispositivo.').show();
            } else if (perm === 'denied') {
                $('#settingsNotifBtn').prop('disabled', true);
                $('#notifBtnText').text('Bloqueadas');
                $('#notifStatus').addClass('warning').text('Las notificaciones fueron bloqueadas. Actívalas desde la configuración de tu navegador.').show();
            }
        } else {
            $('#pwaNotifPerm').text('No soportado');
            $('#settingsNotifBtn').prop('disabled', true);
        }

        // Install button state
        const installState = typeof App !== 'undefined' ? App.canInstallPWA() : 'unavailable';
        if (installState === 'installed') {
            $('#settingsInstallBtn').prop('disabled', true).html('<span class="material-icons-round" style="font-size:18px;vertical-align:middle;margin-right:4px">check_circle</span> Ya instalada');
            $('#pwaInstallStatus').addClass('success').text('La app ya está instalada en este dispositivo.').show();
        } else if (installState === 'unavailable') {
            $('#pwaInstallStatus').addClass('info').html('El navegador no ha ofrecido la instalación aún. En <b>Chrome/Edge</b>, puedes instalar desde el menú del navegador (⋮ → Instalar app). En <b>Safari iOS</b>, usa Compartir → Agregar a inicio.').show();
        }
    },

    async installPWA() {
        if (typeof App === 'undefined') return;
        const result = await App.triggerInstall();
        if (result === 'accepted') {
            Toast.success('¡App instalada correctamente!');
            $('#settingsInstallBtn').prop('disabled', true).html('<span class="material-icons-round" style="font-size:18px;vertical-align:middle;margin-right:4px">check_circle</span> Instalada');
            $('#pwaInstallStatus').removeClass('info warning').addClass('success').text('La app se instaló correctamente.').show();
            $('#pwaDisplayMode').text('App instalada');
        } else if (result === 'standalone') {
            Toast.info('La app ya está instalada');
        } else if (result === 'unavailable') {
            Toast.info('Usa el menú del navegador para instalar');
            $('#pwaInstallStatus').removeClass('success warning').addClass('info').html('En <b>Chrome/Edge</b>: menú ⋮ → Instalar app.<br>En <b>Safari iOS</b>: Compartir → Agregar a pantalla de inicio.').show();
        } else {
            Toast.info('Instalación cancelada');
        }
    },

    async requestNotifications() {
        if (!('Notification' in window)) {
            Toast.danger('Tu navegador no soporta notificaciones');
            return;
        }
        try {
            const permission = await Notification.requestPermission();
            if (permission === 'granted') {
                Toast.success('¡Notificaciones activadas!');
                $('#settingsNotifBtn').prop('disabled', true);
                $('#notifBtnText').text('Activadas');
                $('#notifStatus').removeClass('info warning').addClass('success').text('Las notificaciones están activas.').show();
                $('#pwaNotifPerm').text('Activadas ✓');
            } else if (permission === 'denied') {
                Toast.danger('Notificaciones bloqueadas por el navegador');
                $('#notifStatus').removeClass('info success').addClass('warning').text('Las notificaciones fueron bloqueadas. Actívalas desde la configuración de tu navegador.').show();
                $('#pwaNotifPerm').text('Bloqueadas ✗');
            } else {
                Toast.info('Permiso de notificaciones pendiente');
            }
        } catch (e) {
            Toast.danger('Error al solicitar permisos');
        }
    },

    async clearCache() {
        try {
            if (window.caches) {
                const keys = await caches.keys();
                await Promise.all(keys.map(k => caches.delete(k)));
            }
            localStorage.removeItem('pwa-install-dismissed');
            localStorage.removeItem('notification-ask-dismissed');
            Toast.success('Caché limpiado. La página se recargará.');
            setTimeout(() => location.reload(true), 1000);
        } catch (e) {
            Toast.danger('Error al limpiar caché');
        }
    }
};

$(document).ready(() => Settings.init());
