/**
 * Rosy Analytics - Lightweight visitor tracking
 * Tracks page views, time on page, scroll depth, and custom events
 */
(function() {
    'use strict';

    const API_BASE = '/analytics-api';
    const STORAGE_KEY = '_rosy_visitor';
    const GEO_STORAGE_KEY = '_rosy_geo';

    // ============================================
    // CONFIGURATION - Easy toggle for features
    // ============================================
    const CONFIG = {
        // Set to true to request browser geolocation permission
        // Set to false to disable geolocation requests entirely
        ENABLE_GEOLOCATION: true,

        // How often to re-request location (in days)
        // Set to 0 to request every visit
        GEOLOCATION_REFRESH_DAYS: 7
    };
    // ============================================

    let visitorId = null;
    let pageViewId = null;
    let pageStartTime = Date.now();
    let maxScrollDepth = 0;
    let isVisible = true;
    let totalVisibleTime = 0;
    let lastVisibleTime = Date.now();

    // Get or create visitor ID from localStorage + cookie
    function getVisitorId() {
        // Try localStorage first
        let stored = localStorage.getItem(STORAGE_KEY);
        if (stored) {
            try {
                const data = JSON.parse(stored);
                if (data.id) return data.id;
            } catch (e) {}
        }

        // Try cookie
        const cookies = document.cookie.split(';');
        for (let cookie of cookies) {
            const [name, value] = cookie.trim().split('=');
            if (name === '_rv' && value) return value;
        }

        return null;
    }

    // Save visitor ID to localStorage
    function saveVisitorId(id) {
        localStorage.setItem(STORAGE_KEY, JSON.stringify({
            id: id,
            created: Date.now()
        }));
    }

    // Send tracking data
    async function sendTrack(endpoint, data) {
        try {
            const response = await fetch(API_BASE + endpoint, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                credentials: 'include',  // Include cookies
                body: JSON.stringify(data)
            });
            return await response.json();
        } catch (e) {
            console.error('Analytics error:', e);
            return null;
        }
    }

    // Check if we should request geolocation
    function shouldRequestGeolocation() {
        if (!CONFIG.ENABLE_GEOLOCATION) return false;
        if (!navigator.geolocation) return false;

        // Check if we've already requested recently
        const stored = localStorage.getItem(GEO_STORAGE_KEY);
        if (stored) {
            try {
                const data = JSON.parse(stored);
                const daysSinceRequest = (Date.now() - data.timestamp) / (1000 * 60 * 60 * 24);
                if (daysSinceRequest < CONFIG.GEOLOCATION_REFRESH_DAYS) {
                    return false; // Too soon to request again
                }
            } catch (e) {}
        }

        return true;
    }

    // Request geolocation permission and update page view
    function requestGeolocation() {
        if (!shouldRequestGeolocation()) return;

        navigator.geolocation.getCurrentPosition(
            // Success callback
            function(position) {
                const geoData = {
                    latitude: position.coords.latitude,
                    longitude: position.coords.longitude,
                    accuracy: position.coords.accuracy,
                    timestamp: Date.now(),
                    granted: true
                };

                // Save to localStorage so we don't ask again too soon
                localStorage.setItem(GEO_STORAGE_KEY, JSON.stringify(geoData));

                // Update the current page view with geolocation
                if (pageViewId) {
                    sendTrack('/update-geo', {
                        page_view_id: pageViewId,
                        latitude: geoData.latitude,
                        longitude: geoData.longitude,
                        accuracy: geoData.accuracy
                    });
                }
            },
            // Error callback (user denied or error occurred)
            function(error) {
                // Save that we asked (so we don't keep asking)
                localStorage.setItem(GEO_STORAGE_KEY, JSON.stringify({
                    timestamp: Date.now(),
                    granted: false,
                    error: error.code
                }));
            },
            // Options
            {
                enableHighAccuracy: false, // Don't need GPS precision
                timeout: 10000,            // 10 second timeout
                maximumAge: 300000         // Accept cached position up to 5 minutes old
            }
        );
    }

    // Initialize tracking
    async function init() {
        visitorId = getVisitorId();

        // Register/update visitor
        const result = await sendTrack('/track', {
            visitor_id: visitorId
        });

        if (result && result.visitor_id) {
            visitorId = result.visitor_id;
            saveVisitorId(visitorId);
        }

        // Record page view
        const pvResult = await sendTrack('/pageview', {
            visitor_id: visitorId,
            page_url: window.location.href,
            page_title: document.title,
            referrer: document.referrer
        });

        if (pvResult && pvResult.page_view_id) {
            pageViewId = pvResult.page_view_id;
        }

        // Setup geolocation on first user interaction (required for iOS)
        setupGeolocationTrigger();

        // Setup event listeners
        setupScrollTracking();
        setupVisibilityTracking();
        setupBeforeUnload();
    }

    // Request geolocation on first click/tap (iOS requires user gesture)
    function setupGeolocationTrigger() {
        if (!shouldRequestGeolocation()) return;

        let triggered = false;

        function onFirstInteraction() {
            if (triggered) return;
            triggered = true;

            // Remove listeners once triggered
            document.removeEventListener('click', onFirstInteraction);
            document.removeEventListener('touchend', onFirstInteraction);

            // Now request geolocation (within user gesture context)
            requestGeolocation();
        }

        document.addEventListener('click', onFirstInteraction);
        document.addEventListener('touchend', onFirstInteraction);
    }

    // Track scroll depth
    function setupScrollTracking() {
        let ticking = false;

        window.addEventListener('scroll', function() {
            if (!ticking) {
                window.requestAnimationFrame(function() {
                    const scrollTop = window.scrollY;
                    const docHeight = document.documentElement.scrollHeight - window.innerHeight;
                    const scrollPercent = docHeight > 0 ? Math.round((scrollTop / docHeight) * 100) : 0;

                    if (scrollPercent > maxScrollDepth) {
                        maxScrollDepth = scrollPercent;
                    }

                    ticking = false;
                });
                ticking = true;
            }
        });
    }

    // Track visibility (tab focus)
    function setupVisibilityTracking() {
        document.addEventListener('visibilitychange', function() {
            if (document.hidden) {
                // Page became hidden - accumulate visible time
                isVisible = false;
                totalVisibleTime += Date.now() - lastVisibleTime;
            } else {
                // Page became visible again
                isVisible = true;
                lastVisibleTime = Date.now();
            }
        });
    }

    // Send final data before leaving page
    function setupBeforeUnload() {
        window.addEventListener('beforeunload', function() {
            // Calculate final time on page
            if (isVisible) {
                totalVisibleTime += Date.now() - lastVisibleTime;
            }
            const timeOnPage = Math.round(totalVisibleTime / 1000);

            // Use sendBeacon for reliable delivery
            if (pageViewId && navigator.sendBeacon) {
                navigator.sendBeacon(API_BASE + '/update', JSON.stringify({
                    page_view_id: pageViewId,
                    time_on_page: timeOnPage,
                    scroll_depth: maxScrollDepth
                }));
            }
        });
    }

    // Public API for tracking custom events
    window.RosyAnalytics = {
        /**
         * Track a custom event
         * @param {string} eventType - Type of event (e.g., 'photo_view', 'download', 'click')
         * @param {string} eventTarget - What was interacted with (e.g., photo filename)
         * @param {object} eventData - Optional extra data
         * @param {number} duration - Optional duration in seconds
         */
        trackEvent: function(eventType, eventTarget, eventData, duration) {
            if (!visitorId) return;

            sendTrack('/event', {
                visitor_id: visitorId,
                page_view_id: pageViewId,
                event_type: eventType,
                event_target: eventTarget,
                event_data: eventData || {},
                duration: duration || 0
            });
        },

        /**
         * Get current visitor ID
         */
        getVisitorId: function() {
            return visitorId;
        },

        /**
         * Get current page view ID
         */
        getPageViewId: function() {
            return pageViewId;
        }
    };

    // Initialize when DOM is ready
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }
})();
