/**
 * Searchable Select — RTL-compatible dropdown with search & AJAX support
 *
 * Usage:
 *   Static:  <select data-searchable="true">
 *   AJAX:    <select data-searchable="true" data-search-url="/api/sa/players/search" data-search-min="2">
 *   Cascade: <select data-searchable="true" data-cascade-from="discipline_id" data-cascade-url="/api/sa/groups/search?discipline_id={value}">
 */
var SearchableSelect = (function() {
    'use strict';

    var instances = [];

    function init() {
        var selects = document.querySelectorAll('select[data-searchable]');
        selects.forEach(function(sel) {
            if (sel._ssInitialized) return;
            sel._ssInitialized = true;
            instances.push(new Instance(sel));
        });
    }

    function Instance(originalSelect) {
        this.select = originalSelect;
        this.options = [];
        this.filteredOptions = [];
        this.isOpen = false;
        this.highlightIndex = -1;
        this.ajaxUrl = originalSelect.getAttribute('data-search-url') || '';
        this.ajaxMin = parseInt(originalSelect.getAttribute('data-search-min') || '2', 10);
        this.cascadeFrom = originalSelect.getAttribute('data-cascade-from') || '';
        this.cascadeUrl = originalSelect.getAttribute('data-cascade-url') || '';
        this.placeholder = originalSelect.getAttribute('data-placeholder') || originalSelect.querySelector('option[value=""]')?.textContent || '-- اختر --';
        this.debounceTimer = null;
        this.abortController = null;

        this.build();
        this.cacheOptions();
        this.bindEvents();
        this.bindCascade();
    }

    Instance.prototype.build = function() {
        var wrapper = document.createElement('div');
        wrapper.className = 'ss-wrapper';
        wrapper.style.cssText = 'position:relative;width:100%;';

        var trigger = document.createElement('div');
        trigger.className = 'ss-trigger form-select';
        trigger.setAttribute('tabindex', '0');
        trigger.style.cssText = 'cursor:pointer;display:flex;align-items:center;justify-content:space-between;min-height:38px;';
        trigger.innerHTML = '<span class="ss-label" style="flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">' + escHtml(this.placeholder) + '</span><svg style="width:14px;height:14px;flex-shrink:0;opacity:0.5;margin-right:6px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="6 9 12 15 18 9"></polyline></svg>';

        var dropdown = document.createElement('div');
        dropdown.className = 'ss-dropdown';
        dropdown.style.cssText = 'display:none;position:absolute;top:100%;right:0;left:0;z-index:9999;background:#fff;border:1px solid #D1D5DB;border-radius:6px;box-shadow:0 4px 12px rgba(0,0,0,0.1);margin-top:4px;max-height:260px;overflow:hidden;';

        var searchWrap = document.createElement('div');
        searchWrap.style.cssText = 'padding:8px;border-bottom:1px solid #F3F4F6;';
        var searchInput = document.createElement('input');
        searchInput.type = 'text';
        searchInput.className = 'ss-search';
        searchInput.placeholder = 'ابحث...';
        searchInput.style.cssText = 'width:100%;padding:6px 10px;border:1px solid #E5E7EB;border-radius:4px;font-size:13px;outline:none;';
        searchInput.setAttribute('autocomplete', 'off');
        searchWrap.appendChild(searchInput);

        var list = document.createElement('div');
        list.className = 'ss-list';
        list.style.cssText = 'max-height:200px;overflow-y:auto;padding:4px 0;';

        dropdown.appendChild(searchWrap);
        dropdown.appendChild(list);
        wrapper.appendChild(trigger);
        wrapper.appendChild(dropdown);

        this.select.style.display = 'none';
        this.select.parentNode.insertBefore(wrapper, this.select.nextSibling);

        this.wrapper = wrapper;
        this.trigger = trigger;
        this.dropdown = dropdown;
        this.searchInput = searchInput;
        this.list = list;
        this.label = trigger.querySelector('.ss-label');
    };

    Instance.prototype.cacheOptions = function() {
        var self = this;
        self.options = [];
        var opts = self.select.querySelectorAll('option');
        opts.forEach(function(opt) {
            if (opt.value === '') return;
            self.options.push({
                value: opt.value,
                text: opt.textContent.trim(),
                group: opt.parentElement.tagName === 'OPTGROUP' ? opt.parentElement.label : '',
                el: opt
            });
        });
        self.filteredOptions = self.options.slice();
        self.renderList();
        self.syncLabel();
    };

    Instance.prototype.renderList = function() {
        var self = this;
        var html = '';
        var lastGroup = null;

        if (self.filteredOptions.length === 0) {
            html = '<div style="padding:12px;text-align:center;color:#9CA3AF;font-size:13px;">لا توجد نتائج</div>';
        } else {
            self.filteredOptions.forEach(function(opt, idx) {
                if (opt.group && opt.group !== lastGroup) {
                    html += '<div style="padding:4px 12px;font-size:11px;font-weight:700;color:#6B7280;background:#F9FAFB;">' + escHtml(opt.group) + '</div>';
                    lastGroup = opt.group;
                }
                var isSelected = self.select.value === opt.value;
                var isHL = idx === self.highlightIndex;
                html += '<div class="ss-option" data-idx="' + idx + '" data-value="' + escHtml(opt.value) + '" style="padding:7px 12px;cursor:pointer;font-size:13px;' + (isSelected ? 'background:#EFF6FF;font-weight:600;' : '') + (isHL ? 'background:#F3F4F6;' : '') + '">' + escHtml(opt.text) + '</div>';
            });
        }

        self.list.innerHTML = html;
    };

    Instance.prototype.syncLabel = function() {
        var val = this.select.value;
        if (!val) {
            this.label.textContent = this.placeholder;
            this.label.style.color = '#9CA3AF';
        } else {
            var found = this.options.find(function(o) { return o.value === val; });
            this.label.textContent = found ? found.text : val;
            this.label.style.color = '';
        }
    };

    Instance.prototype.open = function() {
        this.isOpen = true;
        this.dropdown.style.display = '';
        this.searchInput.value = '';
        this.highlightIndex = -1;
        if (!this.ajaxUrl) {
            this.filteredOptions = this.options.slice();
            this.renderList();
        }
        var self = this;
        setTimeout(function() { self.searchInput.focus(); }, 50);
    };

    Instance.prototype.close = function() {
        this.isOpen = false;
        this.dropdown.style.display = 'none';
    };

    Instance.prototype.selectValue = function(value) {
        // For AJAX results, the option may not exist in the original <select>
        if (value && !Array.from(this.select.options).some(function(o) { return o.value === value; })) {
            var found = this.filteredOptions.find(function(o) { return o.value === value; });
            if (found) {
                var newOpt = document.createElement('option');
                newOpt.value = found.value;
                newOpt.textContent = found.text;
                this.select.appendChild(newOpt);
                this.options.push({value: found.value, text: found.text, group: found.group || '', el: newOpt});
            }
        }
        this.select.value = value;
        this.syncLabel();
        this.close();
        this.select.dispatchEvent(new Event('change', { bubbles: true }));
    };

    Instance.prototype.filter = function(query) {
        var self = this;
        query = query.trim().toLowerCase();

        if (self.ajaxUrl) {
            if (query.length < self.ajaxMin) {
                self.filteredOptions = [];
                self.renderList();
                return;
            }
            clearTimeout(self.debounceTimer);
            self.debounceTimer = setTimeout(function() { self.fetchRemote(query); }, 250);
            return;
        }

        if (query === '') {
            self.filteredOptions = self.options.slice();
        } else {
            self.filteredOptions = self.options.filter(function(o) {
                return o.text.toLowerCase().indexOf(query) !== -1 || o.value.indexOf(query) !== -1;
            });
        }
        self.highlightIndex = -1;
        self.renderList();
    };

    Instance.prototype.fetchRemote = function(query) {
        var self = this;
        if (self.abortController) self.abortController.abort();
        self.abortController = new AbortController();

        var url = self.ajaxUrl + (self.ajaxUrl.indexOf('?') > -1 ? '&' : '?') + 'q=' + encodeURIComponent(query);

        var cascadeParent = self.cascadeFrom ? document.querySelector('[name="' + self.cascadeFrom + '"]') : null;
        if (cascadeParent && cascadeParent.value) {
            url += '&' + self.cascadeFrom + '=' + encodeURIComponent(cascadeParent.value);
        }

        self.list.innerHTML = '<div style="padding:12px;text-align:center;color:#9CA3AF;font-size:12px;">جاري البحث...</div>';

        fetch(url, {
            signal: self.abortController.signal,
            headers: { 'X-Requested-With': 'XMLHttpRequest' }
        })
        .then(function(r) { return r.json(); })
        .then(function(data) {
            var results = data.results || data.options || [];
            self.filteredOptions = results.map(function(r) {
                return {
                    value: String(r.id || r.value || ''),
                    text: r.label || r.full_name_ar || r.name_ar || r.name || r.text || '',
                    group: r.group || ''
                };
            });
            self.highlightIndex = -1;
            self.renderList();
        })
        .catch(function(e) {
            if (e.name !== 'AbortError') {
                self.list.innerHTML = '<div style="padding:12px;text-align:center;color:#DC2626;font-size:12px;">خطأ في البحث</div>';
            }
        });
    };

    Instance.prototype.bindEvents = function() {
        var self = this;

        self.trigger.addEventListener('click', function(e) {
            e.stopPropagation();
            if (self.isOpen) self.close(); else self.open();
        });

        self.trigger.addEventListener('keydown', function(e) {
            if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); self.open(); }
        });

        self.searchInput.addEventListener('input', function() {
            self.filter(this.value);
        });

        self.searchInput.addEventListener('keydown', function(e) {
            if (e.key === 'ArrowDown') {
                e.preventDefault();
                self.highlightIndex = Math.min(self.highlightIndex + 1, self.filteredOptions.length - 1);
                self.renderList();
                self.scrollToHighlight();
            } else if (e.key === 'ArrowUp') {
                e.preventDefault();
                self.highlightIndex = Math.max(self.highlightIndex - 1, 0);
                self.renderList();
                self.scrollToHighlight();
            } else if (e.key === 'Enter') {
                e.preventDefault();
                if (self.highlightIndex >= 0 && self.filteredOptions[self.highlightIndex]) {
                    self.selectValue(self.filteredOptions[self.highlightIndex].value);
                }
            } else if (e.key === 'Escape') {
                self.close();
                self.trigger.focus();
            }
        });

        self.list.addEventListener('click', function(e) {
            var opt = e.target.closest('.ss-option');
            if (opt) {
                self.selectValue(opt.getAttribute('data-value'));
            }
        });

        self.list.addEventListener('mouseover', function(e) {
            var opt = e.target.closest('.ss-option');
            if (opt) {
                var idx = parseInt(opt.getAttribute('data-idx'), 10);
                if (idx !== self.highlightIndex) {
                    var prev = self.list.querySelector('.ss-option[data-idx="' + self.highlightIndex + '"]');
                    if (prev) prev.style.background = (self.select.value === prev.getAttribute('data-value')) ? '#EFF6FF' : '';
                    self.highlightIndex = idx;
                    opt.style.background = '#F3F4F6';
                }
            }
        });

        document.addEventListener('click', function(e) {
            if (!self.wrapper.contains(e.target)) {
                self.close();
            }
        });
    };

    Instance.prototype.scrollToHighlight = function() {
        var el = this.list.querySelector('.ss-option[data-idx="' + this.highlightIndex + '"]');
        if (el) el.scrollIntoView({ block: 'nearest' });
    };

    Instance.prototype.bindCascade = function() {
        var self = this;
        if (!self.cascadeFrom) return;

        var parent = document.querySelector('[name="' + self.cascadeFrom + '"]');
        if (!parent) return;

        parent.addEventListener('change', function() {
            var parentVal = parent.value;
            self.select.innerHTML = '<option value="">' + escHtml(self.placeholder) + '</option>';
            self.options = [];
            self.filteredOptions = [];
            self.renderList();
            self.syncLabel();

            if (!parentVal || !self.cascadeUrl) return;

            var url = self.cascadeUrl.replace('{value}', encodeURIComponent(parentVal));
            fetch(url, { headers: { 'X-Requested-With': 'XMLHttpRequest' } })
                .then(function(r) { return r.json(); })
                .then(function(data) {
                    var items = data.results || data.options || data.programs || data.groups || data.coaches || [];
                    items.forEach(function(item) {
                        var opt = document.createElement('option');
                        opt.value = item.id || item.value || '';
                        opt.textContent = item.name_ar || item.full_name_ar || item.name || item.label || '';
                        self.select.appendChild(opt);
                    });
                    self.cacheOptions();
                })
                .catch(function() {});
        });
    };

    Instance.prototype.refresh = function() {
        this.cacheOptions();
    };

    function escHtml(str) {
        var d = document.createElement('div');
        d.textContent = str || '';
        return d.innerHTML;
    }

    function refreshAll() {
        instances.forEach(function(inst) { inst.refresh(); });
    }

    function initNew(container) {
        var selects = (container || document).querySelectorAll('select[data-searchable]:not([data-ss-done])');
        selects.forEach(function(sel) {
            if (sel._ssInitialized) return;
            sel._ssInitialized = true;
            sel.setAttribute('data-ss-done', '1');
            instances.push(new Instance(sel));
        });
    }

    return {
        init: init,
        refresh: refreshAll,
        initNew: initNew
    };
})();

document.addEventListener('DOMContentLoaded', function() {
    SearchableSelect.init();
});
