(function ($) {
    'use strict';

    class SeekMakeFrontend {
        constructor() {
            this.modals = {};
            this.allowedOrigins = [
                'https://seekmake.com',
                'https://dev.seekmake.com',
                'https://www.seekmake.com'
            ];

            this.init();
        }

        init() {
            this.setupMessageListener();
            this.initializeWidgets();
            this.loadSeekMakeAPI();
        }

        loadSeekMakeAPI() {
            if (!document.getElementById('seekmake-api-script')) {
                const script = document.createElement('script');
                script.id = 'seekmake-api-script';
                script.src = 'https://seekmake.com/assets/public/iq-api-latest.js';
                script.async = true;
                document.body.appendChild(script);
            }
        }

        setupMessageListener() {
            window.addEventListener('message', (event) => {
                if (!this.validateOrigin(event.origin)) {
                    return;
                }

                this.handleMessage(event.data);
            });
        }

        validateOrigin(origin) {
            return this.allowedOrigins.includes(origin);
        }

        handleMessage(data) {
            if (!data || typeof data !== 'object') {
                return;
            }

            // Handle SeekMake iframe events (eventId format)
            if (data.eventId === 'EDITOR_PAY_NOW_EXTERNAL_CHECKOUT') {
                this.handleAddToCart(data.data);
                return;
            }

            const { type, payload } = data;

            switch (type) {
                case 'seekmake:resize':
                    this.handleResize(payload);
                    break;

                case 'seekmake:close':
                    this.handleClose(payload);
                    break;

                case 'seekmake:navigate':
                    this.handleNavigate(payload);
                    break;

                case 'seekmake:quote_submitted':
                    this.handleQuoteSubmitted(payload);
                    break;

                default:
                    this.triggerCustomEvent(type, payload);
            }
        }

        initializeWidgets() {
            $('.seekmake-modal-trigger').on('click', (e) => {
                e.preventDefault();
                const widgetType = $(e.currentTarget).data('widget-type');
                this.openModal(widgetType, e.currentTarget);
            });

            this.setupInlineIframes();
        }

        setupInlineIframes() {
            $('.seekmake-embed-iq, .seekmake-embed-dashboard').each((index, iframe) => {
                $(iframe).on('load', () => {
                    this.adjustIframeHeight(iframe);
                });
            });
        }

        openModal(widgetType, triggerElement) {
            const manufacturerId = $(triggerElement).data('manufacturer-id') || seekmakePublic.manufacturerId;
            const lang = $(triggerElement).data('lang') || 'en';

            let iframeSrc = '';
            let modalId = 'seekmake-modal-' + widgetType;

            switch (widgetType) {
                case 'instant-quote':
                    iframeSrc = `${seekmakePublic.apiUrl}/instant-quote/?isEmbed=true&manufacturer=${manufacturerId}`;
                    break;
                case 'client-dashboard':
                    iframeSrc = `${seekmakePublic.apiUrl}/dashboard/client?isEmbed=true&manufacturer=${manufacturerId}&lang=${lang}`;
                    break;
                default:
                    return;
            }

            if (!this.modals[modalId]) {
                this.createModal(modalId, iframeSrc, widgetType);
            }

            this.showModal(modalId);
        }

        createModal(modalId, iframeSrc, widgetType) {
            const modalHtml = `
                <div id="${modalId}" class="seekmake-modal" data-widget-type="${widgetType}">
                    <div class="seekmake-modal-overlay"></div>
                    <div class="seekmake-modal-content">
                        <button class="seekmake-modal-close" aria-label="Close">
                            <span>&times;</span>
                        </button>
                        <div class="seekmake-modal-body">
                            <iframe
                                class="seekmake-modal-iframe"
                                src="${iframeSrc}"
                                sandbox="allow-downloads allow-scripts allow-same-origin allow-forms allow-popups"
                                scrolling="no"
                            ></iframe>
                        </div>
                    </div>
                </div>
            `;

            $('body').append(modalHtml);
            this.modals[modalId] = true;

            $(`#${modalId} .seekmake-modal-close, #${modalId} .seekmake-modal-overlay`).on('click', () => {
                this.closeModal(modalId);
            });

            $(document).on('keydown', (e) => {
                if (e.key === 'Escape') {
                    this.closeModal(modalId);
                }
            });
        }

        showModal(modalId) {
            $(`#${modalId}`).addClass('active');
            $('body').addClass('seekmake-modal-open');
        }

        closeModal(modalId) {
            $(`#${modalId}`).removeClass('active');
            $('body').removeClass('seekmake-modal-open');
        }

        handleResize(payload) {
            const { height, width } = payload;

            $('.seekmake-modal.active iframe').css({
                height: height + 'px'
            });
        }

        handleClose(payload) {
            const activeModal = $('.seekmake-modal.active');
            if (activeModal.length) {
                this.closeModal(activeModal.attr('id'));
            }
        }

        handleNavigate(payload) {
            if (payload.url) {
                window.location.href = payload.url;
            }
        }

        handleQuoteSubmitted(payload) {
            this.triggerCustomEvent('seekmake_quote_submitted', payload);
            this.showNotification('Quote submitted successfully!', 'success');
        }

        handleAddToCart(eventData) {
            if (!seekmakePublic.woocommerceEnabled) {
                return;
            }

            // Close the iframe/modal immediately
            this.closeSeekMakeWidget();

            const data = {
                action: 'seekmake_wc_add_to_cart',
                nonce: seekmakePublic.wooNonce,
                items: JSON.stringify(eventData.items || []),
                subtotal: eventData.subtotal || 0,
                currency: eventData.currency || 'USD'
            };

            $.post(seekmakePublic.ajaxUrl, data, (response) => {
                if (response.success) {
                    this.showNotification(
                        response.data.message + ' <a href="' + response.data.cart_url + '" style="color:inherit;text-decoration:underline;">View Cart</a>',
                        'success'
                    );
                    // Refresh WooCommerce mini-cart fragments
                    $(document.body).trigger('wc_fragment_refresh');
                    this.triggerCustomEvent('seekmake_added_to_cart', response.data);
                } else {
                    this.showNotification(response.data.message || 'Failed to add items to cart.', 'error');
                }
            }).fail(() => {
                this.showNotification('Network error. Please try again.', 'error');
            });
        }

        closeSeekMakeWidget() {
            // Close modal if one is open
            const activeModal = $('.seekmake-modal.active');
            if (activeModal.length) {
                this.closeModal(activeModal.attr('id'));
                return;
            }

            // Hide inline iframe container
            const inlineContainer = $('#seekmake-quote-container');
            if (inlineContainer.length) {
                inlineContainer.slideUp(300);
            }
        }

        adjustIframeHeight(iframe) {
            try {
                const iframeWindow = iframe.contentWindow;
                if (iframeWindow) {
                    const height = iframeWindow.document.body.scrollHeight;
                    $(iframe).css('height', height + 'px');
                }
            } catch (e) {
            }
        }

        triggerCustomEvent(eventName, data) {
            const event = new CustomEvent(eventName, {
                detail: data,
                bubbles: true,
                cancelable: true
            });
            document.dispatchEvent(event);
        }

        showNotification(message, type = 'info') {
            const notification = $(`
                <div class="seekmake-notification seekmake-notification-${type}">
                    ${message}
                </div>
            `);

            $('body').append(notification);

            setTimeout(() => {
                notification.addClass('active');
            }, 10);

            setTimeout(() => {
                notification.removeClass('active');
                setTimeout(() => {
                    notification.remove();
                }, 300);
            }, 5000);
        }
    }

    $(document).ready(function () {
        if (typeof seekmakePublic !== 'undefined') {
            new SeekMakeFrontend();
        }
    });

})(jQuery);
