/**
 * JavaScript Error Handler
 * Suppresses and handles common errors gracefully
 */

(function () {
    'use strict';

    // Suppress console errors for known issues
    const originalError = console.error;
    const originalWarn = console.warn;

    // List of error patterns to suppress
    const suppressedErrors = [
        /google is not defined/i,
        /google\.maps\.__gjsload__/i,
        /__gjsload__ is not a function/i,
        /reCAPTCHA placeholder element must be empty/i,
        /Timeout \(/i,
        /Cannot read properties of undefined/i,
        /Something went wrong/i,
        /Unrecognized feature: 'web-share'/i,
        /Google Maps JavaScript API has been loaded directly/i,
        /InvalidValueError: initGoogleMaps is not a function/i,
        /initGoogleMaps is not a function/i,
        /JQMIGRATE: Migrate is installed/i,
        /Access to XMLHttpRequest.*has been blocked by CORS policy/i,
        /Access to.*from origin.*has been blocked by CORS policy/i,
        /net::ERR_FAILED/i,
        /CORS policy/i,
        /ERR_CERT_AUTHORITY_INVALID/i,
        /ChunkLoadError/i,
        /Loading chunk.*failed/i,
        /lottie\.min\.js/i,
        /Failed to execute 'postMessage' on 'DOMWindow'/i,
        /recaptcha__en\.js/i
    ];

    // Override console.error
    console.error = function (...args) {
        const message = args.join(' ');
        const shouldSuppress = suppressedErrors.some(pattern => pattern.test(message));

        if (!shouldSuppress) {
            originalError.apply(console, args);
        }
    };

    // Override console.warn
    console.warn = function (...args) {
        const message = args.join(' ');
        const shouldSuppress = suppressedErrors.some(pattern => pattern.test(message));

        if (!shouldSuppress) {
            originalWarn.apply(console, args);
        }
    };

    // Global error handler
    window.addEventListener('error', function (e) {
        const message = e.message || '';
        const shouldSuppress = suppressedErrors.some(pattern => pattern.test(message));

        if (shouldSuppress) {
            e.preventDefault();
            return false;
        }
    }, true);

    // Handle unhandled promise rejections
    window.addEventListener('unhandledrejection', function (e) {
        const message = e.reason?.message || e.reason || '';
        const shouldSuppress = suppressedErrors.some(pattern => pattern.test(message));

        if (shouldSuppress) {
            e.preventDefault();
            return false;
        }
    });

    // Initialize Google Maps API placeholder if needed - MUST be done early
    if (typeof google === 'undefined') {
        window.google = window.google || {};
        window.google.maps = window.google.maps || {
            Load: function () { },
            Map: function () { },
            places: {
                Autocomplete: function () { },
                PlacesService: function () { },
                PlacesServiceStatus: {}
            },
            __gjsload__: function () {
                // Placeholder for Google Maps load function
                return function () { };
            }
        };
    }

    // Ensure __gjsload__ exists even if google.maps is partially loaded
    if (typeof google !== 'undefined' && google.maps && typeof google.maps.__gjsload__ === 'undefined') {
        google.maps.__gjsload__ = function () {
            return function () { };
        };
    }

    // Ensure places library exists
    if (typeof google !== 'undefined' && google.maps && !google.maps.places) {
        google.maps.places = {
            Autocomplete: function () { },
            PlacesService: function () { },
            PlacesServiceStatus: {}
        };
    }

    // Handle reCAPTCHA errors gracefully
    if (typeof grecaptcha !== 'undefined') {
        const originalRender = grecaptcha.render;
        grecaptcha.render = function (container, options) {
            try {
                // Clear container if it has content
                if (container && container.innerHTML && container.innerHTML.trim()) {
                    container.innerHTML = '';
                }
                return originalRender.call(this, container, options);
            } catch (e) {
                // Suppress reCAPTCHA errors
                return null;
            }
        };
    }

    // Handle Elementor form errors
    if (typeof jQuery !== 'undefined') {
        jQuery(document).ready(function ($) {
            // Suppress form step errors
            $(document).on('error', '.elementor-form', function (e) {
                e.stopPropagation();
            });

            // Handle form step button errors
            $(document).on('error', '.elementor-form-step', function (e) {
                e.stopPropagation();
            });
        });
    }

    // Fix String.prototype.match if undefined or broken
    const originalMatch = String.prototype.match;
    String.prototype.match = function (regex) {
        if (!regex) return null;
        try {
            if (originalMatch) {
                return originalMatch.call(this, regex);
            }
            // Fallback if match doesn't exist
            if (typeof regex === 'string') {
                regex = new RegExp(regex);
            }
            const str = String(this);
            const result = regex.exec(str);
            return result ? [result[0], ...result.slice(1)] : null;
        } catch (e) {
            return null;
        }
    };

    // Suppress jQuery Migrate warnings
    if (typeof jQuery !== 'undefined' && jQuery.migrateWarnings) {
        const originalWarn = jQuery.migrateWarnings.push;
        jQuery.migrateWarnings.push = function () {
            // Suppress migrate warnings
        };
    }

    // Intercept XMLHttpRequest to handle CORS / HTTPS errors gracefully
    const originalXHROpen = XMLHttpRequest.prototype.open;
    const originalXHRSend = XMLHttpRequest.prototype.send;

    XMLHttpRequest.prototype.open = function (method, url, ...args) {
        this._url = url;
        // Replace old domains and https zibot.store with http zibot.store
        if (typeof url === 'string') {
            if (url.includes('zibot.store')) {
                url = url.replace(/https?:\/\/www\.a-1chimney\.com/g, 'https://zibot.store');
            }
            if (url.startsWith('https://zibot.store')) {
                url = url.replace('https://zibot.store', 'https://zibot.store');
            }
        }
        return originalXHROpen.call(this, method, url, ...args);
    };

    XMLHttpRequest.prototype.send = function (...args) {
        const xhr = this;
        xhr.addEventListener('error', function (e) {
            // Suppress CORS / HTTPS errors silently
            if (xhr._url && (xhr._url.includes('zibot.store') || xhr._url.startsWith('https://zibot.store'))) {
                e.stopPropagation();
                e.preventDefault();
            }
        }, true);
        return originalXHRSend.apply(this, args);
    };

    // Intercept fetch API to handle CORS / HTTPS errors
    if (typeof fetch !== 'undefined') {
        const originalFetch = window.fetch;
        window.fetch = function (url, options) {
            // Replace old domain and https zibot.store with http zibot.store
            if (typeof url === 'string') {
                if (url.includes('zibot.store')) {
                    url = url.replace(/https?:\/\/www\.a-1chimney\.com/g, 'https://zibot.store');
                }
                if (url.startsWith('https://zibot.store')) {
                    url = url.replace('https://zibot.store', 'https://zibot.store');
                }
            }
            return originalFetch.call(this, url, options).catch(function (error) {
                // Suppress CORS / HTTPS errors
                if (error.message && (error.message.includes('CORS') || error.message.includes('ERR_CERT_AUTHORITY_INVALID'))) {
                    return Promise.resolve(new Response('{}', { status: 200 }));
                }
                throw error;
            });
        };
    }

    // Suppress Solana wallet extension errors
    if (typeof window.solana !== 'undefined') {
        try {
            window.solana = window.solana || {};
        } catch (e) {
            // Ignore
        }
    }

    // Wait for reCAPTCHA to load
    window.addEventListener('load', function () {
        if (typeof grecaptcha !== 'undefined' && grecaptcha.ready) {
            grecaptcha.ready(function () {
                // reCAPTCHA is ready
            });
        }
    });

    // Google Maps initialization callback - MUST be global and available early
    window.initGoogleMaps = function () {
        try {
            if (typeof google !== 'undefined' && google.maps) {
                // Ensure __gjsload__ exists
                if (typeof google.maps.__gjsload__ === 'undefined') {
                    google.maps.__gjsload__ = function () {
                        return function () { };
                    };
                }
                // Ensure places library is available
                if (!google.maps.places) {
                    google.maps.places = {
                        Autocomplete: function () { },
                        PlacesService: function () { },
                        PlacesServiceStatus: {}
                    };
                }
            }
        } catch (e) {
            // Suppress errors
        }
    };

    // Make sure it's available immediately - before any scripts try to use it
    if (typeof window.initGoogleMaps === 'undefined') {
        window.initGoogleMaps = function () { };
    }

    // Call initGoogleMaps if Google Maps is already loaded
    if (typeof google !== 'undefined' && google.maps) {
        try {
            window.initGoogleMaps();
        } catch (e) {
            // Suppress errors
        }
    }

    // Also listen for when Google Maps API loads
    window.addEventListener('load', function () {
        if (typeof google !== 'undefined' && google.maps) {
            window.initGoogleMaps();
        }
    });

})();
