// Location Injection Script for Unite WebView
// This script injects location data when popup blocking is enabled

(function() {
    'use strict';
    
    // Skip about:blank / data: / javascript: subframes. YouTube, Gmail, etc.
    // embed many empty iframes that immediately get document.write'd or
    // navigated cross-origin; wiring geolocation hooks into those is a pure
    // waste of cycles on every page load.
    var __href = (location && location.href) ? location.href.toLowerCase() : '';
    var __host = (location && location.host) ? location.host.toLowerCase() : '';
    if (!location || !location.host || __href === 'about:blank' || __href.indexOf('about:') === 0 || __href.indexOf('data:') === 0 || __href.indexOf('javascript:') === 0) {
        return;
    }

    // Keep YouTube pages pristine: avoid mutating navigator.geolocation
    // because YouTube combines JS-surface checks with UA consistency.
    if (/(?:^|\.)(youtube\.com|youtu\.be|youtube-nocookie\.com|ytimg\.com|googlevideo\.com)$/i.test(__host)) {
        return;
    }
    
    // Check if geolocation is already available
    if (!navigator.geolocation) {
        return;
    }
    
    // Store original geolocation methods
    const originalGetCurrentPosition = navigator.geolocation.getCurrentPosition;
    const originalWatchPosition = navigator.geolocation.watchPosition;
    const originalClearWatch = navigator.geolocation.clearWatch;
    
    // Override getCurrentPosition
    navigator.geolocation.getCurrentPosition = function(successCallback, errorCallback, options) {
        // Send message to native code to get current location
        if (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.location) {
            window.webkit.messageHandlers.location.postMessage({
                type: 'getCurrentPosition',
                options: options || {}
            });
            
            // Store callbacks for when native code responds
            window._uniteLocationCallbacks = window._uniteLocationCallbacks || {};
            window._uniteLocationCallbacks.success = successCallback;
            window._uniteLocationCallbacks.error = errorCallback;
        } else {
            // Fallback to original implementation
            originalGetCurrentPosition.call(this, successCallback, errorCallback, options);
        }
    };
    
    // Override watchPosition  
    navigator.geolocation.watchPosition = function(successCallback, errorCallback, options) {
        // Generate a fake watch ID
        const watchId = Math.floor(Math.random() * 1000000);
        
        // Call getCurrentPosition and return the watch ID
        navigator.geolocation.getCurrentPosition(successCallback, errorCallback, options);
        return watchId;
    };
    
    // Override clearWatch
    navigator.geolocation.clearWatch = function(watchId) {
        // No-op since we're not actually watching
    };
    
    // Function to be called by native code when location is available
    window.uniteInjectLocation = function(latitude, longitude, accuracy, timestamp) {
        if (window._uniteLocationCallbacks && window._uniteLocationCallbacks.success) {
            const position = {
                coords: {
                    latitude: latitude,
                    longitude: longitude,
                    accuracy: accuracy || 10,
                    altitude: null,
                    altitudeAccuracy: null,
                    heading: null,
                    speed: null
                },
                timestamp: timestamp || Date.now()
            };
            
            window._uniteLocationCallbacks.success(position);
            
            // Clear callbacks after use
            delete window._uniteLocationCallbacks;
        } else {
        }
    };
    
    // Function to be called by native code when location error occurs
    window.uniteInjectLocationError = function(code, message) {
        if (window._uniteLocationCallbacks && window._uniteLocationCallbacks.error) {
            const error = {
                code: code || 1, // PERMISSION_DENIED = 1, POSITION_UNAVAILABLE = 2, TIMEOUT = 3
                message: message || 'Location access denied'
            };
            
            window._uniteLocationCallbacks.error(error);
            
            // Clear callbacks after use
            delete window._uniteLocationCallbacks;
        } else {
        }
    };
    
    // Test function to verify injection is working
    window.uniteTestLocation = function() {
        navigator.geolocation.getCurrentPosition(
            function(position) {
            },
            function(error) {
            }
        );
    };
    
})();