(function () {
    'use strict';

    function asArray(value) {
        if (!value) return [];
        if (Array.isArray(value)) return value;
        try { return JSON.parse(value); } catch (e) { return []; }
    }

    function getSectionData(section) {
        return {
            pendingCaseStatusIds: asArray(section.getAttribute('data-pending-case-status-ids')).map(String),
            pendingPointOptions: asArray(section.getAttribute('data-pending-point-options'))
        };
    }

    function destroyEnhancedSelects(row) {
        row.querySelectorAll('.select2-container, .selectize-control').forEach(function (el) { el.remove(); });
        row.querySelectorAll('select').forEach(function (select) {
            select.classList.remove('select2-hidden-accessible');
            select.removeAttribute('data-select2-id');
            select.removeAttribute('aria-hidden');
            select.style.display = '';
            if (select.selectize) {
                try { select.selectize.destroy(); } catch (e) {}
            }
        });
    }

    function resetDatepicker(input) {
        input.value = '';
        input.removeAttribute('id');
        input.removeAttribute('data-date');
        input.classList.remove('hasDatepicker');
        if (input._flatpickr) {
            try { input._flatpickr.destroy(); } catch (e) {}
        }
        if (window.jQuery) {
            try { window.jQuery(input).removeData('datepicker').removeData('DateTimePicker'); } catch (e) {}
        }
    }

    function initDatepicker(scope) {
        var root = scope || document;
        root.querySelectorAll('input.datepicker').forEach(function (input) {
            if (window.flatpickr) {
                if (input._flatpickr) {
                    try { input._flatpickr.destroy(); } catch (e) {}
                }
                window.flatpickr(input, {
                    dateFormat: 'Y-m-d',
                    allowInput: true
                });
                return;
            }
            if (window.jQuery && window.jQuery.fn && window.jQuery.fn.datepicker) {
                try { window.jQuery(input).datepicker('destroy'); } catch (e) {}
                window.jQuery(input).datepicker({
                    autoclose: true,
                    format: 'yyyy-mm-dd'
                });
            }
        });
    }

    function initEnhancedSelects(scope) {
        var root = scope || document;
        if (window.jQuery && window.jQuery.fn) {
            root.querySelectorAll('select.search-select').forEach(function (select) {
                if (select.getAttribute('data-no-selectize') === 'true') return;
                if (window.jQuery.fn.select2 && !select.classList.contains('select2-hidden-accessible')) {
                    try { window.jQuery(select).select2({ width: '100%' }); } catch (e) {}
                } else if (window.jQuery.fn.selectize && !select.selectize) {
                    try { window.jQuery(select).selectize(); } catch (e) {}
                }
            });
        }
    }

    function updatePendingPoint(row) {
        var section = row.closest('[data-repeatable-section="status"]');
        if (!section) return;
        var data = getSectionData(section);
        var statusSelect = row.querySelector('[data-status-select]');
        var target = row.querySelector('[data-statuses-target]');
        if (!statusSelect || !target) return;

        var selectedStatus = String(statusSelect.value || '');
        var rowIndex = getRowIndex(row);
        var existing = row.querySelector('[data-existing-pendingpoint]');
        var existingValue = existing ? String(existing.value || '') : '';
        var oldSelect = target.querySelector('select[name^="pendingpoint_"]');
        var currentValue = oldSelect ? String(oldSelect.value || '') : existingValue;

        if (data.pendingCaseStatusIds.indexOf(selectedStatus) === -1) {
            target.innerHTML = '';
            return;
        }

        var html = '<label>Pending Points <span class="text-danger">*</span></label>';
        html += '<select class="form-control search-select" name="pendingpoint_' + rowIndex + '" required>';
        html += '<option value="">Choose One</option>';
        data.pendingPointOptions.forEach(function (opt) {
            var id = String(opt.id || '');
            var name = String(opt.name || '');
            var selected = id === currentValue ? ' selected' : '';
            html += '<option value="' + escapeHtml(id) + '"' + selected + '>' + escapeHtml(name) + '</option>';
        });
        html += '</select>';
        target.innerHTML = html;
        initEnhancedSelects(target);
    }

    function escapeHtml(value) {
        return String(value).replace(/[&<>'"]/g, function (ch) {
            return ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', "'": '&#039;', '"': '&quot;' })[ch];
        });
    }

    function getRowIndex(row) {
        var rows = Array.prototype.slice.call(row.parentNode.querySelectorAll('[data-repeatable-row]'));
        return Math.max(0, rows.indexOf(row));
    }

    function reindexSection(section) {
        var rows = section.querySelectorAll('[data-repeatable-row]');
        rows.forEach(function (row, index) {
            var number = row.querySelector('[data-row-number]');
            if (number) number.textContent = index + 1;
            row.querySelectorAll('[name]').forEach(function (field) {
                field.name = field.name.replace(/_\d+$/, '_' + index);
            });
            updatePendingPoint(row);
        });
        var countInput = section.querySelector('input[type="hidden"][name$="_count"], #statuses_count');
        if (countInput) countInput.value = rows.length || 1;
    }

    function resetClonedRow(row) {
        destroyEnhancedSelects(row);
        row.querySelectorAll('[data-existing-pendingpoint]').forEach(function (el) { el.value = ''; });
        row.querySelectorAll('input').forEach(function (input) {
            if (input.type === 'hidden' && /^status_id_/.test(input.name)) { input.value = ''; return; }
            if (input.type === 'hidden' && /_id_\d+$/.test(input.name)) { input.value = ''; return; }
            if (input.classList.contains('datepicker')) { resetDatepicker(input); return; }
            if (input.type !== 'hidden' && input.type !== 'checkbox' && input.type !== 'radio') input.value = '';
            if (input.type === 'checkbox' || input.type === 'radio') input.checked = false;
        });
        row.querySelectorAll('textarea').forEach(function (textarea) { textarea.value = ''; });
        row.querySelectorAll('select').forEach(function (select) { select.selectedIndex = 0; select.value = ''; });
        row.querySelectorAll('[data-statuses-target], [data-satisfied-target]').forEach(function (target) { target.innerHTML = ''; });
    }

    function addRow(section) {
        var firstRow = section.querySelector('[data-repeatable-row]');
        var container = section.querySelector('#statusRows') || (firstRow ? firstRow.parentNode : null);
        if (!container) return;
        var existingRows = container.querySelectorAll('[data-repeatable-row]');
        if (!existingRows.length) return;
        var clone = existingRows[existingRows.length - 1].cloneNode(true);
        resetClonedRow(clone);
        container.appendChild(clone);
        reindexSection(section);
        initDatepicker(clone);
        initEnhancedSelects(clone);
    }

    document.addEventListener('click', function (event) {
        var addButton = event.target.closest('[data-add-repeatable]');
        if (addButton) {
            event.preventDefault();
            event.stopPropagation();
            var section = addButton.closest('[data-repeatable-section]');
            if (section) addRow(section);
            return false;
        }

        var removeButton = event.target.closest('[data-remove-repeatable]');
        if (removeButton) {
            event.preventDefault();
            event.stopPropagation();
            var section = removeButton.closest('[data-repeatable-section]');
            var row = removeButton.closest('[data-repeatable-row]');
            if (section && row) {
                var rows = section.querySelectorAll('[data-repeatable-row]');
                if (rows.length > 1) row.remove();
                reindexSection(section);
            }
            return false;
        }
    }, true);

    document.addEventListener('change', function (event) {
        if (event.target && event.target.matches('[data-status-select]')) {
            var row = event.target.closest('[data-repeatable-row]');
            if (row) updatePendingPoint(row);
        }
    });

    document.addEventListener('DOMContentLoaded', function () {
        document.querySelectorAll('[data-repeatable-section="status"]').forEach(function (section) {
            reindexSection(section);
        });
        initDatepicker(document);
        initEnhancedSelects(document);
    });
})();
