(function ($) {
    if (typeof acf === 'undefined') {
        return;
    }

    acf.addAction('ready', function () {
        // Layout: two columns side by side
        var $newGroup = $('#acf-group_shh_content_by_group');
        var $oldGroup = $('#acf-group_655529b6683fe');

        if ($newGroup.length && $oldGroup.length) {
            var $columnsWrapper = $('<div style="display:flex;gap:16px;align-items:flex-start;"></div>');
            $newGroup.before($columnsWrapper);
            $columnsWrapper.append($newGroup).append($oldGroup);
            $newGroup.css({ flex: '1', minWidth: 0 });
            $oldGroup.css({ flex: '1', minWidth: 0 });
            $oldGroup.find('[data-key="field_654591a83b3f5"]').css({ width: '100%', minHeight: 'auto' });
            $('<style>[data-name="sh_handicappers"]{width:100%!important;min-height:auto!important;}[data-key="field_shh_content_group_handicappers"] .acf-actions{display:none!important;}.acf-row.shh-newly-added,.acf-row.shh-newly-added td,.acf-row.shh-newly-added .acf-fields{background-color:#d4edda!important;}</style>').appendTo('head');
        }

        // Make the dropdown container full width
        $('[data-name="shh_content_group"]').css({ width: '100%', minHeight: '97px' });
        $('[data-key="field_shh_content_group"] .acf-input').css('width', '100%');

        var $dropdown = $('[data-key="field_shh_content_group"] select');
        var repeaterKey = 'field_shh_content_group_handicappers';
        var oldRepeaterKey = 'field_654591a83b3f5';

        if (!$dropdown.length) {
            return;
        }

        // Reduce dropdown width and wrap elements inline
        $dropdown.css('width', '250px');

        var $wrapper = $('<div style="display:flex;align-items:center;gap:8px;flex-wrap:wrap;"></div>');
        $dropdown.wrap($wrapper);

        var $spinner = $('<span class="spinner shh-group-spinner" style="float:none;margin:0;visibility:hidden;"></span>');
        var $regenerateBtn = $('<button type="button" class="button">Regenerate data</button>');
        var $addToContentBtn = $('<button type="button" class="button button-primary">Add to SH Handicappers Content</button>');
        var $addedCheck = $('<span class="dashicons dashicons-yes-alt" style="color:#46b450;font-size:20px;line-height:30px;display:none;"></span>');

        $dropdown.after($addedCheck).after($addToContentBtn).after($regenerateBtn);
        $addedCheck.after($spinner);

        // Add Check all / Uncheck all button next to the Handicappers label
        var $checkAllBtn = $('<button type="button" class="button button-small" style="margin-left:8px;background:#46b450;color:#fff;border-color:#46b450;">Select all</button>');
        $('[data-key="field_shh_content_group_handicappers"] .acf-label label').append($checkAllBtn);

        $checkAllBtn.on('click', function () {
            var $repeaterField = $('[data-key="field_shh_content_group_handicappers"]');
            var $checkboxes = $repeaterField.find('[data-key="field_shh_cg_handicapper_select"] input[type="checkbox"]');
            var allChecked = $checkboxes.length > 0 && $checkboxes.filter(':checked').length === $checkboxes.length;

            $checkboxes.prop('checked', !allChecked);
            $(this).text(allChecked ? 'Select all' : 'Unselect all');
        });

        function loadHandicappers(groupSlug) {
            var repeater = acf.getField(repeaterKey);

            if (!repeater) {
                return;
            }

            repeater.$el.find('.acf-row:not(.acf-clone)').each(function () {
                repeater.remove($(this));
            });

            if (!groupSlug) {
                return;
            }

            $spinner.css('visibility', 'visible').addClass('is-active');

            $.post(shh_cbg.ajax_url, {
                action: 'shh_get_handicappers_by_group',
                nonce: shh_cbg.nonce,
                group_slug: groupSlug,
            }, function (response) {
                if (response.success && response.data.length) {
                    response.data.forEach(function (item) {
                        repeater.$el.find('.acf-actions .acf-button').trigger('click');

                        var $lastRow = repeater.$el.find('.acf-row:not(.acf-clone)').last();
                        $lastRow.find('[data-key="field_shh_cg_handicapper_id"] input').val(item.id);
                        $lastRow.find('[data-key="field_shh_cg_handicapper_name"] input').val(item.name);
                    });
                }

                $spinner.css('visibility', 'hidden').removeClass('is-active');
            }).fail(function () {
                $spinner.css('visibility', 'hidden').removeClass('is-active');
            });
        }

        // Deduplicate and sort the old repeater rows
        function cleanAndSortOldRepeater() {
            var oldRepeater = acf.getField(oldRepeaterKey);
            if (!oldRepeater) {
                return;
            }

            // Remove duplicate rows (keep first occurrence)
            var seenIds = [];
            oldRepeater.$el.find('.acf-row:not(.acf-clone)').each(function () {
                var val = $(this).find('[data-key="field_654591c93b3f6"] select').val();
                if (!val || seenIds.indexOf(val) !== -1) {
                    oldRepeater.remove($(this));
                } else {
                    seenIds.push(val);
                }
            });

            // Sort remaining rows alphabetically
            var $rows = oldRepeater.$el.find('.acf-row:not(.acf-clone)');
            if ($rows.length > 1) {
                var $tbody = $rows.first().parent();

                $rows.sort(function (a, b) {
                    var nameA = $(a).find('[data-key="field_654591c93b3f6"] select option:selected').text().toLowerCase();
                    var nameB = $(b).find('[data-key="field_654591c93b3f6"] select option:selected').text().toLowerCase();
                    return nameA.localeCompare(nameB);
                });

                $rows.detach();
                $tbody.prepend($rows);
            }
        }

        // Clean and sort on page load
        cleanAndSortOldRepeater();

        $dropdown.on('change', function () {
            $addedCheck.hide();
            loadHandicappers($(this).val());
        });

        $regenerateBtn.on('click', function () {
            $addedCheck.hide();
            var groupSlug = $dropdown.val();

            if (!groupSlug) {
                alert('Please select a group first.');
                return;
            }

            loadHandicappers(groupSlug);
        });

        $addToContentBtn.on('click', function () {
            var newRepeater = acf.getField(repeaterKey);
            var oldRepeater = acf.getField(oldRepeaterKey);

            if (!newRepeater || !oldRepeater) {
                return;
            }

            // Get IDs from checked rows in our new table
            var newIds = [];
            newRepeater.$el.find('.acf-row:not(.acf-clone)').each(function () {
                var isChecked = $(this).find('[data-key="field_shh_cg_handicapper_select"] input[type="checkbox"]').is(':checked');
                var id = $(this).find('[data-key="field_shh_cg_handicapper_id"] input').val();
                if (isChecked && id) {
                    newIds.push(id);
                }
            });

            if (!newIds.length) {
                alert('Please select at least one handicapper.');
                return;
            }

            // Get IDs already in the old table
            var existingIds = [];
            oldRepeater.$el.find('.acf-row:not(.acf-clone)').each(function () {
                var val = $(this).find('[data-key="field_654591c93b3f6"] select').val();
                if (val) {
                    existingIds.push(val);
                }
            });

            // Filter out duplicates
            var toAdd = newIds.filter(function (id) {
                return existingIds.indexOf(id) === -1;
            });

            if (!toAdd.length) {
                alert('All handicappers already exist in SH Handicappers Content.');
                return;
            }

            // Add new rows to the old repeater
            var addedIds = [];
            toAdd.forEach(function (id) {
                oldRepeater.$el.find('.acf-actions .acf-button').trigger('click');

                var $lastRow = oldRepeater.$el.find('.acf-row:not(.acf-clone)').last();
                $lastRow.find('[data-key="field_654591c93b3f6"] select').val(id).trigger('change');
                addedIds.push(id);
            });

            cleanAndSortOldRepeater();

            // Highlight newly added rows
            oldRepeater.$el.find('.acf-row:not(.acf-clone)').each(function () {
                var val = $(this).find('[data-key="field_654591c93b3f6"] select').val();
                if (addedIds.indexOf(val) !== -1) {
                    $(this).addClass('shh-newly-added');
                }
            });

            $addedCheck.show();
        });
    });
})(jQuery);
