/*global document, jQuery */
jQuery(document).ready(function ($) {

    // General-purpose request gating system for list actions
    // Prevents concurrent requests and race conditions
    var GFListActionGate = {
        activeRequests: {},

        /**
         * Check if an action is currently in progress for a specific item
         * @param {string} actionType - Type of action (e.g., 'duplicate', 'delete')
         * @param {number} itemId - ID of the item being acted upon
         * @returns {boolean} True if request is in progress, false otherwise
         */
        isRequestInProgress: function(actionType, itemId) {
            var key = actionType + '_' + itemId;
            return this.activeRequests[key] === true;
        },

        /**
         * Mark an action as in progress
         * @param {string} actionType - Type of action
         * @param {number} itemId - ID of the item
         */
        markRequestStart: function(actionType, itemId) {
            var key = actionType + '_' + itemId;
            this.activeRequests[key] = true;
        },

        /**
         * Mark an action as complete
         * @param {string} actionType - Type of action
         * @param {number} itemId - ID of the item
         */
        markRequestEnd: function(actionType, itemId) {
            var key = actionType + '_' + itemId;
            delete this.activeRequests[key];
        }
    };

    // Bulk action Apply button enable/disable and modal wiring
    // Each toolbar (top/bottom) is handled independently via shared CSS classes.

    function updateBulkApply($select) {
        var actionVal  = $select.val();
        var anyChecked = $('.griffinforms-listitem-cb:checked').length > 0;
        var $applyBtn  = $select.closest('.bulkactions').find('.gf-bulk-action-apply');

        if (actionVal && actionVal !== '-1' && anyChecked) {
            var modalMap = {};
            try { modalMap = JSON.parse($select.attr('data-gf-modal-map') || '{}'); } catch (e) {}
            var target = modalMap[actionVal] ? '#' + modalMap[actionVal] : '';
            $applyBtn.removeClass('disabled').attr('data-bs-target', target);
        } else {
            $applyBtn.addClass('disabled').attr('data-bs-target', '');
        }
    }

    function updateAllBulkApply() {
        $('.gf-bulk-action-select').each(function () {
            updateBulkApply($(this));
        });
    }

    $(document).on('change', '#cb-select-all-1', function () {
        $('.griffinforms-listitem-cb').prop('checked', $(this).is(':checked'));
        updateAllBulkApply();
    });

    $(document).on('change', '.gf-bulk-action-select', function () {
        updateBulkApply($(this));
    });

    $(document).on('change', '.griffinforms-listitem-cb', updateAllBulkApply);

    $(".griffinforms-datepicker").datepicker({
        dateFormat: "yy-mm-dd",
        altFormat: "yy-mm-dd"
    });

    var highlightItemId = sessionStorage.getItem('highlightItemId');
    if (highlightItemId) {
        var itemRow = $("tr[data-gf-itemid='" + highlightItemId + "']");
        itemRow.addClass('griffinforms-new-item-highlight');
        sessionStorage.removeItem('highlightItemId');

        setTimeout(function() {
            itemRow.removeClass('griffinforms-new-item-highlight');
        }, 3000);
    }

    // Duplicate item row action
    $(document).on('click', '.griffinforms-formtheme-duplicate-btn', function(e) {
        e.preventDefault();

        var $button = $(this);
        var itemId = $button.data('gf-id');
        var itemType = $button.data('gf-type');
        var nonce = $button.data('gf-nonce');
        var actionType = 'duplicate';

        // Check if a request is already in progress for this item
        if (GFListActionGate.isRequestInProgress(actionType, itemId)) {
            return;
        }

        // Mark request as in progress
        GFListActionGate.markRequestStart(actionType, itemId);

        // Disable button during request
        $button.prop('disabled', true);
        var originalText = $button.text();
        $button.text('Duplicating...');

        $.ajax({
            url: ajaxurl,
            type: 'POST',
            dataType: 'json',
            data: {
                action: 'duplicateItem',
                item_id: itemId,
                item_type: itemType,
                nonce: nonce
            },
            success: function(response) {
                if (response.status === true) {
                    // Store the new item ID in session storage for highlighting
                    sessionStorage.setItem('highlightItemId', response.new_item_id);

                    // Reload the page to show the new item
                    setTimeout(function() {
                        location.reload();
                    }, 500);
                } else {
                    // Show error message using WordPress notice
                    var notice = '<div class="notice notice-error is-dismissible gf-is-dismissible"><p>' + response.message + '</p><button type="button" class="notice-dismiss gf-dismiss-notice"><span class="screen-reader-text">Dismiss this notice.</span></button></div>';
                    $(notice).insertBefore('.wp-header-end');

                    // Re-enable button
                    $button.prop('disabled', false);
                    $button.text(originalText);

                    // Mark request as complete
                    GFListActionGate.markRequestEnd(actionType, itemId);
                }
            },
            error: function() {
                var errorMessage = 'An error occurred while duplicating the theme.';
                var notice = '<div class="notice notice-error is-dismissible gf-is-dismissible"><p>' + errorMessage + '</p><button type="button" class="notice-dismiss gf-dismiss-notice"><span class="screen-reader-text">Dismiss this notice.</span></button></div>';
                $(notice).insertBefore('.wp-header-end');

                // Re-enable button
                $button.prop('disabled', false);
                $button.text(originalText);

                // Mark request as complete
                GFListActionGate.markRequestEnd(actionType, itemId);
            }
        });
    });

    $(document).on('click', '.gf-run-retention-cleanup', function(e) {
        e.preventDefault();

        var $button = $(this);
        var formId = $button.data('gf-form-id');
        var nonce = $button.data('gf-nonce');

        if (!formId || !nonce) {
            return;
        }

        $button.addClass('disabled').attr('aria-disabled', 'true');
        var originalText = $button.text();
        $button.text('Cleaning...');

        $.ajax({
            url: ajaxurl,
            type: 'POST',
            dataType: 'json',
            data: {
                action: 'griffinforms_run_retention_cleanup',
                form_id: formId,
                nonce: nonce
            },
            success: function(response) {
                if (response && response.success) {
                    var deleted = response.data && typeof response.data.deleted !== 'undefined' ? response.data.deleted : 0;
                    var notice = '<div class="notice notice-success is-dismissible gf-is-dismissible"><p>Cleanup completed. Deleted ' + deleted + ' submissions.</p><button type="button" class="notice-dismiss gf-dismiss-notice"><span class="screen-reader-text">Dismiss this notice.</span></button></div>';
                    $(notice).insertBefore('.wp-header-end');
                    setTimeout(function() { location.reload(); }, 800);
                } else {
                    var message = response && response.data && response.data.message ? response.data.message : 'Cleanup failed.';
                    var errorNotice = '<div class="notice notice-error is-dismissible gf-is-dismissible"><p>' + message + '</p><button type="button" class="notice-dismiss gf-dismiss-notice"><span class="screen-reader-text">Dismiss this notice.</span></button></div>';
                    $(errorNotice).insertBefore('.wp-header-end');
                    $button.removeClass('disabled').attr('aria-disabled', 'false');
                    $button.text(originalText);
                }
            },
            error: function() {
                var errorNotice = '<div class="notice notice-error is-dismissible gf-is-dismissible"><p>Cleanup failed. Please try again.</p><button type="button" class="notice-dismiss gf-dismiss-notice"><span class="screen-reader-text">Dismiss this notice.</span></button></div>';
                $(errorNotice).insertBefore('.wp-header-end');
                $button.removeClass('disabled').attr('aria-disabled', 'false');
                $button.text(originalText);
            }
        });
    });

    // ============================================================
    // Column Manager
    // ============================================================
    (function () {
        var CM = (typeof griffinformsListsData !== 'undefined') ? griffinformsListsData.column_manager : null;
        if (!CM) { return; }

        var colList    = document.getElementById('gf-col-list');
        var sizeSelect = document.getElementById('gf-list-size');
        var warning    = document.getElementById('gf-col-crowding-warning');
        var saveBtn    = document.querySelector('.gf-col-save-btn');
        var resetBtn   = document.querySelector('.gf-col-reset-btn');

        if (!colList || !saveBtn || !resetBtn) { return; }

        // Build items-per-page select
        CM.list_size_options.forEach(function (n) {
            var opt = document.createElement('option');
            opt.value = n;
            opt.textContent = n;
            if (n === CM.list_size) { opt.selected = true; }
            sizeSelect.appendChild(opt);
        });

        // Build column rows
        function buildRows() {
            colList.innerHTML = '';
            CM.columns.forEach(function (col) {
                var li = document.createElement('li');
                li.className = 'list-group-item px-0 py-2';
                li.dataset.key = col.key;

                var handle   = '<span class="gf-col-drag-handle me-2 text-muted" style="cursor:grab;user-select:none"><img src="' + escAttr(CM.drag_handle_url) + '" alt="" width="20" height="20" aria-hidden="true" style="opacity:0.5;display:block"></span>';
                var cbId     = 'gf-col-cb-' + col.key;
                var checked  = col.active ? ' checked' : '';
                var checkbox = '<input type="checkbox" class="form-check-input me-2 gf-col-toggle" id="' + cbId + '"' + checked + ' data-key="' + escAttr(col.key) + '">';
                var cbLabel  = '<label class="form-check-label flex-grow-1" for="' + cbId + '">' + escHtml(col.label || col.key) + '</label>';

                var variantHtml = '';
                if (col.variants && Object.keys(col.variants).length > 0) {
                    variantHtml = '<select class="form-select form-select-sm gf-col-variant ms-2" style="width:auto" data-key="' + escAttr(col.key) + '">';
                    Object.keys(col.variants).forEach(function (vk) {
                        var sel = col.saved_variant === vk ? ' selected' : '';
                        variantHtml += '<option value="' + escAttr(vk) + '"' + sel + '>' + escHtml(col.variants[vk]) + '</option>';
                    });
                    variantHtml += '</select>';
                }

                var widthVal  = col.saved_width || '';
                var widthHtml = '<input type="text" class="form-control form-control-sm gf-col-width ms-2" placeholder="e.g. 10%" value="' + escAttr(widthVal) + '" data-key="' + escAttr(col.key) + '" style="width:80px">';

                li.innerHTML = '<div class="d-flex align-items-center">' + handle + checkbox + cbLabel + variantHtml + widthHtml + '</div>';
                colList.appendChild(li);
            });

            updateCrowdingWarning();
        }

        buildRows();

        // jQuery UI Sortable — already enqueued globally (admin/stylesheets.php line 91)
        $('#gf-col-list').sortable({
            handle: '.gf-col-drag-handle',
            axis: 'y',
            placeholder: 'gf-col-sort-placeholder',
            tolerance: 'pointer'
        });

        // Auto-append % to bare numbers in width inputs
        function normalizeWidth(val) {
            var v = val.trim();
            return (v !== '' && /^\d+(\.\d+)?$/.test(v)) ? v + '%' : v;
        }

        colList.addEventListener('blur', function (e) {
            if (e.target.classList.contains('gf-col-width')) {
                e.target.value = normalizeWidth(e.target.value);
            }
        }, true);

        // Crowding warning
        function updateCrowdingWarning() {
            var activeCount = colList.querySelectorAll('.gf-col-toggle:checked').length;
            if (activeCount >= CM.crowding_threshold) {
                warning.classList.remove('d-none');
            } else {
                warning.classList.add('d-none');
            }
        }

        colList.addEventListener('change', function (e) {
            if (e.target.classList.contains('gf-col-toggle')) {
                updateCrowdingWarning();
            }
        });

        // Save
        saveBtn.addEventListener('click', function () {
            var rows     = colList.querySelectorAll('[data-key]');
            var columns  = [];
            var variants = {};
            var widths   = {};

            rows.forEach(function (li) {
                var key = li.dataset.key;
                var cb  = li.querySelector('.gf-col-toggle');
                if (cb && cb.checked) {
                    columns.push(key);
                }
                var variantSel = li.querySelector('.gf-col-variant');
                if (variantSel) {
                    variants[key] = variantSel.value;
                }
                var widthInput = li.querySelector('.gf-col-width');
                if (widthInput && widthInput.value.trim() !== '') {
                    widths[key] = normalizeWidth(widthInput.value);
                }
            });

            var listSize = parseInt(sizeSelect.value, 10) || 10;
            var data     = new FormData();
            data.append('action',    CM.save_action);
            data.append('nonce',     CM.nonce);
            data.append('list_type', CM.list_type);
            data.append('list_size', listSize);
            columns.forEach(function (c) { data.append('columns[]', c); });
            Object.keys(variants).forEach(function (k) { data.append('variants[' + k + ']', variants[k]); });
            Object.keys(widths).forEach(function (k)   { data.append('widths['   + k + ']', widths[k]);   });

            saveBtn.disabled = true;
            fetch(CM.ajax_url, { method: 'POST', body: data, credentials: 'same-origin' })
                .then(function (r) { return r.json(); })
                .then(function (res) {
                    if (res.success) {
                        window.location.reload();
                    } else {
                        saveBtn.disabled = false;
                        window.alert((res.data && res.data.message) ? res.data.message : 'Save failed.');
                    }
                })
                .catch(function () { saveBtn.disabled = false; });
        });

        // Reset
        resetBtn.addEventListener('click', function () {
            var i18n          = (typeof griffinformsListsData !== 'undefined') ? griffinformsListsData.i18n : {};
            var confirmText   = i18n.confirmReset || 'Reset columns to defaults?';
            if (!window.confirm(confirmText)) { return; }

            var data = new FormData();
            data.append('action',    CM.reset_action);
            data.append('nonce',     CM.nonce);
            data.append('list_type', CM.list_type);

            resetBtn.disabled = true;
            fetch(CM.ajax_url, { method: 'POST', body: data, credentials: 'same-origin' })
                .then(function (r) { return r.json(); })
                .then(function (res) {
                    if (res.success) {
                        window.location.reload();
                    } else {
                        resetBtn.disabled = false;
                    }
                })
                .catch(function () { resetBtn.disabled = false; });
        });

        function escHtml(str) {
            return String(str)
                .replace(/&/g, '&amp;')
                .replace(/</g, '&lt;')
                .replace(/>/g, '&gt;');
        }

        function escAttr(str) {
            return String(str).replace(/"/g, '&quot;');
        }
    }());
    // ============================================================
    // End Column Manager
    // ============================================================
});
