class Dropdown {

    constructor(container, options = {}) {
        this.container = container;
        this.options = {
            items: [],
            defaultText: 'Select...',
            onSelect: () => {},
            onDefaultAction: null,
            splitButton: false,
            required: false,
            label: '',
            name: '',
            id: options.id || this.generateId(),
            ...options
        };
        this.isOpen = false;
        this.selectedIndex = -1;
        this.isValid = true;
        this.init();
    }

    generateId() {
        return 'dropdown-' + Math.random().toString(36).substring(2, 11);
    }

    init() {
        this.container.className = 'dropdown-container';

        if (this.options.splitButton) {
            this.createSplitButton();
        } else {
            this.createStandardDropdown();
        }

        this.setupEventListeners();

        if (this.options.items.length > 0 && !this.options.required) {
            this.selectItem(0, false);
        }
    }

    createSplitButton() {
        this.container.innerHTML = `
            <div class="dropdown-trigger split-button" type="button">
                <button class="dropdown-main-button" type="button">
                    <span class="dropdown-text">${this.options.defaultText}</span>
                </button>
                <button class="dropdown-arrow-button" type="button">
                    <span class="dropdown-arrow">▼</span>
                </button>
            </div>
            <div class="dropdown-menu" style="display: none;">
                ${this.options.items.map((item, index) =>
                    `<div class="dropdown-item" data-index="${index}">${item.text}</div>`
                ).join('')}
            </div>
        `;

        this.trigger = this.container.querySelector('.dropdown-trigger');
        this.mainButton = this.container.querySelector('.dropdown-main-button');
        this.arrowButton = this.container.querySelector('.dropdown-arrow-button');
        this.menu = this.container.querySelector('.dropdown-menu');
        this.text = this.container.querySelector('.dropdown-text');
        this.arrow = this.container.querySelector('.dropdown-arrow');
    }

    createStandardDropdown() {
        this.container.innerHTML = `
            <button class="dropdown-trigger" type="button">
                <span class="dropdown-text">${this.options.defaultText}</span>
                <span class="dropdown-arrow">▼</span>
            </button>
            <div class="dropdown-menu" style="display: none;">
                ${this.options.items.map((item, index) =>
                    `<div class="dropdown-item" data-index="${index}">${item.text}</div>`
                ).join('')}
            </div>
            <div class="dropdown-error" style="display: none;"></div>
        `;

        this.trigger = this.container.querySelector('.dropdown-trigger');
        this.menu = this.container.querySelector('.dropdown-menu');
        this.text = this.container.querySelector('.dropdown-text');
        this.arrow = this.container.querySelector('.dropdown-arrow');
        this.errorElement = this.container.querySelector('.dropdown-error');
    }

    setupEventListeners() {
        if (this.options.splitButton) {

            this.mainButton.addEventListener('click', (e) => {
                e.stopPropagation();
                if (this.options.onDefaultAction) {
                    this.options.onDefaultAction();
                }
            });

            this.arrowButton.addEventListener('click', (e) => {
                e.stopPropagation();
                this.toggle();
            });
        } else {

            this.trigger.addEventListener('click', (e) => {
                e.stopPropagation();
                this.toggle();
            });
        }

        this.menu.addEventListener('click', (e) => {
            const item = e.target.closest('.dropdown-item');
            if (item) {
                const index = parseInt(item.getAttribute('data-index'));
                this.selectItem(index);
                this.close();
            }
        });

        document.addEventListener('click', () => {
            this.close();
        });
    }

    toggle() {
        if (this.isOpen) {
            this.close();
        } else {
            this.open();
        }
    }

    open() {
        this.isOpen = true;
        this.menu.style.display = 'block';
        this.arrow.textContent = '▲';
        this.container.classList.add('dropdown-open');

        if (this.options.onOpen) {
            this.options.onOpen();
        }
    }

    close() {
        this.isOpen = false;
        this.menu.style.display = 'none';
        this.arrow.textContent = '▼';
        this.container.classList.remove('dropdown-open');

        if (this.options.onClose) {
            this.options.onClose();
        }
    }

    selectItem(index, triggerCallback = true) {
        if (index >= 0 && index < this.options.items.length) {
            this.selectedIndex = index;
            const item = this.options.items[index];
            this.text.textContent = item.text;

            this.trigger.classList.add('has-selection');

            this.showError(null);

            this.menu.querySelectorAll('.dropdown-item').forEach((el, i) => {
                el.classList.toggle('selected', i === index);
            });

            if (triggerCallback) {
                this.options.onSelect(item, index);
            }
        }
    }

    updateItems(items) {
        this.options.items = items;
        this.menu.innerHTML = items.map((item, index) =>
            `<div class="dropdown-item" data-index="${index}">${item.text}</div>`
        ).join('');

        this.clearSelection();
    }

    getSelectedItem() {
        return this.options.items[this.selectedIndex];
    }

    getSelectedIndex() {
        return this.selectedIndex;
    }

    clearSelection() {
        this.selectedIndex = -1;
        this.text.textContent = this.options.defaultText;
        this.trigger.classList.remove('has-selection');

        this.menu.querySelectorAll('.dropdown-item').forEach(el => {
            el.classList.remove('selected');
        });
    }

    getValue() {
        if (this.selectedIndex >= 0 && this.selectedIndex < this.options.items.length) {
            const item = this.options.items[this.selectedIndex];
            return item.value || item.text || '';
        }
        return '';
    }

    setValue(value) {
        const index = this.options.items.findIndex(item =>
            (item.value && item.value === value) || item.text === value
        );
        if (index >= 0) {
            this.selectItem(index, false);
        }
    }

    validate() {
        if (this.options.required && this.selectedIndex < 0) {
            this.isValid = false;
            this.showError('Please select an option');
            return false;
        }
        this.isValid = true;
        this.showError(null);
        return true;
    }

    showError(message) {
        if (!this.errorElement) return;

        if (message) {
            this.errorElement.textContent = message;
            this.errorElement.style.display = 'block';
            this.trigger.classList.add('error');
        } else {
            this.errorElement.style.display = 'none';
            this.trigger.classList.remove('error');
        }
    }

    getData() {
        const data = {};
        if (this.options.name) {
            data[this.options.name] = this.getValue();
        }
        return data;
    }

    setData(data) {
        if (this.options.name && data[this.options.name]) {
            this.setValue(data[this.options.name]);
        }
    }

    setUnlockedState(unlocked) {
        if (unlocked) {
            this.trigger.classList.add('unlocked');
        } else {
            this.trigger.classList.remove('unlocked');
        }
    }

    updateDefaultText(text) {
        this.options.defaultText = text;
        this.text.textContent = text;
    }

    destroy() {

        if (this.options.splitButton) {
            this.mainButton?.removeEventListener('click', this.handleMainButtonClick);
            this.arrowButton?.removeEventListener('click', this.handleArrowButtonClick);
        } else {
            this.trigger?.removeEventListener('click', this.handleTriggerClick);
        }

        this.menu?.removeEventListener('click', this.handleMenuClick);

        this.container.innerHTML = '';

        this.trigger = null;
        this.mainButton = null;
        this.arrowButton = null;
        this.menu = null;
        this.text = null;
        this.arrow = null;
    }
}

if (typeof module !== 'undefined' && module.exports) {
    module.exports = Dropdown;
}

if (typeof window !== 'undefined') {
    window.Dropdown = Dropdown;
}