/**
 * Custom Multi-Select Component for WPUF
 * Replaces native select multiple with modern UI
 */

class WPUFCustomMultiSelect {
    constructor(selectElement) {
        this.originalSelect = selectElement;
        this.selectedValues = new Set();
        this.isOpen = false;

        this.init();
    }

    init() {
        // Get initial selected values
        this.getInitialValues();

        // Create custom HTML structure
        this.createCustomStructure();

        // Bind events
        this.bindEvents();

        // Hide original select
        this.originalSelect.style.display = 'none';
    }

    getInitialValues() {
        const options = this.originalSelect.querySelectorAll('option:checked');
        options.forEach(option => {
            if (option.value && option.value !== '-1') {
                this.selectedValues.add(option.value);
            }
        });
    }

    createCustomStructure() {
        // Create wrapper
        this.wrapper = document.createElement('div');
        this.wrapper.className = 'custom-multiselect';

        // Create input container
        this.inputContainer = document.createElement('div');
        this.inputContainer.className = 'multiselect-input';
        this.inputContainer.setAttribute('tabindex', '0');
        this.inputContainer.setAttribute('role', 'combobox');
        this.inputContainer.setAttribute('aria-expanded', 'false');
        this.inputContainer.setAttribute('aria-haspopup', 'listbox');

        // Create selected items container
        this.selectedItemsContainer = document.createElement('div');
        this.selectedItemsContainer.className = 'selected-items';

        // Create placeholder text
        this.placeholderText = document.createElement('span');
        this.placeholderText.className = 'multiselect-placeholder';
        this.placeholderText.textContent = this.originalSelect.getAttribute('data-placeholder') || 'Select options...';

        // Create dropdown arrow
        this.dropdownArrow = document.createElement('span');
        this.dropdownArrow.className = 'dropdown-arrow';
        this.dropdownArrow.innerHTML = '<svg width="14" height="8" viewBox="0 0 14 8" fill="none" xmlns="http://www.w3.org/2000/svg">\n' +
            '<path d="M13.25 0.750001L7 7L0.75 0.750001" stroke="#4B5563" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>\n' +
            '</svg>\n';

        // Create dropdown container
        this.dropdownContainer = document.createElement('div');
        this.dropdownContainer.className = 'multiselect-dropdown';
        this.dropdownContainer.setAttribute('role', 'listbox');

        // Build options
        this.buildOptions();

        // Assemble structure
        this.inputContainer.appendChild(this.selectedItemsContainer);
        this.inputContainer.appendChild(this.placeholderText);
        this.inputContainer.appendChild(this.dropdownArrow);

        this.wrapper.appendChild(this.inputContainer);
        this.wrapper.appendChild(this.dropdownContainer);

        // Insert after original select
        this.originalSelect.parentNode.insertBefore(this.wrapper, this.originalSelect.nextSibling);

        // Update display
        this.updateDisplay();
    }

    buildOptions() {
        const options = this.originalSelect.querySelectorAll('option');

        options.forEach(option => {
            if (option.value === '-1') return; // Skip placeholder option

            const optionElement = document.createElement('div');
            optionElement.className = 'multiselect-option';
            optionElement.setAttribute('role', 'option');
            optionElement.setAttribute('data-value', option.value);

            const checkbox = document.createElement('input');
            checkbox.type = 'checkbox';
            checkbox.id = `option-${option.value}-${Math.random().toString(36).substr(2, 9)}`;
            checkbox.checked = this.selectedValues.has(option.value);

            const label = document.createElement('label');
            label.htmlFor = checkbox.id;
            label.textContent = option.textContent;

            optionElement.appendChild(checkbox);
            optionElement.appendChild(label);

            this.dropdownContainer.appendChild(optionElement);
        });
    }

    bindEvents() {
        // Toggle dropdown
        this.inputContainer.addEventListener('click', (e) => {
            e.stopPropagation();
            this.toggleDropdown();
        });

        // Option selection
        this.dropdownContainer.addEventListener('change', (e) => {
            if (e.target.type === 'checkbox') {
                this.handleOptionChange(e.target);
            }
        });

        // Close dropdown when clicking outside
        document.addEventListener('click', (e) => {
            if (!this.wrapper.contains(e.target)) {
                this.closeDropdown();
            }
        });

        // Keyboard navigation
        this.inputContainer.addEventListener('keydown', (e) => {
            this.handleKeyboard(e);
        });
    }

    handleOptionChange(checkbox) {
        const value = checkbox.closest('.multiselect-option').getAttribute('data-value');

        if (checkbox.checked) {
            this.selectedValues.add(value);
        } else {
            this.selectedValues.delete(value);
        }

        this.updateDisplay();
        this.updateOriginalSelect();
    }

    updateDisplay() {
        // Clear selected items
        this.selectedItemsContainer.innerHTML = '';

        if (this.selectedValues.size === 0) {
            this.placeholderText.style.display = 'block';
        } else {
            this.placeholderText.style.display = 'none';

            // Create pills for selected items
            this.selectedValues.forEach(value => {
                const option = this.originalSelect.querySelector(`option[value="${value}"]`);
                if (option) {
                    const pill = this.createPill(value, option.textContent);
                    this.selectedItemsContainer.appendChild(pill);
                }
            });
        }
    }

    createPill(value, text) {
        const pill = document.createElement('div');
        pill.className = 'selected-item';
        pill.setAttribute('data-value', value);

        const textSpan = document.createElement('span');
        textSpan.textContent = text;

        const removeBtn = document.createElement('button');
        removeBtn.type = 'button';
        removeBtn.className = 'remove-item';
        removeBtn.innerHTML = '×';
        removeBtn.setAttribute('aria-label', `Remove ${text}`);

        pill.appendChild(textSpan);
        pill.appendChild(removeBtn);

        // Remove item when X is clicked
        removeBtn.addEventListener('click', (e) => {
            e.stopPropagation();
            this.selectedValues.delete(value);
            
            // Uncheck the corresponding checkbox in the dropdown
            const optionElement = this.dropdownContainer.querySelector(`.multiselect-option[data-value="${value}"]`);
            if (optionElement) {
                const checkbox = optionElement.querySelector('input[type="checkbox"]');
                if (checkbox) {
                    checkbox.checked = false;
                }
            }
            
            this.updateDisplay();
            this.updateOriginalSelect();
        });

        return pill;
    }

    updateOriginalSelect() {
        // Update original select to match custom selection
        const options = this.originalSelect.querySelectorAll('option');
        options.forEach(option => {
            option.selected = this.selectedValues.has(option.value);
        });

        // Trigger change event for form validation
        const changeEvent = new Event('change', { bubbles: true });
        this.originalSelect.dispatchEvent(changeEvent);
    }

    toggleDropdown() {
        if (this.isOpen) {
            this.closeDropdown();
        } else {
            this.openDropdown();
        }
    }

    openDropdown() {
        this.isOpen = true;
        this.dropdownContainer.style.display = 'block';
        this.inputContainer.setAttribute('aria-expanded', 'true');
        this.dropdownArrow.style.transform = 'rotate(180deg)';
    }

    closeDropdown() {
        this.isOpen = false;
        this.dropdownContainer.style.display = 'none';
        this.inputContainer.setAttribute('aria-expanded', 'false');
        this.dropdownArrow.style.transform = 'rotate(0deg)';
    }

    handleKeyboard(e) {
        switch (e.key) {
            case 'Enter':
            case ' ':
                e.preventDefault();
                this.toggleDropdown();
                break;
            case 'Escape':
                this.closeDropdown();
                break;
        }
    }
}

// Initialize custom multi-selects when DOM is ready
document.addEventListener('DOMContentLoaded', function() {
    // Target WPUF multi-select fields specifically
    const wpufMultiSelects = document.querySelectorAll('select.wpuf-multiselect-field[multiple]');

    wpufMultiSelects.forEach(select => {
        new WPUFCustomMultiSelect(select);
    });
});

// Also initialize on AJAX form loads (for dynamic forms)
jQuery(document).on('wpuf_form_loaded', function() {
    const wpufMultiSelects = document.querySelectorAll('select.wpuf-multiselect-field[multiple]');

    wpufMultiSelects.forEach(select => {
        // Check if already initialized
        if (!select.closest('.custom-multiselect')) {
            new WPUFCustomMultiSelect(select);
        }
    });
});
