/* GETCOURSE — USER CARD / JS v1.5 */
(function () {
    'use strict';

    const PAGE_RE = /^\/user\/control\/user\/update\/id\/\d+\/?$/;
    const STATUS_CLASSES = [
        'psych-deal-status-success',
        'psych-deal-status-warning',
        'psych-deal-status-danger',
        'psych-deal-status-info',
        'psych-deal-status-neutral'
    ];
    let globalSelectClosingEnabled = false;

    function isTargetPage() {
        return PAGE_RE.test(window.location.pathname) && document.querySelector('#userForm');
    }

    function markStatus(element) {
        if (!element) return;
        const text = element.textContent.replace(/\s+/g, ' ').trim().toLowerCase();
        element.classList.remove(...STATUS_CLASSES);
        let className = 'psych-deal-status-neutral';
        if (/оплачен|оплачено|платеж получен|завершен|завершён/.test(text)) {
            className = 'psych-deal-status-success';
        } else if (/отмен|отказ|аннулир|возврат/.test(text)) {
            className = 'psych-deal-status-danger';
        } else if (/ожида|не оплачен|неоплачен|частич|в обработке/.test(text)) {
            className = 'psych-deal-status-warning';
        } else if (/новый|в работе|активен|открыт/.test(text)) {
            className = 'psych-deal-status-info';
        }
        element.classList.add(className);
    }

    function enhanceDealStatuses(root = document) {
        root.querySelectorAll('#userFormDeals .deal-status, .gc-right-active-block .deal-status').forEach(markStatus);
        root.querySelectorAll('.gc-right-active-block .status-deal-status').forEach(function (status) {
            const statusText = status.querySelector('.row .text-right div');
            if (statusText) markStatus(statusText);
        });
    }

    function enhanceManagerRow(root = document) {
        const manager = root.querySelector('#w0');
        const row = manager?.closest('tr');
        if (row) row.classList.add('psych-user-manager-row');
    }

    function enhanceRightPanel(root = document) {
        root.querySelectorAll('.gc-right-active-block .btn').forEach(function (button) {
            button.classList.add('psych-user-btn');
        });
        root.querySelectorAll('.gc-right-active-block input, .gc-right-active-block textarea, .gc-right-active-block select').forEach(function (control) {
            control.classList.add('psych-right-control');
        });
    }

    function closeCustomSelect(wrapper) {
        if (!wrapper) return;
        wrapper.classList.remove('is-open');
        wrapper.querySelector('.psych-user-select__control')?.setAttribute('aria-expanded', 'false');
    }

    function closeOtherCustomSelects(current) {
        document.querySelectorAll('.psych-user-select.is-open').forEach(function (wrapper) {
            if (wrapper !== current) closeCustomSelect(wrapper);
        });
    }

    function initCustomSelects(root = document) {
        root.querySelectorAll('#userForm select:not(.psych-user-select__native):not(.kv-hide):not(.select2-offscreen)').forEach(function (select) {
            if (select.dataset.psychCustomSelect === 'ready') return;
            if (select.id === 'managerUserIdInput') return;
            if (select.closest('.select2-container')) return;

            const select2 = select.id
                ? document.querySelector(`#s2id_${CSS.escape(select.id)}`)
                : null;
            if (select2) return;

            select.dataset.psychCustomSelect = 'ready';
            select.classList.add('psych-user-select__native');

            const wrapper = document.createElement('div');
            wrapper.className = 'psych-user-select';

            const control = document.createElement('button');
            control.type = 'button';
            control.className = 'psych-user-select__control';
            control.setAttribute('aria-haspopup', 'listbox');
            control.setAttribute('aria-expanded', 'false');

            const value = document.createElement('span');
            value.className = 'psych-user-select__value';

            const arrow = document.createElement('span');
            arrow.className = 'psych-user-select__arrow';

            const menu = document.createElement('div');
            menu.className = 'psych-user-select__menu';
            menu.setAttribute('role', 'listbox');

            control.append(value, arrow);
            select.parentNode.insertBefore(wrapper, select);
            wrapper.append(select, control, menu);

            function getSelectedOption() {
                return select.options[select.selectedIndex] || select.options[0] || null;
            }

            function getEnabledOptions() {
                return Array.from(menu.querySelectorAll('.psych-user-select__option:not(:disabled)'));
            }

            function focusOption(direction) {
                const options = getEnabledOptions();
                if (!options.length) return;
                const active = document.activeElement;
                let index = options.indexOf(active);
                if (index === -1) {
                    index = options.findIndex(option => option.classList.contains('is-selected'));
                }
                if (index === -1) index = direction > 0 ? -1 : 0;
                index = (index + direction + options.length) % options.length;
                options[index].focus();
            }

            function render() {
                const selected = getSelectedOption();
                value.textContent = selected ? selected.textContent : '';
                menu.innerHTML = '';

                Array.from(select.options).forEach(function (option) {
                    const button = document.createElement('button');
                    button.type = 'button';
                    button.className = 'psych-user-select__option';
                    button.dataset.value = option.value;
                    button.textContent = option.textContent;
                    button.setAttribute('role', 'option');
                    button.setAttribute('aria-selected', option.selected ? 'true' : 'false');
                    if (option.selected) button.classList.add('is-selected');
                    if (option.disabled) button.disabled = true;

                    button.addEventListener('click', function () {
                        if (select.value !== option.value) {
                            select.value = option.value;
                            select.dispatchEvent(new Event('change', { bubbles: true }));
                            render();
                        }
                        closeCustomSelect(wrapper);
                        control.focus();
                    });

                    button.addEventListener('keydown', function (event) {
                        if (event.key === 'ArrowDown') {
                            event.preventDefault();
                            focusOption(1);
                        } else if (event.key === 'ArrowUp') {
                            event.preventDefault();
                            focusOption(-1);
                        } else if (event.key === 'Escape') {
                            event.preventDefault();
                            closeCustomSelect(wrapper);
                            control.focus();
                        }
                    });

                    menu.appendChild(button);
                });

                wrapper.classList.toggle('is-disabled', select.disabled);
                control.disabled = select.disabled;
            }

            function open() {
                if (select.disabled) return;
                closeOtherCustomSelects(wrapper);
                wrapper.classList.add('is-open');
                control.setAttribute('aria-expanded', 'true');
            }

            control.addEventListener('click', function () {
                if (wrapper.classList.contains('is-open')) {
                    closeCustomSelect(wrapper);
                } else {
                    open();
                }
            });

            control.addEventListener('keydown', function (event) {
                if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
                    event.preventDefault();
                    open();
                    requestAnimationFrame(function () {
                        focusOption(event.key === 'ArrowDown' ? 1 : -1);
                    });
                } else if (event.key === 'Escape') {
                    closeCustomSelect(wrapper);
                }
            });

            select.addEventListener('change', render);

            const observer = new MutationObserver(render);
            observer.observe(select, {
                childList: true,
                attributes: true,
                subtree: true,
                attributeFilter: ['disabled', 'selected']
            });

            render();
        });
    }

    function enableCustomSelectClosing() {
        if (globalSelectClosingEnabled) return;
        globalSelectClosingEnabled = true;

        document.addEventListener('click', function (event) {
            document.querySelectorAll('.psych-user-select.is-open').forEach(function (wrapper) {
                if (!wrapper.contains(event.target)) closeCustomSelect(wrapper);
            });
        });

        document.addEventListener('keydown', function (event) {
            if (event.key !== 'Escape') return;
            document.querySelectorAll('.psych-user-select.is-open').forEach(closeCustomSelect);
        });
    }

    function enhance(root = document) {
        document.body.classList.add('psych-user-card-enhanced');
        enhanceManagerRow(root);
        enhanceRightPanel(root);
        enhanceDealStatuses(root);
        initCustomSelects(root);
    }

    function observeDynamicContent() {
        let timer = null;
        const observer = new MutationObserver(function (mutations) {
            const hasAddedNodes = mutations.some(mutation => mutation.addedNodes.length);
            if (!hasAddedNodes) return;
            window.clearTimeout(timer);
            timer = window.setTimeout(function () {
                enhance(document);
            }, 40);
        });
        observer.observe(document.body, { childList: true, subtree: true });
    }

    function init() {
        if (!isTargetPage()) return;
        enhance();
        enableCustomSelectClosing();
        observeDynamicContent();
        [100, 300, 800, 1500].forEach(delay => window.setTimeout(enhance, delay));
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init, { once: true });
    } else {
        init();
    }
})();
