document.addEventListener('DOMContentLoaded', function() {

    const ModalSystem = {
        overlay: null,
        content: null,
        container: null,
        closeBtn: null,
        modalStack: [],

        init() {
            this.overlay = document.getElementById('modal-overlay');
            if (!this.overlay) return;

            this.content = document.getElementById('modal-content');
            this.container = this.content ? this.content.parentElement : null;
            this.closeBtn = document.getElementById('modal-close');

            if (!this.content || !this.container) {
                return;
            }

            this.bindEvents();
            this.initFormHandling();
        },

        bindEvents() {
            if (this.closeBtn) {
                this.closeBtn.addEventListener('click', () => this.close());
            }

            this.overlay.addEventListener('click', (e) => {
                if (e.target === this.overlay) this.close();
            });

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

            document.addEventListener('click', (e) => {
                const modalTrigger = e.target.closest('[data-modal]');
                if (modalTrigger) {
                    e.preventDefault();
                    const modalName = modalTrigger.getAttribute('data-modal');

                    const params = {};
                    Array.from(modalTrigger.attributes).forEach(attr => {
                        if (attr.name.startsWith('data-') && attr.name !== 'data-modal') {
                            const key = attr.name.replace('data-', '').replace(/-([a-z])/g, (g) => g[1].toUpperCase());
                            params[key] = attr.value;
                        }
                    });

                    this.open(modalName, params);
                }
            });

            document.addEventListener('click', (e) => {
                if (e.target.closest('[data-modal-close]')) {
                    e.preventDefault();
                    this.close();
                }
            });
        },

        initFormHandling() {
            document.addEventListener('fluentform_submission_success', (e) => {
                const form = e.target.closest('.ff-el-form-wrapper form');
                if (form) {
                    setTimeout(() => {
                        const thankYouUrl = this.getLocalizedUrl('/thank-you');
                        window.location.href = thankYouUrl;
                    }, 300);
                }
            }, true);

            if (typeof jQuery !== 'undefined') {
                jQuery(document).ajaxSuccess((event, xhr, settings) => {
                    if (settings.url && settings.url.includes('admin-ajax.php') &&
                        settings.data && settings.data.includes('fluentform_submit')) {
                        try {
                            const response = JSON.parse(xhr.responseText);
                            if (response.success && response.data && response.data.insert_id) {
                                setTimeout(() => {
                                    const thankYouUrl = this.getLocalizedUrl('/thank-you');
                                    window.location.href = thankYouUrl;
                                }, 300);
                            }
                        } catch (e) {
                        }
                    }
                });
            }
        },

        getLocalizedUrl(path) {
            const htmlLang = document.documentElement.lang;
            const currentLang = window.pll_current_language || this.getCurrentLangFromUrl();

            if (currentLang) {
                return `/${currentLang}${path}`;
            }

            return path;
        },

        getCurrentLangFromUrl() {
            const currentPath = window.location.pathname;
            const languageCodes = ['gym'];
            const pathParts = currentPath.split('/').filter(part => part.length > 0);

            return pathParts.length > 0 && languageCodes.includes(pathParts[0]) ? pathParts[0] : null;
        },

        getCurrentBranch() {
            const isGymPage = window.location.pathname.includes('/gym/');
            return isGymPage ? 'gym' : 'main';
        },

        open(modalName, params = {}) {
            const template = document.getElementById(`modal-template-${modalName}`);
            if (!template) return;

            this.modalStack.push({
                name: modalName,
                params: params,
                content: template.innerHTML
            });

            this.content.innerHTML = template.innerHTML;

            if (this.modalStack.length === 1) {
                this.show();
            }

            this.injectParams(params);
        },

        replace(modalName, params = {}) {
            if (this.modalStack.length === 0) {
                this.open(modalName, params);
                return;
            }

            const template = document.getElementById(`modal-template-${modalName}`);
            if (!template) return;

            this.modalStack[this.modalStack.length - 1] = {
                name: modalName,
                params: params,
                content: template.innerHTML
            };

            this.content.innerHTML = template.innerHTML;
            this.injectParams(params);
        },

        injectParams(params) {
            if (params.cardTitle) {
                const titleElements = this.content.querySelectorAll('[data-inject="card-title"]');
                titleElements.forEach(el => {
                    el.textContent = params.cardTitle;
                });
            }

            const attrElements = this.content.querySelectorAll('[data-inject="card-attr"]');
            attrElements.forEach(el => {
                const parentDiv = el.closest('div');

                if (params.cardAttr && params.cardAttr.trim() !== '') {
                    el.textContent = params.cardAttr;
                    if (parentDiv) {
                        parentDiv.style.display = 'flex';
                    }
                } else {
                    if (parentDiv) {
                        parentDiv.style.display = 'none';
                    }
                }
            });

            if (params.cardTime) {
                this.fillTimeInfo(JSON.parse(params.cardTime));
            }

            if (params.cardPrices) {
                this.fillPrices(JSON.parse(params.cardPrices), params.cardTitle, params.cardId);
            }
        },

        fillTimeInfo(timeSlots) {
            if (!timeSlots.length) return;

            const firstSlot = timeSlots[0];

            if (firstSlot.normal_days) {
                const normalDaysEl = this.content.querySelector('[data-inject="normal-days"]');
                if (normalDaysEl) normalDaysEl.textContent = firstSlot.normal_days;
            }

            if (firstSlot.vacation_days) {
                const vacationDaysEl = this.content.querySelector('[data-inject="vacation-days"]');
                if (vacationDaysEl) vacationDaysEl.textContent = firstSlot.vacation_days;
            }
        },

        fillPrices(prices, cardTitle, cardId) {
            const priceOptions = this.content.querySelectorAll('.price-option');
            let firstAvailableOption = null;
            let firstAvailablePeriod = null;
            let firstAvailablePrice = null;

            priceOptions.forEach(option => {
                const period = option.dataset.period;
                const price = prices[period];

                if (!price || !price.full || !price.day) {
                    option.classList.add('hidden');
                    return;
                }

                option.classList.remove('hidden');

                const fullElements = option.querySelectorAll(`[data-inject="price-${period.replace('_', '-')}-full"]`);
                const dayElements = option.querySelectorAll(`[data-inject="price-${period.replace('_', '-')}-day"]`);

                fullElements.forEach(el => el.textContent = price.full);
                dayElements.forEach(el => el.textContent = price.day);

                if (!firstAvailableOption) {
                    firstAvailableOption = option;
                    firstAvailablePeriod = period;
                    firstAvailablePrice = price;
                }

                option.addEventListener('click', () => {
                    this.selectPrice(option, period, price, cardTitle, cardId);
                });
            });

            if (firstAvailableOption) {
                this.selectPrice(firstAvailableOption, firstAvailablePeriod, firstAvailablePrice, cardTitle, cardId);
            } else {
                const priceContainer = this.content.querySelector('#price-options');
                if (priceContainer) {
                    priceContainer.innerHTML = '<p class="text-center text-gray-500">Цены временно недоступны</p>';
                }
            }
        },

        selectPrice(selectedOption, period, price, cardTitle, cardId) {
            this.content.querySelectorAll('.price-option').forEach(option => {
                option.classList.remove('bg-[linear-gradient(90deg,_#2b2c35_39.42%,_#6e7996_92.9%)]', '[&_div]:text-[#f8f8f8]', '[&_p]:text-[#bcbcc0]');
                option.classList.add('bg-[linear-gradient(180deg,_#f2f2f2_69.59%,_#ededed_100%)]', '[&_div]:text-[#222]', '[&_p]:text-[#6c6b6b]');
            });

            selectedOption.classList.remove('bg-[linear-gradient(180deg,_#f2f2f2_69.59%,_#ededed_100%)]', '[&_div]:text-[#222]', '[&_p]:text-[#6c6b6b]');
            selectedOption.classList.add('bg-[linear-gradient(90deg,_#2b2c35_39.42%,_#6e7996_92.9%)]', '[&_div]:text-[#f8f8f8]', '[&_p]:text-[#bcbcc0]');

            const periodNames = {
                '1_month': '1 месяц',
                '3_month': '3 месяца',
                '6_month': '6 месяцев',
                '12_month': '12 месяцев'
            };

            const selectedPeriodEl = this.content.querySelector('#selected-period');
            const selectedFullPriceEl = this.content.querySelector('#selected-full-price');
            const selectedDayPriceEl = this.content.querySelector('#selected-day-price');

            if (selectedPeriodEl) selectedPeriodEl.textContent = periodNames[period];
            if (selectedFullPriceEl) selectedFullPriceEl.textContent = price.full;
            if (selectedDayPriceEl) selectedDayPriceEl.textContent = price.day;

            setTimeout(() => {
                const hiddenInput = this.content.querySelector('input[name="hidden"]');
                if (hiddenInput) {
                    const formWrapper = this.content.querySelector('.form-block-wrapper');
                    const baseValue = formWrapper ? formWrapper.dataset.hiddenValue : '';

                    const normalDays = this.content.querySelector('[data-inject="normal-days"]')?.textContent || '';
                    const vacationDays = this.content.querySelector('[data-inject="vacation-days"]')?.textContent || '';
                    const daysInfo = normalDays || vacationDays ? ` | Дни: обычные ${normalDays}, выходные ${vacationDays}` : '';

                    const tariffInfo = `Карта: ${cardTitle} | Тариф: ${periodNames[period]} | Цена: ${price.full} ₽ (${price.day} ₽/день)${daysInfo} | ID карты: ${cardId}`;
                    hiddenInput.value = `${baseValue} | ${tariffInfo}`;
                }
            }, 100);
        },

        camelToKebab(str) {
            return str.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase();
        },

        show() {
            if (!this.overlay || !this.container) return;

            this.overlay.classList.remove('opacity-0', 'invisible');
            this.overlay.classList.add('opacity-100', 'visible');

            setTimeout(() => {
                if (this.closeBtn) this.closeBtn.focus();
            }, 350);
        },

        close() {
            if (this.modalStack.length === 0) return;

            const currentModal = this.modalStack[this.modalStack.length - 1];

            if (currentModal.name === 'welcome-branch') {
                const currentBranch = this.getCurrentBranch();
                localStorage.setItem('branch_choice_made', currentBranch);
            }

            this.modalStack.pop();

            if (this.modalStack.length > 0) {
                const prevModal = this.modalStack[this.modalStack.length - 1];
                this.content.innerHTML = prevModal.content;
                this.injectParams(prevModal.params);
            } else {
                this.hide();
            }
        },

        hide() {
            if (!this.container || !this.overlay) return;

            this.overlay.classList.remove('opacity-100', 'visible');
            this.overlay.classList.add('opacity-0', 'invisible');

            this.modalStack = [];
        },

        isOpen() {
            return this.modalStack.length > 0;
        }
    };

    ModalSystem.init();

    function checkWelcomeModal() {
        const isHomePage = window.location.pathname === '/' || window.location.pathname === '';
        const isGymPage = window.location.pathname.includes('/gym/');
        const hasChoiceMade = localStorage.getItem('branch_choice_made');

        if ((isHomePage || isGymPage) && !hasChoiceMade) {
            setTimeout(function() {
                ModalSystem.open('welcome-branch');
            }, 1000);
        }
    }

    document.addEventListener('click', function(e) {
        if (e.target.closest('.branch-card')) {
            e.preventDefault();

            const branchCard = e.target.closest('.branch-card');
            const branch = branchCard.dataset.branch;

            if (!branch) return;

            localStorage.setItem('branch_choice_made', branch);

            branchCard.classList.add('selecting');
            const button = branchCard.querySelector('button');
            if (button) {
                button.querySelector('span').textContent = 'Переходим...';
            }

            setTimeout(function() {
                const isHomePage = window.location.pathname === '/' || window.location.pathname === '';
                const isGymPage = window.location.pathname.includes('/gym/');

                if (branch === 'gym') {
                    if (isGymPage) {
                        ModalSystem.close();
                    } else {
                        window.location.href = '/gym/';
                    }
                } else {
                    if (isHomePage) {
                        ModalSystem.close();
                    } else {
                        window.location.href = '/';
                    }
                }
            }, 500);
        }
    });

    document.addEventListener('click', function(e) {
        const branchCard = e.target.closest('.branch-card');
        if (branchCard && !e.target.closest('.select-branch-btn')) {
            document.querySelectorAll('.branch-card').forEach(function(card) {
                card.classList.remove('selected');
            });
            branchCard.classList.add('selected');
        }
    });

    checkWelcomeModal();

    window.resetBranchChoice = function() {
        localStorage.removeItem('branch_choice_made');
    };

});