/*
 * NGBVD data-entry save/cascade fixes.
 * Scope: JavaScript behaviour only. No layout, visual styling or UI redesign changes.
 */
(function ($) {
    'use strict';

    if (!$) { return; }

    function csrfToken() {
        return $('meta[name="csrf-token"]').attr('content') || $('input[name="_token"]').first().val() || '';
    }

    function asArray(payload) {
        if (!payload) { return []; }
        if (Array.isArray(payload)) { return payload; }
        if (Array.isArray(payload.data)) { return payload.data; }
        if (Array.isArray(payload.items)) { return payload.items; }
        if (Array.isArray(payload.results)) { return payload.results; }
        return [];
    }

    function labelOf(item) {
        return item.name || item.title || item.label || item.text || item.value || '';
    }

    function valueOf(item) {
        return item.id || item.uuid || item.value || '';
    }

    function hasSelectize($select) {
        return $select.length && $select[0] && $select[0].selectize;
    }

    function clearAndLoadSelect($select, payload, placeholder, selectedValue, allowEmptyWhenNoData) {
        var items = asArray(payload);
        var selected = selectedValue || $select.attr('data-selected') || $select.val() || '';

        if (hasSelectize($select)) {
            var control = $select[0].selectize;
            control.clear(true);
            control.clearOptions();
            control.addOption({ value: '', text: placeholder || 'Choose One' });
            items.forEach(function (item) {
                var value = String(valueOf(item));
                if (value !== '') {
                    control.addOption({ value: value, text: labelOf(item) });
                }
            });
            control.refreshOptions(false);
            if (selected) { control.setValue(String(selected), true); }
        } else {
            var html = '<option value="">' + (placeholder || 'Choose One') + '</option>';
            items.forEach(function (item) {
                var value = String(valueOf(item));
                var text = labelOf(item);
                var isSelected = selected && String(selected) === value ? ' selected' : '';
                if (value !== '') {
                    html += '<option value="' + value + '"' + isSelected + '>' + text + '</option>';
                }
            });
            $select.html(html);
        }

        if (allowEmptyWhenNoData && items.length === 0) {
            $select.prop('required', false).removeAttr('required').attr('data-required-suspended', 'true');
        } else if ($select.attr('data-required-suspended') === 'true') {
            $select.prop('required', true).attr('required', 'required').removeAttr('data-required-suspended');
        }
    }

    function syncSurvivorCode() {
        var ref = $.trim($('#crb_number').val() || '');
        if (ref !== '') {
            $('#survivor_code').val(ref);
        }
    }

    function getNationalStatusCategorySelect() {
        var $select = $('#nstatuscategory, [name="ns_categornsy"]').first();
        if (!$select.length && $('#ns_category').length) {
            $('#ns_category').html('<select class="form-control search-select" name="ns_categornsy" id="nstatuscategory" data-national-status-category="true" required><option value="">Choose One</option></select>');
            $select = $('#nstatuscategory');
        }
        return $select;
    }

    function cascadeNationalStatusCategory(preselected) {
        var $status = $('#nstatus');
        var $category = getNationalStatusCategorySelect();
        var statusId = $status.val();

        if (!$status.length || !$category.length) { return; }

        if (!statusId) {
            clearAndLoadSelect($category, [], 'Choose One', null, true);
            return;
        }

        $category.prop('disabled', true).attr('data-disabled-for-loading', 'true');

        $.ajax({
            type: 'GET',
            url: window.NGBVD_FIND_NS_CATEGORY_URL || '/findNSCategory',
            data: { id: statusId },
            headers: { 'X-CSRF-TOKEN': csrfToken() }
        }).done(function (payload) {
            clearAndLoadSelect($category, payload, 'Choose One', preselected, true);
        }).fail(function () {
            clearAndLoadSelect($category, [], 'Choose One', null, true);
        }).always(function () {
            $category.prop('disabled', false).removeAttr('data-disabled-for-loading');
        });
    }

    function updateReporterRelationRequired() {
        var type = $('input[name="reporter_type"]:checked').val();
        var $relation = $('[name="reporter_relation"]').first();
        if (!$relation.length) { return; }

        if (String(type) === '2') {
            $relation.prop('required', true).attr('required', 'required');
        } else {
            // When the reporter is the survivor, relationship-to-survivor is not applicable.
            // Keeping it required causes the browser to block submission silently when Selectize hides the select.
            $relation.prop('required', false).removeAttr('required');
        }
    }

    function markSubmitAction($button) {
        var $form = $button.closest('form');
        var $action = $form.find('input[name="action"]').first();
        if (!$action.length) {
            $action = $('<input type="hidden" name="action" id="action">').appendTo($form);
        }

        if ($button.hasClass('draftsave') || $button.attr('data-save-draft') === 'true') {
            $action.val('draft');
        } else if ($button.hasClass('savecontinue') || $button.hasClass('savebutton')) {
            $action.val('save_continue');
        } else if (!$action.val()) {
            $action.val('save');
        }
    }

    function prepareBeforeSubmit($form) {
        syncSurvivorCode();
        updateReporterRelationRequired();

        var $category = getNationalStatusCategorySelect();
        if ($category.length && !$category.val() && $category.find('option').length <= 1) {
            $category.prop('required', false).removeAttr('required').attr('data-required-suspended', 'true');
        }

        $form.find(':input:disabled[data-disabled-for-loading="true"]').prop('disabled', false).removeAttr('data-disabled-for-loading');
    }

    function boot() {
        $(document).on('input keyup change paste', '#crb_number', function () {
            setTimeout(syncSurvivorCode, 0);
        });

        $(document).on('change', '#nstatus', function () {
            cascadeNationalStatusCategory(null);
        });

        $(document).on('change', 'input[name="reporter_type"]', updateReporterRelationRequired);

        $(document).on('click', 'form#indexform button[type="submit"], form.ngbvd-form-section button[type="submit"]', function () {
            markSubmitAction($(this));
            prepareBeforeSubmit($(this).closest('form'));
        });

        $(document).on('submit', 'form#indexform, form.ngbvd-form-section', function () {
            prepareBeforeSubmit($(this));
            return true;
        });

        syncSurvivorCode();
        updateReporterRelationRequired();

        var $status = $('#nstatus');
        var $category = getNationalStatusCategorySelect();
        if ($status.length && $status.val()) {
            var hasRealCategory = $category.find('option').filter(function () {
                return String($(this).val() || '') !== '';
            }).length > 0;
            if (!hasRealCategory) {
                cascadeNationalStatusCategory($category.attr('data-selected') || null);
            }
        }
    }

    $(document).ready(boot);
})(window.jQuery);
