// source --> http://www.thetotaldentistry.com/wp-content/plugins/wp-cforms-spam-protect/js/script.js?ver=f590f6865238273377f452fe2e7f8236 
document.addEventListener("DOMContentLoaded", () => {
    // Helper function to wait for gtag with timeout
    function waitForGtag(callback, maxWaitTime = 1500) {
        if (typeof gtag !== 'undefined') {
            callback();
            return;
        }

        // Force load gtag if not already loading
        if (typeof window.loadGtagScript === 'function' && !window.gaScriptLoaded) {
            window.loadGtagScript();
        }

        const startTime = Date.now();
        const checkInterval = setInterval(() => {
            if (typeof gtag !== 'undefined') {
                clearInterval(checkInterval);
                callback();
            } else if (Date.now() - startTime > maxWaitTime) {
                clearInterval(checkInterval);
                console.warn('gtag loading timeout. Analytics event may not be sent.');
                callback(); // Continue anyway
            }
        }, 100);
    }

    // Trigger gtag loading on form interaction (optimization)
    let formInteractionTracked = false;
    document.addEventListener('focus', event => {
        if (formInteractionTracked || !(event.target instanceof Element)) return;

        const form = event.target.closest('.wpcf7-form');
        if (form && typeof window.loadGtagScript === 'function' && !window.gaScriptLoaded) {
            window.loadGtagScript();
            formInteractionTracked = true;
        }
    }, true);

    // Form submission handler
    document.addEventListener('wpcf7mailsent', event => {
        if (!event?.detail?.unitTag) return;
        // Google Analytics tracking - Get form title from hidden field
        // unitTag is used as an ID, not a class
        const formElement = document.getElementById(event.detail.unitTag);
        let formTitle = 'Contact Form';

        if (formElement) {
            const formTitleField = formElement.querySelector('input[name="form_title"]');
            if (formTitleField && formTitleField.value) {
                formTitle = formTitleField.value;
            }
        }

        // Format form title and page URI as "form-title__page-uri"
        const formatSlug = (str) => str.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '');
        const formattedTitle = formatSlug(formTitle);
        const pageUri = formatSlug(window.location.pathname.replace(/^\/|\/$/g, '') || 'home');
        const formIdentifier = `${formattedTitle}__${pageUri}`;

        const extraParams = localStorage.getItem('cf7-extraparams');
        if (extraParams) localStorage.removeItem('cf7-extraparams');

        // Wait for gtag to be available before sending event and redirecting
        waitForGtag(() => {
            // Send analytics event if gtag is now available
            if (typeof gtag !== 'undefined') {
                try {
                    gtag('event', 'generate_lead', {
                        event_category: 'form',
                        event_label: formIdentifier,
                        form_id: event.detail.contactFormId
                    });
                } catch (error) {
                    console.warn('Error sending gtag event:', error);
                }
            } else {
                console.warn('gtag is not defined. Google Analytics event not sent.');
            }

            // Redirect after sending analytics
            setTimeout(() => {
                const homeUrl = document.querySelector('a[rel="home"]')?.getAttribute('href') || '';
                let baseUrl = (homeUrl.length > 10 && homeUrl !== window.location.origin + '/') ? homeUrl : window.location.origin + '/';
                if (!baseUrl.endsWith('/')) baseUrl += '/';
                window.location = `${baseUrl}thank-you-for-your-submission/?form=${event.detail.unitTag}${extraParams ? '&' + extraParams : ''}&path=${window.location.pathname.replace(/\//g, '')}`;
            }, 500);
        });
    }, false);

    // UTM and referrer tracking
    const url = new URL(window.location);
    const currentHostname = window.location.hostname;
    const referrerHost = document.referrer ? new URL(document.referrer).hostname : '';

    if (referrerHost && referrerHost !== currentHostname) {
        if (referrerHost.includes('google.com') || referrerHost.includes('facebook')) {
            localStorage.setItem('referrerUrl', referrerHost);
        }
        referrerUrl = referrerHost;
    } else {
        referrerUrl = localStorage.getItem('referrerUrl') || currentHostname;
    }

    let uatCode = localStorage.getItem('uatCode') || '--';
    let uat = url.searchParams.get('uat');

    // Set tracking codes based on source
    if (url.searchParams.get('gclid')) {
        [uat, uatCode] = ['ven', '$$-ads-G'];
        localStorage.setItem('referrerUrl', "ads.google.com");
    } else if (referrerUrl.includes('ads.google.com')) {
        [uat, uatCode] = ['ven', '$$-ads-G'];
    } else if (referrerUrl.includes('google.com')) {
        [uat, uatCode] = ['ven', '$$-organic-G'];
    } else if (referrerUrl.includes('facebook.com')) {
        [uat, uatCode] = ['ven', '$$-FB'];
    } else {
        [uat, uatCode] = ['ven', '$$-organic-other'];
    }

    // Append campaign name if present
    const cname = url.searchParams.get('cname');
    if (cname) uatCode += ` - ${cname}`;

    // Update UAT fields if present
    const uatFields = document.getElementsByName('hlnk');
    if (uatFields.length) {
        setTimeout(() => {
            uatFields.forEach(elem => elem.value = `${uatCode} :: ${referrerUrl}`);
        }, 2000);
    }

    // Store tracking data
    if (uat === 'ven') {
        const expDate = new Date();
        expDate.setDate(expDate.getDate() + 1);
        localStorage.setItem('uat', uat);
        localStorage.setItem('uat-exp', expDate.getTime());
    }
    if (uatCode) localStorage.setItem('uatCode', uatCode);
});