(function () {
    'use strict';

    function ready(fn) {
        if (document.readyState !== 'loading') { fn(); return; }
        document.addEventListener('DOMContentLoaded', fn);
    }

    function reflowCharts() {
        if (window.Highcharts && Highcharts.charts) {
            window.Highcharts.charts.forEach(function (chart) {
                if (chart && chart.reflow) { chart.reflow(); }
            });
        }
    }

    function initSidebar(scope) {
        scope = scope || document;
        var body = document.body;
        var sidebarToggle = scope.querySelector('[data-ngbvd-sidebar-toggle]');
        var mobileToggle = scope.querySelector('[data-ngbvd-mobile-toggle]');
        var backdrop = scope.querySelector('[data-ngbvd-sidebar-backdrop]');
        var savedState = localStorage.getItem('ngbvd.sidebar.collapsed');
        if (savedState === '1') { body.classList.add('ngbvd-sidebar-collapsed'); }

        if (sidebarToggle && sidebarToggle.dataset.bound !== '1') {
            sidebarToggle.dataset.bound = '1';
            sidebarToggle.addEventListener('click', function (event) {
                event.preventDefault();
                body.classList.toggle('ngbvd-sidebar-collapsed');
                localStorage.setItem('ngbvd.sidebar.collapsed', body.classList.contains('ngbvd-sidebar-collapsed') ? '1' : '0');
                setTimeout(reflowCharts, 300);
            });
        }
        if (mobileToggle && mobileToggle.dataset.bound !== '1') {
            mobileToggle.dataset.bound = '1';
            mobileToggle.addEventListener('click', function (event) {
                event.preventDefault();
                body.classList.toggle('ngbvd-sidebar-open');
            });
        }
        if (backdrop && backdrop.dataset.bound !== '1') {
            backdrop.dataset.bound = '1';
            backdrop.addEventListener('click', function () { body.classList.remove('ngbvd-sidebar-open'); });
        }

        scope.querySelectorAll('[data-ngbvd-nav-toggle]').forEach(function (button) {
            if (button.dataset.bound === '1') { return; }
            button.dataset.bound = '1';
            var group = button.closest('.ngbvd-nav-group');
            if (!group) { return; }
            var hasActiveChild = group.querySelector('.ngbvd-nav-submenu .active');
            if (hasActiveChild || button.classList.contains('active')) { group.classList.add('open'); }
            button.addEventListener('click', function (event) {
                event.preventDefault();
                group.classList.toggle('open');
            });
        });
    }

    function initSelects(scope) {
        scope = scope || document;
        if (!(window.jQuery && jQuery.fn && jQuery.fn.selectize)) { return; }
        jQuery(scope).find('select').not('[data-no-selectize]').each(function () {
            if (!this.selectize) {
                try { jQuery(this).selectize({ allowEmptyOption: true }); } catch (e) { /* keep native select */ }
            }
        });
    }

    function initDates(scope) {
        scope = scope || document;
        var inputs = scope.querySelectorAll('.datepicker, input[name*="date"], input[id="from"], input[id="to"]');
        inputs.forEach(function (input) {
            if (!input || input.dataset.ngbvdDateReady === '1' || input.dataset.noModernDatepicker === 'true') { return; }
            input.dataset.ngbvdDateReady = '1';
            input.classList.add('ngbvd-date-input');
            input.removeAttribute('readonly');
            input.setAttribute('autocomplete', 'off');
            input.placeholder = input.placeholder || 'YYYY-MM-DD';
            if (window.flatpickr) {
                try {
                    window.flatpickr(input, {
                        dateFormat: 'Y-m-d',
                        allowInput: true,
                        disableMobile: false,
                        appendTo: document.body,
                        maxDate: input.dataset.allowFuture === 'true' || input.id === 'to' ? null : 'today'
                    });
                } catch (e) {}
            } else {
                try { input.setAttribute('type', 'date'); } catch (e) {}
            }
        });
    }

    function hasUnsafeTableStructure(table) {
        if (!table || table.dataset.noDatatable === 'true' || table.dataset.serverPaginated === 'true') { return true; }
        if (table.querySelector('td[colspan], th[colspan], td[rowspan], th[rowspan]')) { return true; }
        var headerCells = table.querySelectorAll('thead tr:last-child th').length;
        if (!headerCells) { return true; }
        var unsafe = false;
        table.querySelectorAll('tbody tr').forEach(function (row) {
            if (row.children.length && row.children.length !== headerCells) { unsafe = true; }
        });
        return unsafe;
    }

    function initDataTables(scope) {
        scope = scope || document;
        if (!(window.jQuery && jQuery.fn && jQuery.fn.DataTable)) { return; }
        jQuery.fn.dataTable.ext.errMode = 'none';
        jQuery(scope).find('table[data-datatable="true"], table.ngbvd-modern-table').each(function () {
            if (hasUnsafeTableStructure(this)) { this.classList.add('ngbvd-static-table'); return; }
            if (jQuery.fn.DataTable.isDataTable(this)) { return; }
            var hasButtons = !!(jQuery.fn.dataTable && jQuery.fn.dataTable.Buttons);
            try {
                jQuery(this).DataTable({
                    paging: true,
                    pageLength: 10,
                    lengthMenu: [[10, 25, 50, 100, -1], [10, 25, 50, 100, 'All']],
                    responsive: true,
                    autoWidth: false,
                    order: [],
                    dom: hasButtons ? '<"ngbvd-dt-top"lfB>rt<"ngbvd-dt-bottom"ip>' : '<"ngbvd-dt-top"lf>rt<"ngbvd-dt-bottom"ip>',
                    buttons: hasButtons ? ['copy', 'csv', 'excel'] : [],
                    language: { search: 'Search:', lengthMenu: 'Show _MENU_ records', emptyTable: 'No records found', zeroRecords: 'No matching records found' }
                });
            } catch (e) {
                this.classList.add('ngbvd-static-table');
                if (window.console) { console.warn('NGBVD DataTable skipped:', e.message); }
            }
        });
    }

    function initIncidentPicker(scope) {
        scope = scope || document;
        var grid = scope.querySelector ? scope.querySelector('#incidentPickerGrid') : document.getElementById('incidentPickerGrid');
        if (!grid || grid.dataset.ngbvdIncidentReady === '1') { return; }
        grid.dataset.ngbvdIncidentReady = '1';
        var search = scope.querySelector ? scope.querySelector('#incidentSearch') : document.getElementById('incidentSearch');
        var count = scope.querySelector ? scope.querySelector('#incidentSelectedCount') : document.getElementById('incidentSelectedCount');
        var options = Array.prototype.slice.call(grid.querySelectorAll('.ngbvd-incident-option'));
        function refreshCount() {
            var selected = 0;
            options.forEach(function (option) {
                var input = option.querySelector('input[type="checkbox"]');
                var checked = input && input.checked;
                option.classList.toggle('is-selected', checked);
                if (checked) { selected++; }
            });
            if (count) { count.textContent = selected + ' selected'; }
        }
        options.forEach(function (option) {
            var input = option.querySelector('input[type="checkbox"]');
            if (!input) { return; }
            input.addEventListener('change', refreshCount);
        });
        if (search) {
            search.addEventListener('input', function () {
                var query = search.value.toLowerCase().trim();
                options.forEach(function (option) {
                    var name = (option.getAttribute('data-incident-name') || option.textContent || '').toLowerCase();
                    option.classList.toggle('is-hidden', query && name.indexOf(query) === -1);
                });
            });
        }
        refreshCount();
    }

    function initAsyncLinks(scope) {
        scope = scope || document;
        scope.querySelectorAll('a[data-ngbvd-async="true"]').forEach(function (link) {
            if (link.dataset.bound === '1') { return; }
            link.dataset.bound = '1';
            link.addEventListener('click', function (event) {
                if (!window.fetch || !window.DOMParser) { return; }
                if (link.target || link.href.indexOf(window.location.origin) !== 0) { return; }
                var container = document.getElementById('ngbvd-page-content');
                if (!container) { return; }
                event.preventDefault();
                container.classList.add('ngbvd-loading');
                fetch(link.href, { headers: { 'X-Requested-With': 'XMLHttpRequest' } })
                    .then(function (response) { return response.text(); })
                    .then(function (html) {
                        var doc = new DOMParser().parseFromString(html, 'text/html');
                        var next = doc.getElementById('ngbvd-page-content');
                        if (!next) { window.location.href = link.href; return; }
                        container.innerHTML = next.innerHTML;
                        window.history.pushState({}, '', link.href);
                        container.classList.remove('ngbvd-loading');
                        window.NGBVDInit(container);
                    })
                    .catch(function () { window.location.href = link.href; });
            });
        });
    }

    window.NGBVDInit = function (scope) {
        scope = scope || document;
        initSidebar(document);
        initSelects(scope);
        initDates(scope);
        initDataTables(scope);
        initIncidentPicker(scope);
        initAsyncLinks(scope);
        setTimeout(reflowCharts, 250);
    };

    ready(function () {
        window.NGBVDInit(document);
        window.addEventListener('resize', function () { setTimeout(reflowCharts, 150); });
        window.addEventListener('load', function () {
            var loader = document.querySelector('.theme-loader');
            if (loader) { loader.style.display = 'none'; }
            setTimeout(reflowCharts, 500);
        });
        setTimeout(function () {
            var loader = document.querySelector('.theme-loader');
            if (loader) { loader.style.display = 'none'; }
        }, 900);
    });
})();

(function(){
    function reindex(section){
        var rows = section.querySelectorAll('[data-repeatable-row]');
        rows.forEach(function(row, index){
            var n = row.querySelector('[data-row-number]'); if(n){ n.textContent = index + 1; }
            row.querySelectorAll('[name]').forEach(function(input){
                var name = input.getAttribute('name');
                if(!name){ return; }
                input.setAttribute('name', name.replace(/_(\d+)(\]|$)/, '_' + index + '$2').replace(/_(\d+)$/, '_' + index));
            });
        });
        var hidden = section.querySelector('input[type="hidden"]'); if(hidden){ hidden.value = rows.length; }
    }
    document.addEventListener('click', function(e){
        var add = e.target.closest('[data-add-repeatable]');
        if(add && add.closest('[data-repeatable-section]')){ return; }
        if(add){
            var type = add.getAttribute('data-add-repeatable');
            var section = document.querySelector('[data-repeatable-section="'+type+'"]');
            var rows = section ? section.querySelectorAll('[data-repeatable-row]') : [];
            if(section && rows.length){
                var clone = rows[rows.length - 1].cloneNode(true);
                clone.querySelectorAll('input, textarea').forEach(function(input){ if(input.type === 'radio' || input.type === 'checkbox'){ input.checked = false; } else { input.value = ''; } });
                clone.querySelectorAll('select').forEach(function(select){ select.selectedIndex = 0; });
                rows[rows.length-1].parentNode.appendChild(clone);
                reindex(section);
                if(window.flatpickr){ clone.querySelectorAll('.datepicker').forEach(function(el){ flatpickr(el, {dateFormat:'Y-m-d', allowInput:true}); }); }
            }
        }
        var remove = e.target.closest('[data-remove-repeatable]');
        if(remove && remove.closest('[data-repeatable-section]')){ return; }
        if(remove){
            var section = remove.closest('[data-repeatable-section]');
            var rows = section.querySelectorAll('[data-repeatable-row]');
            if(rows.length > 1){ remove.closest('[data-repeatable-row]').remove(); reindex(section); }
        }
    });
})();


// Precision behaviour fixes: static modals, better alerts, cascading locations, safer DataTables.
(function(){
    function ready(fn){ if(document.readyState !== 'loading'){ fn(); } else { document.addEventListener('DOMContentLoaded', fn); } }
    function escapeHtml(value){ return String(value || '').replace(/[&<>"']/g,function(s){return {'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[s];}); }
    function selectizeSetOptions($select, rows, placeholder){
        if (!$select || !$select.length) { return; }
        var el = $select[0];
        if (el.selectize) {
            var inst = el.selectize;
            inst.clear(true); inst.clearOptions();
            inst.addOption({id:'', name: placeholder || 'Choose One', text: placeholder || 'Choose One', value:''});
            (rows || []).forEach(function(row){ inst.addOption({id: row.id, value: row.id, name: row.name, text: row.name}); });
            inst.refreshOptions(false);
            inst.setValue('', true);
            return;
        }
        var html = '<option value="">'+escapeHtml(placeholder || 'Choose One')+'</option>';
        (rows || []).forEach(function(row){ html += '<option value="'+escapeHtml(row.id)+'">'+escapeHtml(row.name)+'</option>'; });
        $select.html(html).trigger('change.select2');
        if ($.fn.selectize && !$select.is('[data-no-selectize]')) { try { $select.selectize({ valueField:'id', labelField:'name', searchField:'name', allowEmptyOption:true }); } catch(e){} }
    }
    function findField($origin, names){
        var $form = $origin.closest('form');
        var $scope = $form.length ? $form : $(document.body);
        var selector = names.map(function(n){ return 'select[name="'+n+'"], select#'+n; }).join(',');
        var $field = $scope.find(selector).first();
        return $field.length ? $field : $(selector).first();
    }
    function bindLocations(){
        if (!window.jQuery) { return; }
        $(document).off('change.ngbvdDistrict').on('change.ngbvdDistrict', 'select[name="districtid"], select#districtid, select#district, select[name="incident_districtid"], select[name="district"]', function(){
            var $district = $(this), districtId = $district.val();
            var $sub = findField($district, ['subcountyid','subcounty','incident_subcountyid']);
            var $parish = findField($district, ['parishid','parish','incident_parishid']);
            selectizeSetOptions($parish, [], 'Choose One');
            selectizeSetOptions($sub, [], districtId ? 'Loading sub-counties...' : 'Choose One');
            if (!districtId || !$sub.length) { return; }
            $.get('/findSubcounty', {id: districtId, district_id: districtId})
                .done(function(rows){ selectizeSetOptions($sub, rows, 'Choose One'); })
                .fail(function(){ selectizeSetOptions($sub, [], 'Unable to load sub-counties'); });
        });
        $(document).off('change.ngbvdSubcounty').on('change.ngbvdSubcounty', 'select[name="subcountyid"], select#subcountyid, select#subcounty, select[name="incident_subcountyid"], select[name="subcounty"]', function(){
            var $sub = $(this), subId = $sub.val();
            var $form = $sub.closest('form');
            var districtId = ($form.length ? $form : $(document)).find('select[name="districtid"], select#districtid, select#district').first().val();
            var $parish = findField($sub, ['parishid','parish','incident_parishid']);
            selectizeSetOptions($parish, [], subId ? 'Loading parishes...' : 'Choose One');
            if (!subId || !$parish.length) { return; }
            $.get('/findParish', {id: subId, subcounty_id: subId, district_id: districtId})
                .done(function(rows){ selectizeSetOptions($parish, rows, 'Choose One'); })
                .fail(function(){ selectizeSetOptions($parish, [], 'Unable to load parishes'); });
        });
    }
    function bindModernConfirms(){
        if (!window.jQuery) { return; }
        $(document).on('click', '[data-confirm-action]', function(e){
            var link = this;
            e.preventDefault();
            var message = link.getAttribute('data-confirm-message') || 'Are you sure you want to continue?';
            if (window.Swal) {
                Swal.fire({title:'Please confirm', text:message, icon:'warning', showCancelButton:true, confirmButtonText:'Yes, continue', cancelButtonText:'Cancel', confirmButtonColor:'#f5ad05'})
                    .then(function(result){ if(result.isConfirmed){ window.location.href = link.href; } });
            } else if (window.confirm(message)) {
                window.location.href = link.href;
            }
        });
    }
    ready(function(){
        if (window.jQuery && $.fn.modal) {
            $('.modal').attr('data-backdrop','static').attr('data-keyboard','false');
            $(document).on('show.bs.modal', '.modal', function(){ var modal = $(this).data('bs.modal'); if(modal && modal._config){ modal._config.backdrop='static'; modal._config.keyboard=false; } });
        }
        bindLocations();
        bindModernConfirms();
        if(window.jQuery && $.fn && $.fn.dataTable){ $.fn.dataTable.ext.errMode = 'none'; }
    });
})();
