(function($) {
    'use strict';

    const FO = window.KookoaWPF;

    // ========================
    // Custom Dropdown (replaces native <select> in modals)
    // ========================

    const KookoawpfCustomSelect = window.KookoawpfCustomSelect = {

        _lockIcon: '<span class="dashicons dashicons-lock" style="font-size:14px;width:14px;height:14px;line-height:14px;color:#F5BF42;vertical-align:middle;"></span>',
        _pinIcon: '<span class="dashicons dashicons-star-filled" style="font-size:14px;width:14px;height:14px;line-height:14px;color:#F5BF42;vertical-align:middle;"></span>',

        _renderLabel: function(text) {
            const hasPin = text.indexOf('\u2B50') !== -1;
            const hasLock = text.indexOf('\uD83D\uDD12') !== -1;
            const clean = text.replace(' \u2B50', '').replace(' \uD83D\uDD12', '');
            let html = $('<span>').text(clean).html();
            if (hasPin) html += ' ' + this._pinIcon;
            if (hasLock) html += ' ' + this._lockIcon;
            return html;
        },

        /**
         * Convert a native <select> into a custom dropdown.
         * The native select is hidden but kept in sync for form submission.
         */
        replace: function($select) {
            if ($select.data('kookoawpf-cs-init')) return;
            $select.data('kookoawpf-cs-init', true);

            const $wrapper = $('<div class="kookoawpf-custom-select"></div>');
            const selectedText = $select.find('option:selected').text() || $select.find('option').first().text();

            const $trigger = $(
                '<div class="kookoawpf-custom-select-trigger">' +
                '<span class="kookoawpf-cs-label">' + KookoawpfCustomSelect._renderLabel(selectedText) + '</span>' +
                '<span class="kookoawpf-custom-select-arrow dashicons dashicons-arrow-down-alt2"></span>' +
                '</div>'
            );

            const $optionsList = $('<div class="kookoawpf-custom-select-options"></div>');

            $select.find('option').each(function() {
                const $opt = $(this);
                let cls = 'kookoawpf-custom-select-option';
                if ($opt.is(':selected')) cls += ' kookoawpf-cs-selected';
                const $div = $('<div></div>')
                    .addClass(cls)
                    .attr('data-value', $opt.val())
                    .html(KookoawpfCustomSelect._renderLabel($opt.text()));
                // Font preview: if the option carries a data-css font family, apply it.
                const css = $opt.attr('data-css');
                if (css) { $div.addClass('kookoawpf-cs-font-preview'); $div[0].style.setProperty('font-family', css, 'important'); }
                $optionsList.append($div);
            });

            // Apply font preview to the trigger if selected option has data-css.
            const selCss = $select.find('option:selected').attr('data-css');
            if (selCss) { $trigger.find('.kookoawpf-cs-label')[0].style.setProperty('font-family', selCss, 'important'); }

            $wrapper.append($trigger).append($optionsList);
            $select.hide().after($wrapper);

            // Toggle dropdown
            $trigger.on('click', function(e) {
                e.stopPropagation();
                // Close all other open dropdowns
                $('.kookoawpf-custom-select.kookoawpf-cs-open').not($wrapper).removeClass('kookoawpf-cs-open');
                $wrapper.toggleClass('kookoawpf-cs-open');
            });

            // Select an option
            $optionsList.on('click', '.kookoawpf-custom-select-option', function(e) {
                e.stopPropagation();
                const val = $(this).data('value');
                const text = $(this).text();

                // Update native select
                $select.val(val).trigger('change');

                // Update UI
                const $label = $trigger.find('.kookoawpf-cs-label');
                $label.html(KookoawpfCustomSelect._renderLabel(text));
                // Font preview: update trigger font if the selected native option has data-css.
                const optCss = $select.find('option:selected').attr('data-css');
                if (optCss) { $label[0].style.setProperty('font-family', optCss, 'important'); } else { $label[0].style.removeProperty('font-family'); }

                $optionsList.find('.kookoawpf-cs-selected').removeClass('kookoawpf-cs-selected');
                $(this).addClass('kookoawpf-cs-selected');

                $wrapper.removeClass('kookoawpf-cs-open');
            });
        },

        /**
         * Refresh the custom dropdown options from the native <select>.
         * Call this after dynamically adding options to the select.
         */
        refresh: function($select) {
            const $wrapper = $select.next('.kookoawpf-custom-select');
            if (!$wrapper.length) return;

            const $optionsList = $wrapper.find('.kookoawpf-custom-select-options');
            $optionsList.empty();

            const selectedVal = $select.val();

            $select.find('option').each(function() {
                const $opt = $(this);
                let cls = 'kookoawpf-custom-select-option';
                if ($opt.val() === selectedVal) cls += ' kookoawpf-cs-selected';
                const $div = $('<div></div>')
                    .addClass(cls)
                    .attr('data-value', $opt.val())
                    .html(KookoawpfCustomSelect._renderLabel($opt.text()));
                const css = $opt.attr('data-css');
                if (css) { $div.addClass('kookoawpf-cs-font-preview'); $div[0].style.setProperty('font-family', css, 'important'); }
                $optionsList.append($div);
            });

            const selectedText = $select.find('option:selected').text() || '';
            const $label = $wrapper.find('.kookoawpf-cs-label');
            $label.html(KookoawpfCustomSelect._renderLabel(selectedText));
            const selCss = $select.find('option:selected').attr('data-css');
            if (selCss) { $label[0].style.setProperty('font-family', selCss, 'important'); } else { $label[0].style.removeProperty('font-family'); }
        },

        /**
         * Initialize: convert all selects in modals, and watch for new ones.
         */
        init: function() {
            const self = this;

            // Close dropdowns on outside click
            $(document).on('click', function() {
                $('.kookoawpf-custom-select.kookoawpf-cs-open').removeClass('kookoawpf-cs-open');
            });

            // Close on Escape
            $(document).on('keydown', function(e) {
                if (e.keyCode === 27) {
                    $('.kookoawpf-custom-select.kookoawpf-cs-open').removeClass('kookoawpf-cs-open');
                }
            });

            // Convert selects when modals open
            $(document).on('click', function() {
                setTimeout(function() {
                    self.convertVisible();
                }, 50);
            });

            // Also observe DOM for dynamically added selects
            const observer = new MutationObserver(function() {
                self.convertVisible();
            });
            observer.observe(document.body, { childList: true, subtree: true });
        },

        /**
         * Convert all visible selects in modals that haven't been converted yet.
         */
        convertVisible: function() {
            const self = this;
            // Only convert selects inside OUR modals, NOT the WP media modal
            $('.kookoawpf-modal:visible select').each(function() {
                if ($(this).closest('.media-modal').length) return;
                self.replace($(this));
            });
        }
    };

    // Patch FO.populateFolderSelect to refresh custom dropdown after populating
    const _origPopulate = FO.populateFolderSelect;
    FO.populateFolderSelect = function($select, currentVal, excludeFolder) {
        _origPopulate.call(this, $select, currentVal, excludeFolder);
        // After options are populated (async), refresh the custom dropdown
        this.getCachedFolderList(function() {
            setTimeout(function() {
                KookoawpfCustomSelect.refresh($select);
            }, 50);
        });
    };

    KookoawpfCustomSelect.init();

})(jQuery);
