/**
 * Merge Tags Dropdown Component
 * 
 * Alpine.js component for managing merge tag insertion in email templates.
 * Provides a dropdown interface similar to Elementor's dynamic content picker.
 * 
 * @since 1.1.0
 */

// Export function to register the merge tags dropdown component
export function registerMergeTagsDropdown(Alpine) {
    Alpine.data('mergeTagsDropdown', (initialMergeTags = []) => ({
        isOpen: false,
        mergeTags: initialMergeTags,
        searchQuery: '',
        targetInput: null,

        init() {
            // Close dropdown when clicking outside
            document.addEventListener('click', (e) => {
                if (!this.$el.contains(e.target)) {
                    this.isOpen = false;
                }
            });

            // Handle escape key
            document.addEventListener('keydown', (e) => {
                if (e.key === 'Escape' && this.isOpen) {
                    this.isOpen = false;
                }
            });
        },

        /**
         * Toggle dropdown visibility
         * @param {HTMLElement} targetInput - The input field to insert merge tags into
         */
        toggleDropdown(targetInput = null) {
            this.isOpen = !this.isOpen;
            this.targetInput = targetInput;
            this.searchQuery = '';

            if (this.isOpen && this.$refs.searchInput) {
                this.$nextTick(() => {
                    this.$refs.searchInput.focus();
                });
            }
        },

        /**
         * Filter merge tags based on search query
         */
        get filteredMergeTags() {
            if (!Array.isArray(this.mergeTags)) {
                return [];
            }
            
            if (!this.searchQuery) {
                return this.mergeTags;
            }

            const query = this.searchQuery.toLowerCase();
            return this.mergeTags.filter(tag => 
                tag.label && tag.label.toLowerCase().includes(query) ||
                tag.tag && tag.tag.toLowerCase().includes(query) ||
                tag.description && tag.description.toLowerCase().includes(query)
            );
        },

        /**
         * Insert merge tag into target input at cursor position
         * @param {Object} mergeTag - The merge tag object to insert
         */
        insertMergeTag(mergeTag) {
            if (!this.targetInput) return;

            const tag = `{${mergeTag.tag}}`;
            const startPos = this.targetInput.selectionStart;
            const endPos = this.targetInput.selectionEnd;
            const textBefore = this.targetInput.value.substring(0, startPos);
            const textAfter = this.targetInput.value.substring(endPos);

            // Insert the merge tag
            this.targetInput.value = textBefore + tag + textAfter;

            // Set cursor position after the inserted tag
            const newCursorPos = startPos + tag.length;
            this.targetInput.setSelectionRange(newCursorPos, newCursorPos);

            // Trigger input event for any listeners (like Alpine.js x-model)
            this.targetInput.dispatchEvent(new Event('input', { bubbles: true }));

            // Focus back to the input
            this.targetInput.focus();

            // Close dropdown
            this.isOpen = false;
        },

        /**
         * Update merge tags list (useful when switching between different emails)
         * @param {Array} newMergeTags - New array of merge tag definitions
         */
        updateMergeTags(newMergeTags) {
            this.mergeTags = newMergeTags || [];
        },

        /**
         * Get dropdown position classes
         */
        get dropdownClasses() {
            return this.isOpen ? 'opacity-100 scale-100' : 'opacity-0 scale-95 pointer-events-none';
        }
    }));
}
