/**
 * VMO Visit Tracker — Frontend Analytics Client
 * Sends visitor data to the VMO Analytics Tracker backend
 * 
 * Works with: includes/class-vmo-analytics-tracker.php
 * Endpoints: vmo_track_visit, vmo_track_pageview, vmo_track_event, vmo_track_exit
 * 
 * @package VMO_AI_Website_Builder
 * @version 1.0.0
 */
;(function() {
    'use strict';

    /* ───────── Configuration ───────── */

    const CONFIG = {
        sessionTimeoutMs: 30 * 60 * 1000,  // 30 minutes = new session
        heartbeatIntervalMs: 30 * 1000,     // Track time-on-page every 30s
        scrollDepthThresholds: [25, 50, 75, 90, 100],
        maxEventsPerPage: 50,
        storagePrefix: 'vmo_vt_',
        debug: false
    };

    /* ───────── State ───────── */

    let contactId = null;
    let interactionId = null;
    let pageEntryTime = Date.now();
    let eventCount = 0;
    let scrollDepthReported = new Set();
    let heartbeatTimer = null;
    let ajaxUrl = '';
    let siteUserId = 0;

    /* ───────── Utilities ───────── */

    function log() {
        if (!CONFIG.debug) return;
        console.log('[VMO Tracker]', ...arguments);
    }

    function getAjaxUrl() {
        // Try multiple sources for the AJAX URL
        if (typeof vmo_tracker_data !== 'undefined' && vmo_tracker_data.ajaxurl) {
            return vmo_tracker_data.ajaxurl;
        }
        if (typeof vmo_ajax !== 'undefined' && vmo_ajax.ajaxurl) {
            return vmo_ajax.ajaxurl;
        }
        if (typeof ajaxurl !== 'undefined') {
            return ajaxurl;
        }
        // Fallback: construct from current URL
        const wpAdmin = document.querySelector('link[href*="wp-admin"]');
        if (wpAdmin) {
            return wpAdmin.href.replace(/\/wp-admin\/.*/, '/wp-admin/admin-ajax.php');
        }
        return '/wp-admin/admin-ajax.php';
    }

    function getSiteUserId() {
        if (typeof vmo_tracker_data !== 'undefined' && vmo_tracker_data.site_user_id) {
            return parseInt(vmo_tracker_data.site_user_id, 10) || 0;
        }
        return 0;
    }

    function getStoredContactId() {
        try {
            const stored = localStorage.getItem(CONFIG.storagePrefix + 'contact_id');
            const ts = parseInt(localStorage.getItem(CONFIG.storagePrefix + 'last_visit') || '0', 10);
            if (stored && (Date.now() - ts) < CONFIG.sessionTimeoutMs) {
                return stored;
            }
        } catch (e) { /* localStorage unavailable */ }
        return null;
    }

    function storeContactId(id) {
        try {
            localStorage.setItem(CONFIG.storagePrefix + 'contact_id', id);
            localStorage.setItem(CONFIG.storagePrefix + 'last_visit', String(Date.now()));
        } catch (e) { /* localStorage unavailable */ }
    }

    function getUTMParams() {
        const params = new URLSearchParams(window.location.search);
        return {
            utm_source: params.get('utm_source') || '',
            utm_medium: params.get('utm_medium') || '',
            utm_campaign: params.get('utm_campaign') || '',
            utm_term: params.get('utm_term') || '',
            utm_content: params.get('utm_content') || ''
        };
    }

    function getBrowserInfo() {
        const ua = navigator.userAgent || '';
        let browser = 'Unknown';
        let os = 'Unknown';

        // Browser detection
        if (ua.indexOf('Firefox') > -1) browser = 'Firefox';
        else if (ua.indexOf('SamsungBrowser') > -1) browser = 'Samsung Browser';
        else if (ua.indexOf('Opera') > -1 || ua.indexOf('OPR') > -1) browser = 'Opera';
        else if (ua.indexOf('Edg') > -1) browser = 'Edge';
        else if (ua.indexOf('Chrome') > -1) browser = 'Chrome';
        else if (ua.indexOf('Safari') > -1) browser = 'Safari';
        else if (ua.indexOf('MSIE') > -1 || ua.indexOf('Trident') > -1) browser = 'IE';

        // OS detection
        if (ua.indexOf('Windows') > -1) os = 'Windows';
        else if (ua.indexOf('Mac') > -1) os = 'macOS';
        else if (ua.indexOf('Linux') > -1) os = 'Linux';
        else if (ua.indexOf('Android') > -1) os = 'Android';
        else if (ua.indexOf('iPhone') > -1 || ua.indexOf('iPad') > -1) os = 'iOS';

        // Device type
        let device = 'desktop';
        if (/Mobi|Android/i.test(ua)) device = 'mobile';
        else if (/Tablet|iPad/i.test(ua)) device = 'tablet';

        return { browser, os, device };
    }

    function getScrollDepth() {
        const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
        const docHeight = Math.max(
            document.body.scrollHeight,
            document.documentElement.scrollHeight,
            document.body.offsetHeight,
            document.documentElement.offsetHeight
        );
        const winHeight = window.innerHeight;
        if (docHeight <= winHeight) return 100;
        return Math.round((scrollTop / (docHeight - winHeight)) * 100);
    }

    /* ───────── AJAX Sender ───────── */

    function sendTracking(action, data, useBeacon) {
        if (!ajaxUrl) return;

        const formData = new FormData();
        formData.append('action', action);

        // Add all tracking data fields
        Object.keys(data).forEach(function(key) {
            formData.append(key, data[key]);
        });

        // Use sendBeacon for exit events (page unload)
        if (useBeacon && navigator.sendBeacon) {
            const blob = new Blob([new URLSearchParams(data).toString() + '&action=' + action], {
                type: 'application/x-www-form-urlencoded'
            });
            navigator.sendBeacon(ajaxUrl, blob);
            log('Beacon sent:', action);
            return;
        }

        // Standard fetch for normal events
        fetch(ajaxUrl, {
            method: 'POST',
            body: formData,
            credentials: 'same-origin',
            keepalive: true
        })
        .then(function(resp) { return resp.json(); })
        .then(function(json) {
            if (json.success) {
                log(action + ' tracked:', json.data);
                // Store contact_id from initial visit
                if (action === 'vmo_track_visit' && json.data && json.data.contact_id) {
                    contactId = json.data.contact_id;
                    storeContactId(contactId);
                    interactionId = json.data.interaction_id;
                }
            }
        })
        .catch(function(err) {
            log(action + ' failed:', err.message);
        });
    }

    /* ───────── Core Tracking Functions ───────── */

    function trackInitialVisit() {
        const info = getBrowserInfo();
        const utm = getUTMParams();

        const data = {
            page_url: window.location.href,
            page_title: document.title,
            referrer: document.referrer || '',
            user_id: siteUserId,
            contact_id: contactId || '',
            device: info.device,
            browser: info.browser,
            os: info.os,
            screen_width: screen.width,
            screen_height: screen.height,
            language: navigator.language || '',
            timezone: Intl.DateTimeFormat().resolvedOptions().timeZone || '',
            utm_source: utm.utm_source,
            utm_medium: utm.utm_medium,
            utm_campaign: utm.utm_campaign
        };

        sendTracking('vmo_track_visit', data, false);
    }

    function trackPageview() {
        if (!contactId) return;

        const elapsed = Math.round((Date.now() - pageEntryTime) / 1000);

        const data = {
            page_url: window.location.href,
            page_title: document.title,
            user_id: siteUserId,
            contact_id: contactId,
            time_on_page: elapsed
        };

        sendTracking('vmo_track_pageview', data, false);
    }

    function trackEvent(eventName, eventData) {
        if (!contactId) return;
        if (eventCount >= CONFIG.maxEventsPerPage) return;
        eventCount++;

        const data = {
            page_url: window.location.href,
            user_id: siteUserId,
            contact_id: contactId,
            event_name: eventName,
            event_data: JSON.stringify(eventData || {})
        };

        sendTracking('vmo_track_event', data, false);
    }

    function trackExit() {
        if (!contactId) return;

        const elapsed = Math.round((Date.now() - pageEntryTime) / 1000);
        const depth = getScrollDepth();

        const data = {
            page_url: window.location.href,
            user_id: siteUserId,
            contact_id: contactId,
            time_on_page: elapsed,
            scroll_depth: depth,
            interaction_id: interactionId || ''
        };

        sendTracking('vmo_track_exit', data, true); // Use beacon for reliability
    }

    /* ───────── Scroll Depth Tracking ───────── */

    function onScroll() {
        const depth = getScrollDepth();
        CONFIG.scrollDepthThresholds.forEach(function(threshold) {
            if (depth >= threshold && !scrollDepthReported.has(threshold)) {
                scrollDepthReported.add(threshold);
                trackEvent('scroll_depth', { threshold: threshold, page: window.location.pathname });
            }
        });
    }

    /* ───────── Click Tracking ───────── */

    function onClick(e) {
        const target = e.target.closest('a, button, [data-vmo-track]');
        if (!target) return;

        const trackData = {
            tag: target.tagName.toLowerCase(),
            text: (target.innerText || '').substring(0, 100).trim(),
            page: window.location.pathname
        };

        if (target.href) {
            trackData.href = target.href;
            // Check if it's an outbound link
            if (target.hostname && target.hostname !== window.location.hostname) {
                trackData.type = 'outbound_click';
            }
        }

        if (target.dataset.vmoTrack) {
            trackData.category = target.dataset.vmoTrack;
        }

        const eventName = trackData.type || (target.tagName === 'A' ? 'link_click' : 'button_click');
        trackEvent(eventName, trackData);
    }

    /* ───────── Form Submission Tracking ───────── */

    function onFormSubmit(e) {
        const form = e.target;
        if (!form || form.tagName !== 'FORM') return;

        trackEvent('form_submit', {
            form_id: form.id || '',
            form_action: form.action || '',
            form_method: form.method || 'get',
            page: window.location.pathname
        });
    }

    /* ───────── Heartbeat (Time on Page) ───────── */

    function startHeartbeat() {
        if (heartbeatTimer) return;
        heartbeatTimer = setInterval(function() {
            // Passive heartbeat — just keeps session alive
            // Actual time-on-page is sent on exit
        }, CONFIG.heartbeatIntervalMs);
    }

    function stopHeartbeat() {
        if (heartbeatTimer) {
            clearInterval(heartbeatTimer);
            heartbeatTimer = null;
        }
    }

    /* ───────── Page Visibility ───────── */

    function onVisibilityChange() {
        if (document.visibilityState === 'hidden') {
            trackExit();
        }
    }

    /* ───────── Initialization ───────── */

    function init() {
        // Skip tracking for logged-in WordPress admins in wp-admin
        if (document.body && document.body.classList.contains('wp-admin')) return;
        // Skip bots
        if (/bot|crawl|spider|slurp|facebookexternalhit|Googlebot/i.test(navigator.userAgent)) return;

        ajaxUrl = getAjaxUrl();
        siteUserId = getSiteUserId();
        contactId = getStoredContactId();

        log('Initializing. Ajax URL:', ajaxUrl, 'User:', siteUserId, 'Contact:', contactId);

        // Track the initial visit
        trackInitialVisit();

        // Start heartbeat
        startHeartbeat();

        // Scroll depth tracking (throttled)
        let scrollTimer = null;
        window.addEventListener('scroll', function() {
            if (scrollTimer) return;
            scrollTimer = setTimeout(function() {
                scrollTimer = null;
                onScroll();
            }, 250);
        }, { passive: true });

        // Click tracking
        document.addEventListener('click', onClick, true);

        // Form submission tracking
        document.addEventListener('submit', onFormSubmit, true);

        // Track exit on page unload / visibility change
        document.addEventListener('visibilitychange', onVisibilityChange);
        window.addEventListener('beforeunload', trackExit);
        window.addEventListener('pagehide', trackExit);

        log('Visit tracker initialized');
    }

    /* ───────── Public API ───────── */

    window.VMOVisitTracker = {
        trackEvent: trackEvent,
        trackPageview: trackPageview,
        getContactId: function() { return contactId; }
    };

    /* ───────── Boot ───────── */

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }
})();
