(function ($) {
    'use strict';

    class SeekMakeAdmin {
        constructor() {
            this.iframe = null;
            this.allowedOrigins = [
                'https://seekmake.com',
                'https://dev.seekmake.com',
                'https://www.seekmake.com',
                window.location.origin
            ];

            this.init();
        }

        init() {
            this.iframe = document.getElementById('seekmake-auth-iframe');

            const urlParams = new URLSearchParams(window.location.search);
            if (urlParams.has('logout')) {
                localStorage.clear();
                sessionStorage.clear();
                document.cookie.split(";").forEach(function (c) {
                    document.cookie = c.replace(/^ +/, "").replace(/=.*/, "=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/");
                });
            }

            this.hideLoadingOverlay();

            this.setupEventListeners();

            setTimeout(() => {
                this.hideLoadingOverlay();
            }, 3000);
        }

        setupEventListeners() {
            if (this.iframe) {
                this.setupMessageListener();
                this.setupIframeLoadHandler();
            }
            this.setupDisconnectHandler();
        }

        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;
            }

            const type = data.type || (data.eventId ? `seekmake:${data.eventId.toLowerCase()}` : '');

            if (!type || !type.startsWith('seekmake:')) {
                return;
            }

            const payload = data.payload || data;

            if (data.eventId === 'SUCCESS_AUTH' && data.businessId) {
                payload.manufacturerId = data.businessId;
            }

            switch (type) {
                case 'seekmake:ready':
                    this.handleReadyEvent(payload);
                    break;

                case 'seekmake:auth_success':
                case 'seekmake:success_auth':
                    this.handleAuthSuccess(payload);
                    break;

                case 'seekmake:auth_failed':
                    this.handleAuthFailed(payload);
                    break;

                case 'seekmake:signup_complete':
                    this.handleSignupComplete(payload);
                    break;

                case 'seekmake:config_updated':
                    this.handleConfigUpdate(payload);
                    break;

                case 'seekmake:settings_changed':
                    this.handleSettingsChange(payload);
                    break;

                case 'seekmake:manufacturer_id_changed':
                    this.handleManufacturerIdChange(payload);
                    break;

                case 'seekmake:user_disconnected':
                    break;

                case 'seekmake:auto_update':
                    this.handleAutoUpdate(payload);
                    break;

                case 'seekmake:error':
                    this.handleError(payload);
                    break;

                default:
            }
        }

        handleReadyEvent(payload) {
            this.sendToIframe({
                type: 'wordpress:config',
                payload: {
                    manufacturerId: seekmakeAdmin.manufacturerId,
                    platform: 'wordpress',
                    version: '1.0.0',
                    siteUrl: window.location.origin
                }
            });
        }

        handleAuthSuccess(payload) {
            const manufacturerId = payload.manufacturerId || payload.manufacturer_id || payload.businessId;

            if (!manufacturerId) {
                this.hideLoadingOverlay();
                this.showNotice('❌ Authentication failed: No manufacturer ID received', 'error');
                return;
            }

            if (this.iframe) {
                this.iframe.src = 'about:blank';
                this.iframe.style.display = 'none';
                setTimeout(() => {
                    if (this.iframe && this.iframe.parentNode) {
                        this.iframe.parentNode.removeChild(this.iframe);
                    }
                }, 100);
            }

            const authCard = document.querySelector('.seekmake-auth-card');
            if (authCard) {
                authCard.style.display = 'none';
            }

            this.showLoadingOverlay('Connecting to your account...');
            this.updateLoadingMessage('Activating features...');

            this.sendAjaxRequest('seekmake_handle_auth', {
                event_type: 'auth_success',
                event_data: {
                    manufacturer_id: manufacturerId,
                    user_email: payload.email || payload.userEmail || '',
                    user_name: payload.name || payload.userName || '',
                    token: payload.token || '',
                    authenticated: true
                }
            }).then(response => {
                this.hideLoadingOverlay();
                this.showSuccessScreen();

                setTimeout(() => {
                    const currentUrl = new URL(window.location.href);
                    currentUrl.searchParams.set('t', Date.now());
                    window.location.href = currentUrl.toString();
                }, 2500);
            }).catch(error => {
                this.hideLoadingOverlay();
                this.showNotice('❌ Failed to activate account. Please try again.', 'error');
            });
        }

        updateLoadingMessage(message) {
            const loadingText = document.querySelector('.seekmake-loading-text');
            if (loadingText) {
                loadingText.textContent = message;
            }
        }

        handleAuthFailed(payload) {
            this.showNotice(payload.message || 'Authentication failed. Please try again.', 'error');
        }

        handleSignupComplete(payload) {
            this.handleAuthSuccess(payload);
        }

        handleConfigUpdate(payload) {
            this.sendAjaxRequest('seekmake_handle_event', {
                event_type: 'config_updated',
                event_data: payload
            }).then(response => {
                this.showNotice('Configuration updated successfully', 'success');
            }).catch(error => {
                this.showNotice('Failed to update configuration', 'error');
            });
        }

        handleSettingsChange(payload) {
            this.sendAjaxRequest('seekmake_handle_event', {
                event_type: 'widget_settings_changed',
                event_data: payload
            }).then(response => {
                this.showNotice('Settings updated successfully', 'success');
            }).catch(error => {
                this.showNotice('Failed to update settings', 'error');
            });
        }

        handleManufacturerIdChange(payload) {
            this.sendAjaxRequest('seekmake_handle_event', {
                event_type: 'manufacturer_id_changed',
                event_data: payload
            }).then(response => {
                seekmakeAdmin.manufacturerId = payload.manufacturer_id;
                this.showNotice('Manufacturer ID updated successfully', 'success');

                setTimeout(() => {
                    const currentUrl = new URL(window.location.href);
                    currentUrl.searchParams.set('t', Date.now());
                    window.location.href = currentUrl.toString();
                }, 1500);
            }).catch(error => {
                this.showNotice('Failed to update manufacturer ID', 'error');
            });
        }

        setupDisconnectHandler() {
            const disconnectBtn = document.getElementById('seekmake-dashboard-disconnect');

            if (!disconnectBtn) {
                return;
            }

            disconnectBtn.addEventListener('click', (e) => {
                e.preventDefault();

                if (!confirm('Are you sure you want to disconnect your SeekMake account?')) {
                    return;
                }

                disconnectBtn.disabled = true;
                disconnectBtn.innerHTML = '<span style="animation: rotation 1s infinite linear;">⟳</span> Disconnecting...';

                const disconnectEvent = {
                    eventId: 'USER_DISCONNECTED'
                };

                if (this.iframe && this.iframe.contentWindow) {
                    this.iframe.contentWindow.postMessage(disconnectEvent, 'https://dev.seekmake.com');
                }

                window.postMessage(disconnectEvent, '*');

                document.cookie.split(";").forEach(function (c) {
                    document.cookie = c.replace(/^ +/, "").replace(/=.*/, "=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/");
                });

                setTimeout(() => {
                    this.sendAjaxRequest('seekmake_disconnect_account', {})
                        .then(response => {
                            const currentUrl = new URL(window.location.href);
                            currentUrl.searchParams.set('logout', '1');
                            currentUrl.searchParams.set('t', Date.now());
                            window.location.href = currentUrl.toString();
                        })
                        .catch(error => {
                            alert('Failed to disconnect. Please try again.');
                            disconnectBtn.disabled = false;
                            disconnectBtn.innerHTML = 'Disconnect';
                        });
                }, 500);
            });
        }

        handleAutoUpdate(payload) {
            this.sendAjaxRequest('seekmake_handle_event', {
                event_type: 'auto_update',
                event_data: payload
            }).then(response => {
                this.showNotice('Auto-update completed successfully', 'success');
            }).catch(error => {
            });
        }

        handleError(payload) {
            this.showNotice(payload.message || 'An error occurred', 'error');
        }

        sendToIframe(message) {
            if (this.iframe && this.iframe.contentWindow) {
                this.iframe.contentWindow.postMessage(message, '*');
            }
        }

        setupIframeLoadHandler() {
            if (!this.iframe) return;
            this.iframe.addEventListener('load', () => {
                setTimeout(() => {
                    this.hideLoadingOverlay();
                }, 500);
            });
        }

        sendAjaxRequest(action, data) {
            return new Promise((resolve, reject) => {
                $.ajax({
                    url: seekmakeAdmin.ajaxUrl,
                    type: 'POST',
                    data: {
                        action: action,
                        seekmake_nonce: seekmakeAdmin.nonce,
                        ...data
                    },
                    success: function (response) {
                        if (response.success) {
                            resolve(response.data);
                        } else {
                            reject(response.data);
                        }
                    },
                    error: function (xhr, status, error) {
                        reject(error);
                    }
                });
            });
        }

        showLoadingOverlay(message = 'Loading...') {
            const loading = document.getElementById('seekmake-loading');
            if (loading) {
                const text = loading.querySelector('.seekmake-loading-text');
                if (text) {
                    text.textContent = message;
                }
                loading.classList.remove('hidden');
                loading.style.display = 'flex';
            }
        }

        hideLoadingOverlay() {
            const loading = document.getElementById('seekmake-loading');
            if (loading) {
                loading.classList.add('hidden');
                loading.style.display = 'none';
            }
        }

        showNotice(message, type = 'info') {
            const noticeClass = type === 'error' ? 'notice-error' : 'notice-success';
            const noticeHtml = `
                <div class="notice ${noticeClass} is-dismissible seekmake-notice">
                    <p>${message}</p>
                </div>
            `;

            $('.seekmake-admin-wrapper, .wrap').prepend(noticeHtml);

            setTimeout(() => {
                $('.seekmake-notice').fadeOut(300, function () {
                    $(this).remove();
                });
            }, 5000);
        }

        showSuccessScreen() {
            const successHtml = `
                <div class="seekmake-success-overlay" id="seekmake-success-overlay">
                    <div class="seekmake-success-content">
                        <div class="seekmake-success-checkmark-container">
                            <svg class="seekmake-success-checkmark" viewBox="0 0 52 52">
                                <circle class="seekmake-success-checkmark-circle" cx="26" cy="26" r="25" fill="none"/>
                                <path class="seekmake-success-checkmark-check" fill="none" d="M14.1 27.2l7.1 7.2 16.7-16.8"/>
                            </svg>
                        </div>
                        <h2 class="seekmake-success-title">Plugin activated successfully</h2>
                        <p class="seekmake-success-message">All widgets and features are now active!</p>
                    </div>
                </div>
            `;

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

            setTimeout(() => {
                $('#seekmake-success-overlay').addClass('active');
            }, 10);
        }
    }

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

})(jQuery);
