// static/programmer/js/floating-button.js
const CallbackModal = {
    shown: false,
    modalId: 'callbackModal',
    floatingBtnId: 'floatingButton',

    init() {
        setTimeout(() => {
            const btn = document.getElementById(this.floatingBtnId);
            if (btn) {
                btn.style.display = 'block';
                this.shown = true;
                const button = btn.querySelector('.btn');
                if (button) button.classList.add('pulse');
            }
        }, 5000);
    },

    open(productTitle) {
        const modal = document.getElementById(this.modalId);
        if (modal) {

            if (productTitle) {
            const questionField = modal.querySelector('#id_question');
            if (questionField) {
                questionField.value = `Запрос цены по ПП "${productTitle}"`;
                }
            }

            modal.style.display = 'block';
            const floatingBtn = document.getElementById(this.floatingBtnId);
            if (floatingBtn && this.shown) {
                floatingBtn.style.display = 'none';
            }
        }
    },

    close() {
        const modal = document.getElementById(this.modalId);
        if (modal) {
            modal.style.display = 'none';
            const floatingBtn = document.getElementById(this.floatingBtnId);
            if (floatingBtn && this.shown) {
                floatingBtn.style.display = 'block';
                const button = floatingBtn.querySelector('.btn.pulse');
                if (button) {
                    button.style.animation = 'none';
                    setTimeout(() => button.style.animation = '', 10);
                }
            }
        }
    }
};

// Инициализация и глобальные обработчики
document.addEventListener('DOMContentLoaded', () => {
    CallbackModal.init();

    // Закрытие по клику вне модального окна
    const modal = document.getElementById(CallbackModal.modalId);
    if (modal) {
        modal.addEventListener('click', (event) => {
            if (event.target === modal) CallbackModal.close();
        });
    }

    // Закрытие по ESC
    document.addEventListener('keydown', (event) => {
        if (event.key === 'Escape') CallbackModal.close();
    });
});