/*
 * NGBVD Data Entry Cascade Restore
 * Fixes dynamic cascades that can break when form-state restoration or newer UI wrappers are applied.
 * Covers:
 * - Disability Status Yes -> Disability Category dropdown
 * - Case Status Pending -> Pending Points dropdown
 * - Pending Points -> optional Satisfaction dropdown if enabled by existing endpoint
 */
(function (window, document) {
    'use strict';

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

    function hasJquery() {
        return !!window.jQuery;
    }

    function csrfToken() {
        var meta = document.querySelector('meta[name="csrf-token"]');
        return meta ? meta.getAttribute('content') : '';
    }

    function escapeHtml(value) {
        return String(value === null || typeof value === 'undefined' ? '' : value)
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#039;');
    }

    function parseJsonAttribute(element, name, fallback) {
        if (!element) return fallback;
        var raw = element.getAttribute(name);
        if (!raw) return fallback;
        try { return JSON.parse(raw); } catch (e) { return fallback; }
    }

    function ajaxJson(url, data, success, failure) {
        if (hasJquery()) {
            window.jQuery.ajax({
                type: 'GET',
                url: url,
                data: data || {},
                dataType: 'json',
                headers: {'X-CSRF-TOKEN': csrfToken(), 'Accept': 'application/json'},
                success: function (response) { success(response || []); },
                error: function (xhr) { if (failure) failure(xhr); }
            });
            return;
        }

        var params = new URLSearchParams(data || {});
        fetch(url + (params.toString() ? '?' + params.toString() : ''), {
            credentials: 'same-origin',
            headers: {'Accept': 'application/json', 'X-CSRF-TOKEN': csrfToken()}
        }).then(function (response) { return response.json(); })
          .then(function (json) { success(json || []); })
          .catch(function (error) { if (failure) failure(error); });
    }

    function initEnhancedSelect(select) {
        if (!select) return;
        if (!select.classList.contains('search-select')) {
            select.classList.add('search-select');
        }

        if (hasJquery() && window.jQuery.fn && window.jQuery.fn.selectize && !select.selectize) {
            try {
                window.jQuery(select).selectize({
                    create: false,
                    allowEmptyOption: true,
                    sortField: 'text'
                });
            } catch (e) {}
        }
    }

    function selectedRadioValue(name) {
        var checked = document.querySelector('input[name="' + name + '"]:checked');
        return checked ? checked.value : null;
    }

    function findDisabilityWrapper() {
        return document.querySelector('[data-disability-wrapper]') || document.getElementById('disabilityWrapper') || document.getElementById('disability');
    }

    function renderDisabilityDropdown(rows, selectedValue) {
        var wrapper = findDisabilityWrapper();
        if (!wrapper) return;

        var options = '<option value="">Choose One</option>';
        (rows || []).forEach(function (row) {
            var selected = String(row.id) === String(selectedValue || '') ? ' selected' : '';
            options += '<option value="' + escapeHtml(row.id) + '"' + selected + '>' + escapeHtml(row.name) + '</option>';
        });

        wrapper.innerHTML =
            '<label class="col-sm-4 control-label">Disability Category:<span class="text-danger"> *</span></label>' +
            '<div class="col-md-8">' +
                '<select class="form-control search-select" name="disability" id="disability_category" required>' + options + '</select>' +
            '</div>';

        initEnhancedSelect(wrapper.querySelector('select'));
    }

    function clearDisabilityDropdown() {
        var wrapper = findDisabilityWrapper();
        if (wrapper) wrapper.innerHTML = '';
    }

    function handleDisabilityChange() {
        var value = selectedRadioValue('pwd');
        var wrapper = findDisabilityWrapper();
        var selectedValue = wrapper ? (wrapper.getAttribute('data-selected-disability') || '') : '';

        if (String(value) !== '1') {
            clearDisabilityDropdown();
            return;
        }

        ajaxJson('/findDisability', {id: value}, function (rows) {
            renderDisabilityDropdown(rows, selectedValue);
        }, function () {
            var wrapper = findDisabilityWrapper();
            if (wrapper) {
                wrapper.innerHTML = '<div class="col-md-12"><div class="alert alert-warning mb-0">Disability categories could not be loaded. Please refresh and try again.</div></div>';
            }
        });
    }

    function rowIndexFromSelect(select) {
        var name = select ? (select.getAttribute('name') || '') : '';
        var match = name.match(/_(\d+)$/);
        return match ? match[1] : '0';
    }

    function nearestStatusRow(element) {
        if (!element) return null;
        return element.closest('[data-repeatable-row="status"]') || element.closest('.ngbvd-repeat-card') || element.closest('form');
    }

    function statusSectionFor(element) {
        return element ? element.closest('[data-repeatable-section="status"]') : document.querySelector('[data-repeatable-section="status"]');
    }

    function statusIsPending(select) {
        var section = statusSectionFor(select);
        var pendingIds = parseJsonAttribute(section, 'data-pending-case-status-ids', ['1']).map(String);
        var value = String(select.value || '');
        var selectedText = '';
        if (select.selectedIndex >= 0 && select.options[select.selectedIndex]) {
            selectedText = String(select.options[select.selectedIndex].text || '').toLowerCase();
        }

        return pendingIds.indexOf(value) !== -1 || selectedText.indexOf('pending') !== -1;
    }

    function pendingOptionsFor(select) {
        var section = statusSectionFor(select);
        return parseJsonAttribute(section, 'data-pending-point-options', []);
    }

    function destroySelectizeIfAny(select) {
        if (select && select.selectize) {
            try { select.selectize.destroy(); } catch (e) {}
        }
    }

    function renderPendingPoint(select, selectedValue) {
        var row = nearestStatusRow(select);
        if (!row) return;
        var target = row.querySelector('[data-statuses-target]') || row.querySelector('#statuses');
        if (!target) return;

        if (!statusIsPending(select)) {
            target.innerHTML = '';
            var satTarget = row.querySelector('[data-satisfied-target]') || row.querySelector('#satisfied');
            if (satTarget) satTarget.innerHTML = '';
            return;
        }

        var index = rowIndexFromSelect(select);
        var optionsData = pendingOptionsFor(select);
        var existing = row.querySelector('[data-existing-pendingpoint]');
        selectedValue = selectedValue || (existing ? existing.value : '');

        var options = '<option value="">Choose One</option>';
        (optionsData || []).forEach(function (item) {
            var selected = String(item.id) === String(selectedValue || '') ? ' selected' : '';
            options += '<option value="' + escapeHtml(item.id) + '"' + selected + '>' + escapeHtml(item.name) + '</option>';
        });

        target.innerHTML =
            '<label>Pending Points <span class="text-danger">*</span></label>' +
            '<select class="form-control search-select" name="pendingpoint_' + escapeHtml(index) + '" data-pending-point-select required>' + options + '</select>';

        var pendingSelect = target.querySelector('select');
        initEnhancedSelect(pendingSelect);

        if (pendingSelect && pendingSelect.value) {
            renderSatisfaction(pendingSelect);
        }
    }

    function renderSatisfaction(pendingSelect) {
        var row = nearestStatusRow(pendingSelect);
        if (!row) return;
        var target = row.querySelector('[data-satisfied-target]') || row.querySelector('#satisfied');
        if (!target) return;

        var pendingPointId = pendingSelect.value;
        if (!pendingPointId) {
            target.innerHTML = '';
            return;
        }

        ajaxJson('/findSatisfaction', {id: pendingPointId}, function (rows) {
            if (!rows || !rows.length) {
                target.innerHTML = '';
                return;
            }

            var index = rowIndexFromSelect(row.querySelector('[data-status-select]'));
            var options = '<option value="">Choose One</option>';
            rows.forEach(function (item) {
                options += '<option value="' + escapeHtml(item.id) + '">' + escapeHtml(item.name) + '</option>';
            });

            target.innerHTML =
                '<label>Level of Satisfaction</label>' +
                '<select class="form-control search-select" name="satisfaction_' + escapeHtml(index) + '" data-satisfaction-select>' + options + '</select>';
            initEnhancedSelect(target.querySelector('select'));
        }, function () {
            target.innerHTML = '';
        });
    }

    function handleStatusChange(event) {
        var select = event.target;
        if (!select || !select.matches('[data-status-select], #reportedto')) return;
        renderPendingPoint(select, '');
    }

    function handlePendingPointChange(event) {
        var select = event.target;
        if (!select || !select.matches('[data-pending-point-select], #pendingpoint, select[name^="pendingpoint"]')) return;
        renderSatisfaction(select);
    }

    function initialiseExistingStatusRows() {
        document.querySelectorAll('[data-status-select], #reportedto').forEach(function (select) {
            renderPendingPoint(select, '');
        });
    }

    ready(function () {
        document.addEventListener('change', function (event) {
            if (event.target && event.target.matches('input[name="pwd"]')) {
                handleDisabilityChange();
            }
            handleStatusChange(event);
            handlePendingPointChange(event);
        }, true);

        // Delay slightly so selectize/form-state restoration can finish first.
        setTimeout(function () {
            handleDisabilityChange();
            initialiseExistingStatusRows();
        }, 250);
    });
})(window, document);
