<?php
/**
 * MapGeo Safety Wrapper
 * Prevents MapGeo plugin from crashing the page in any browser
 * 
 * @package HVAC_Community_Events
 * @since 2.0.0
 */

if (!defined('ABSPATH')) {
    exit;
}

/**
 * Class HVAC_MapGeo_Safety
 * Wraps MapGeo integration with error boundaries and fallbacks
 */
class HVAC_MapGeo_Safety {
    
    /**
     * Instance of this class
     */
    private static $instance = null;
    
    /**
     * Get instance
     */
    public static function get_instance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    /**
     * Constructor
     */
    private function __construct() {
        $this->init_hooks();
    }
    
    /**
     * Initialize hooks
     */
    private function init_hooks() {
        // Add safety wrapper before MapGeo loads
        add_action('wp_enqueue_scripts', array($this, 'add_safety_wrapper'), 4);
        
        // Add error boundaries in footer
        add_action('wp_footer', array($this, 'add_error_boundaries'), 1);
        
        // Filter MapGeo shortcode output
        add_filter('do_shortcode_tag', array($this, 'wrap_mapgeo_shortcode'), 10, 4);
    }
    
    /**
     * Add safety wrapper script
     */
    public function add_safety_wrapper() {
        // Only on find-a-trainer page
        if (!is_page() || get_post_field('post_name') !== 'find-a-trainer') {
            return;
        }
        
        wp_enqueue_script(
            'hvac-mapgeo-safety',
            HVAC_PLUGIN_URL . 'assets/js/mapgeo-safety.js',
            array(),
            HVAC_PLUGIN_VERSION . '.fix2',
            false // Load in head to catch errors early
        );
        
        // Add inline configuration
        wp_add_inline_script('hvac-mapgeo-safety', '
            window.HVAC_MapGeo_Config = {
                maxRetries: 3,
                retryDelay: 2000,
                timeout: 30000,
                fallbackEnabled: true,
                debugMode: ' . (defined('WP_DEBUG') && WP_DEBUG ? 'true' : 'false') . '
            };
        ', 'before');
    }
    
    /**
     * Add error boundaries in footer
     */
    public function add_error_boundaries() {
        // Only on find-a-trainer page
        if (!is_page() || get_post_field('post_name') !== 'find-a-trainer') {
            return;
        }
        
        ?>
        <script type="text/javascript">
        (function() {
            'use strict';
            
            // Global error handler for MapGeo issues
            window.addEventListener('error', function(event) {
                // Check if error is MapGeo related
                if (event.filename && (
                    event.filename.includes('mapgeo') ||
                    event.filename.includes('amcharts') ||
                    event.filename.includes('interactive-geo-maps')
                )) {
                    console.error('[HVAC MapGeo Safety] Caught MapGeo error:', event.message);
                    
                    // Prevent browser error page
                    event.preventDefault();
                    
                    // Show fallback content if available
                    var fallback = document.getElementById('hvac-map-fallback');
                    var mapContainer = document.querySelector('.igm-map-container, [class*="mapgeo"], [id*="map-"]');
                    
                    if (fallback && mapContainer) {
                        // Relaxed safety: Don't hide map on error immediately to allow debugging
                        // mapContainer.style.display = 'none';
                        // fallback.style.display = 'block';
                        console.warn('[HVAC MapGeo Safety] Error detected but keeping map visible for debugging.');
                    }
                    
                    // Log to our error tracking
                    if (window.HVAC_MapGeo_Config && window.HVAC_MapGeo_Config.debugMode) {
                        console.log('[HVAC MapGeo Safety] Activated fallback due to error');
                    }
                    
                    return true;
                }
            });
            
            // Promise rejection handler for async MapGeo issues
            window.addEventListener('unhandledrejection', function(event) {
                if (event.reason && event.reason.toString().includes('MapGeo')) {
                    console.error('[HVAC MapGeo Safety] Caught unhandled MapGeo promise:', event.reason);
                    event.preventDefault();
                }
            });
            
        })();
        </script>
        <?php
    }
    
    /**
     * Wrap MapGeo shortcode output with enhanced error handling and CDN fallback support
     */
    public function wrap_mapgeo_shortcode($output, $tag, $attr, $m) {
        // Check if this is a MapGeo related shortcode
        $mapgeo_shortcodes = apply_filters('hvac_mapgeo_safety_shortcodes', 
            array('mapgeo', 'interactive-geo-maps', 'igm', 'map-widget', 'display-map')
        );
        
        if (!in_array($tag, $mapgeo_shortcodes)) {
            return $output;
        }
        
        // Wrap output with safety container
        $wrapped = '<div class="hvac-mapgeo-wrapper" data-shortcode="' . esc_attr($tag) . '">';
        $wrapped .= $output;
        $wrapped .= '</div>';
        
        // Add enhanced fallback content with better messaging
        $wrapped .= '<div id="hvac-map-fallback" style="display:none;" class="hvac-map-fallback">';
        $wrapped .= '<div class="hvac-fallback-message">';
        $wrapped .= '<div class="hvac-fallback-icon">';
        $wrapped .= '<span class="dashicons dashicons-location-alt"></span>';
        $wrapped .= '</div>';
        $wrapped .= '<h3>Map Temporarily Unavailable</h3>';
        $wrapped .= '<p>The interactive trainer map is currently experiencing connectivity issues.</p>';
        $wrapped .= '<p>You can still browse all available trainers using the directory below.</p>';
        $wrapped .= '<div class="hvac-fallback-actions">';
        $wrapped .= '<button type="button" class="hvac-retry-map button">Try Loading Map Again</button>';
        $wrapped .= '</div>';
        $wrapped .= '</div>';
        
        // Add loading indicator that shows initially
        $wrapped .= '<div id="hvac-map-loading" class="hvac-map-loading" style="display:none;">';
        $wrapped .= '<div class="hvac-loading-spinner"></div>';
        $wrapped .= '<p>Loading interactive trainer map...</p>';
        $wrapped .= '<small>Checking map resources...</small>';
        $wrapped .= '</div>';
        
        $wrapped .= '</div>';
        
        return $wrapped;
    }
}

// Initialize
HVAC_MapGeo_Safety::get_instance();