/**
 * Custom Schema by SCHEMAFY - Bulk URL Selector
 * Version: 1.0.0
 * Manage bulk URL selection with counter
 */

(function() {
    'use strict';

    window.SCHEMAFY = window.SCHEMAFY || {};

    /**
     * Initialize bulk selector
     * @param {string} containerId - ID of the container
     * @param {object} options - Configuration
     */
    window.SCHEMAFY.initBulkSelector = function(containerId, options) {
        var settings = jQuery.extend({
            showCounter: true,
            counterPosition: 'top', // 'top' or 'bottom'
            selectAllButton: true,
            clearButton: true,
            onChange: null
        }, options);

        var $container = jQuery('#' + containerId);
        if (!$container.length) {
            console.warn('[SCHEMAFY Bulk] Container not found:', containerId);
            return;
        }

        var $checkboxes = $container.find('.schemafy-url-checkbox');
        var $counter = null;
        var $selectAllBtn = null;
        var $clearBtn = null;

        // Create counter element
        if (settings.showCounter) {
            $counter = jQuery('<div class="schemafy-selection-counter" style="display:none;"></div>');
            $counter.html(
                '<span class="schemafy-selection-count">0</span> URLs Selected ' +
                (settings.clearButton ? '<button class="schemafy-clear-selection">❌ Clear</button>' : '')
            );

            if (settings.counterPosition === 'top') {
                $container.before($counter);
            } else {
                $container.after($counter);
            }

            $clearBtn = $counter.find('.schemafy-clear-selection');
        }

        /**
         * Update counter display
         */
        function updateCounter() {
            var count = getSelectedCount();

            if ($counter) {
                $counter.find('.schemafy-selection-count').text(count);

                if (count > 0) {
                    $counter.show();
                } else {
                    $counter.hide();
                }
            }

            // Callback
            if (typeof settings.onChange === 'function') {
                settings.onChange(count, getSelectedURLs());
            }
        }

        /**
         * Get number of selected checkboxes
         */
        function getSelectedCount() {
            return $checkboxes.filter(':checked').length;
        }

        /**
         * Get array of selected URL data
         */
        function getSelectedURLs() {
            var selected = [];
            $checkboxes.filter(':checked').each(function() {
                var $item = jQuery(this).closest('.schemafy-url-item');
                selected.push({
                    checkbox: this,
                    url: $item.find('.schemafy-url-path').text().trim(),
                    type: $item.find('.schemafy-url-type-badge').text().trim(),
                    element: $item[0]
                });
            });
            return selected;
        }

        /**
         * Select all checkboxes
         */
        function selectAll() {
            $checkboxes.prop('checked', true);
            updateCounter();
        }

        /**
         * Clear all selections
         */
        function clearSelection() {
            $checkboxes.prop('checked', false);
            updateCounter();
        }

        /**
         * Toggle selection (select all if none selected, clear if some/all selected)
         */
        function toggleAll() {
            if (getSelectedCount() === 0) {
                selectAll();
            } else {
                clearSelection();
            }
        }

        // Event listeners
        $checkboxes.on('change', updateCounter);

        if ($clearBtn) {
            $clearBtn.on('click', function(e) {
                e.preventDefault();
                clearSelection();
            });
        }

        // Initial update
        updateCounter();


        // Public API
        return {
            getCount: getSelectedCount,
            getSelected: getSelectedURLs,
            selectAll: selectAll,
            clear: clearSelection,
            toggle: toggleAll,
            update: updateCounter
        };
    };

    /**
     * Add Select All / Clear buttons to bulk form
     */
    window.SCHEMAFY.addBulkActionButtons = function(formId, bulkSelectorAPI) {
        var $form = jQuery('#' + formId);
        var $actions = $form.find('.schemafy-form-actions');

        if (!$actions.length) return;

        // Check if buttons already exist
        if ($actions.find('.schemafy-select-all-btn').length) return;

        var $selectAllBtn = jQuery('<button type="button" class="schemafy-btn-secondary schemafy-select-all-btn">☑️ Select All</button>');
        var $deselectAllBtn = jQuery('<button type="button" class="schemafy-btn-secondary schemafy-deselect-all-btn" style="display:none;">☐ Deselect All</button>');

        $actions.append($selectAllBtn);
        $actions.append($deselectAllBtn);

        $selectAllBtn.on('click', function(e) {
            e.preventDefault();
            bulkSelectorAPI.selectAll();
            $selectAllBtn.hide();
            $deselectAllBtn.show();
        });

        $deselectAllBtn.on('click', function(e) {
            e.preventDefault();
            bulkSelectorAPI.clear();
            $deselectAllBtn.hide();
            $selectAllBtn.show();
        });
    };

})();
