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.overlay.querySelector('.bg-white');
            this.closeBtn = document.getElementById('modal-close');

            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 cardId = modalTrigger.getAttribute('data-card-id');
                    this.open(modalName, { cardId });
                }
            });

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

        initFormHandling() {
            console.log('Form handling initialized');

            document.addEventListener('fluentform_submission_success', (e) => {
                const form = e.target.closest('.ff-el-form-wrapper form');
                if (form) {
                    setTimeout(() => {
                        if (this.isOpen()) {
                            this.replace('form-success');
                        } else {
                            this.open('form-success');
                        }
                    }, 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);
                            console.log('Response:', response);
                            if (response.success && response.data && response.data.insert_id) {
                                setTimeout(() => {
                                    if (this.isOpen()) {
                                        this.replace('form-success');
                                    } else {
                                        this.open('form-success');
                                    }
                                }, 300);
                            }
                        } catch (e) {
                        }
                    }
                });
            } else {
            }
        },

        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.cardId) {
                setTimeout(() => {
                    const hiddenInput = this.content.querySelector('input[name="hidden"]');
                    if (hiddenInput && !hiddenInput.dataset.cardInjected) {
                        const currentValue = hiddenInput.value || '';
                        hiddenInput.value = currentValue + ` | Карта ID: ${params.cardId}`;
                        hiddenInput.dataset.cardInjected = 'true';
                    }
                }, 100);
            }
        },

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

            setTimeout(() => {
                this.container.classList.remove('scale-90');
                this.container.classList.add('scale-100');
            }, 10);

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

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

            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() {
            this.container.classList.remove('scale-100');
            this.container.classList.add('scale-90');

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

            this.modalStack = [];
        },

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

    ModalSystem.init();
});