<?php
/**
 * Interactive Map Shortcode
 * 
 * Usage:
 * [interactive_map background="url-to-image"]
 *   [map_point x="25" y="50" title="Point 1" description="Description 1"]
 *   [map_point x="35" y="60" title="Point 2" description="Description 2"]
 * [/interactive_map]
 */
function bw_interactive_map_shortcode($atts, $content = null) {
    // Prevent execution during REST API calls (which includes Gutenberg saving)
    if (defined('REST_REQUEST') && REST_REQUEST) {
        return '[interactive_map] - Preview not available in editor';
    }
    
    // Also check if this is an AJAX request
    if (wp_doing_ajax()) {
        return '[interactive_map] - Preview not available during AJAX';
    }
    // Extract attributes
    $atts = shortcode_atts(array(
        'background' => '',
        'id' => 'interactive-map-' . mt_rand(1000, 9999),
    ), $atts);
    
    // Start output buffer
    ob_start();
    
    // Add CSS styles
    $styles = "
        <style>
        .bw-interactive-map {
            position: relative;
            margin-bottom: 30px;
        }
        
        .map-container {
            position: relative;
            width: 100%;
        }
        
        .map-background {
            display: block;
            width: 100%;
            height: auto;
        }
        
        .map-points {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
        }
        
        .map-point {
            position: absolute;
            transform: translate(-50%, -50%);
            width: 20px;
            height: 20px;
            cursor: pointer;
            z-index: 1;
        }
        
        .map-marker {
            width: 100%;
            height: 100%;
            transition: transform 0.2s ease;
            /* Default state - minimal pulse */
            animation: softPulse 3s infinite;
        }
        
        /* Soft pulse animation for inactive state */
        @keyframes softPulse {
            0% {
                transform: scale(1);
                opacity: 0.8;
            }
            50% {
                transform: scale(1.05);
                opacity: 1;
            }
            100% {
                transform: scale(1);
                opacity: 0.8;
            }
        }
        
        /* Strong pulse animation for active state */
        @keyframes strongPulse {
            0% {
                transform: scale(1);
                opacity: 1;
            }
            50% {
                transform: scale(1.4);
                opacity: 1;
            }
            100% {
                transform: scale(1);
                opacity: 1;
            }
        }
        
        /* Pulse effect for the outer circle when active */
        @keyframes activeCirclePulse {
            0% {
                r: 9;
                opacity: 0.3;
            }
            50% {
                r: 14;
                opacity: 0.7;
            }
            100% {
                r: 9;
                opacity: 0.3;
            }
        }
        
        /* Active point styling */
        .map-point.active .map-marker {
            animation: strongPulse 1.5s infinite;
            z-index: 10; /* Bring active point to front */
        }
        
        .map-point.active .pulse-circle {
            animation: activeCirclePulse 1.5s infinite;
            fill: #ff7760;
            fill-opacity: 0.3;
        }
        
        /* Add a glow effect for active points */
        .map-point.active {
            filter: drop-shadow(0 0 5px rgba(255, 112, 96, 0.6));
        }
        
        .map-point.active .marker-bg {
            fill: #ff5a46; /* More vibrant color for active state */
        }
        
        /* Hover behavior */
        .map-point:hover .map-marker {
            transform: scale(1.2);
            animation: none; /* Stop pulsing on hover */
        }
        
        .map-tooltip {
            position: absolute;
            bottom: 100%;
            left: 50%;
            transform: translateX(-50%);
            width: 200px;
            padding: 10px;
            background: #fff;
            border-radius: 4px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.2);
            margin-bottom: 10px;
            opacity: 0;
            visibility: hidden;
            transition: opacity 0.3s ease, visibility 0.3s ease;
            z-index: 2;
            text-align: left;
        }
        
        .map-tooltip:after {
            content: '';
            position: absolute;
            top: 100%;
            left: 50%;
            margin-left: -8px;
            border-width: 8px;
            border-style: solid;
            border-color: #fff transparent transparent transparent;
        }
        
        .map-point:hover .map-tooltip,
        .map-point.active .map-tooltip {
            opacity: 1;
            visibility: visible;
        }
        
        .map-tooltip h4 {
            margin: 0 0 5px 0;
            font-size: 16px;
            font-weight: 600;
        }
        
        .map-tooltip .map-description {
            margin: 0;
            font-size: 14px;
            line-height: 1.4;
        }
        
        .map-tooltip .map-description p {
            margin: 0 0 10px 0;
        }
        
        .map-tooltip .map-description p:last-child {
            margin-bottom: 0;
        }
        
        .map-tooltip .map-description a {
            color: #ff7760;
            text-decoration: underline;
        }
        
        .map-tooltip .map-description a:hover {
            text-decoration: none;
        }
        
        @media (max-width: 768px) {
            .map-tooltip {
                width: 150px;
                padding: 8px;
                font-size: 12px;
            }
            
            .map-tooltip h4 {
                font-size: 14px;
            }
            
            .map-point {
                width: 16px;
                height: 16px;
            }
        }
        
        /* Instance specific styles */
        #" . esc_attr($atts['id']) . " .map-marker svg circle.marker-bg {
            fill: #FF7063;
        }
        #" . esc_attr($atts['id']) . " .map-tooltip {
            background-color: #FFFFFF;
            color: #333333;
        }
        #" . esc_attr($atts['id']) . " .map-tooltip:after {
            border-top-color: #FFFFFF;
        }
        </style>
    ";
    
    echo $styles;
    
    // Reset global map points array
    global $bw_map_points;
    $bw_map_points = array();
    
    // Process nested shortcodes first to populate $bw_map_points
    do_shortcode($content);
    
    // Use the points from the global variable
    $points = $bw_map_points;
    
    // Start output buffer
    ob_start();
    
    // Generate HTML for the map
    ?>
    <div id="<?php echo esc_attr($atts['id']); ?>" class="bw-interactive-map">
        <div class="map-container">
            <img src="<?php echo esc_url($atts['background']); ?>" alt="Interactive Map" class="map-background" />
            
            <div class="map-points">
                <?php foreach ($points as $index => $point) : ?>
                    <div class="map-point" style="left: <?php echo esc_attr($point['x']); ?>%; top: <?php echo esc_attr($point['y']); ?>%;" data-index="<?php echo esc_attr($index); ?>">
                        <div class="map-marker">
                            <svg viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg">
                                <!-- Outer pulse circle -->
                                <circle class="pulse-circle" cx="10" cy="10" r="9" fill="#FFFFFF" fill-opacity="0.2" />
                                
                                <!-- Inner white circle -->
                                <circle cx="10" cy="10" r="7" fill="#FFFFFF" fill-opacity="0.75" />
                                <path d="M10,3c3.9,0,7,3.1,7,7s-3.1,7-7,7s-7-3.1-7-7S6.1,3,10,3 M10,2C5.6,2,2,5.6,2,10s3.6,8,8,8s8-3.6,8-8S14.4,2,10,2L10,2z" fill="#FFFFFF" fill-opacity="0.75" />
                                
                                <!-- Colored center -->
                                <circle class="marker-bg" cx="10" cy="10" r="5" fill="#FF7063" />
                                
                                <!-- Cross in the center -->
                                <line x1="6" y1="10" x2="14" y2="10" stroke="#FFFFFF" stroke-width="0.5" />
                                <line x1="10" y1="6" x2="10" y2="14" stroke="#FFFFFF" stroke-width="0.5" />
                            </svg>
                        </div>
                        
                        <?php if (!empty($point['title']) || !empty($point['description'])) : ?>
                            <div class="map-tooltip">
                                <?php if (!empty($point['title'])) : ?>
                                    <h4><?php echo esc_html($point['title']); ?></h4>
                                <?php endif; ?>
                                
                                <?php if (!empty($point['description'])) : ?>
                                    <div class="map-description"><?php echo wp_kses_post($point['description']); ?></div>
                                <?php endif; ?>
                            </div>
                        <?php endif; ?>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
    </div>
    
    <?php
    // Generate a unique ID for this map instance
    $map_id = esc_attr($atts['id']);
    
    // Inline JavaScript specifically for this map instance
    $inline_js = "
        <script>
        (function($) {
            // Wait for the document to be fully ready
            $(document).ready(function() {
                // Make sure map exists
                if ($('#" . $map_id . "').length === 0) {
                    console.log('Map with ID " . $map_id . " not found');
                    return;
                }
                
                // Adjust tooltip positions for edge cases for this specific map
                $('#" . $map_id . " .map-point').each(function() {
                    $(this).on('mouseenter', function() {
                        var \$tooltip = $(this).find('.map-tooltip');
                        if (!\$tooltip.length) return;
                        
                        var tooltipWidth = \$tooltip.outerWidth();
                        var tooltipLeft = \$tooltip.offset().left;
                        var tooltipRight = tooltipLeft + tooltipWidth;
                        var windowWidth = $(window).width();
                        
                        // Reset position
                        \$tooltip.css({
                            'left': '50%',
                            'right': 'auto',
                            'transform': 'translateX(-50%)'
                        });
                        
                        // Check right edge
                        if (tooltipRight > windowWidth) {
                            \$tooltip.css({
                                'left': 'auto',
                                'right': '0',
                                'transform': 'none'
                            });
                        }
                        
                        // Check left edge
                        if (tooltipLeft < 0) {
                            \$tooltip.css({
                                'left': '0',
                                'right': 'auto',
                                'transform': 'none'
                            });
                        }
                    });
                });
                
                // Sequential animation function for this specific map
                function initSequentialAnimation() {
                    var \$points = $('#" . $map_id . " .map-point');
                    var totalPoints = \$points.length;
                    var animationDelay = 3000; // 3 second delay
                    var currentIndex = 0;
                    var animationPaused = false;
                    var animationTimer = null;
                    
                    console.log('Initializing animation for map #" . $map_id . " with ' + totalPoints + ' points');
                    
                    if (totalPoints === 0) return;
                    
                    // Initially hide all tooltips and remove active state
                    \$points.removeClass('active');
                    
                    // Add pause/resume on hover
                    \$points.on('mouseenter', function() {
                        // Pause the animation when user interacts
                        animationPaused = true;
                        clearTimeout(animationTimer);
                    });
                    
                    \$points.on('mouseleave', function() {
                        // Resume animation after a brief delay
                        setTimeout(function() {
                            animationPaused = false;
                            activatePoint(currentIndex);
                        }, 500);
                    });
                    
                    // Function to activate a single point
                    function activatePoint(index) {
                        // If animation is paused, don't proceed
                        if (animationPaused) return;
                        
                        // Clear any existing timer
                        clearTimeout(animationTimer);
                        
                        console.log('Activating point ' + index + ' on map #" . $map_id . "');
                        
                        // Deactivate all points
                        \$points.removeClass('active');
                        
                        // Activate the current point
                        var \$currentPoint = \$points.eq(index);
                        \$currentPoint.addClass('active');
                        
                        // Show tooltip for active point and hide after a short delay
                        var \$tooltip = \$currentPoint.find('.map-tooltip');
                        \$tooltip.css({
                            'opacity': 1,
                            'visibility': 'visible'
                        });
                        
                        // Hide tooltip before moving to next point
                        setTimeout(function() {
                            if (!animationPaused) {
                                \$tooltip.css({
                                    'opacity': '',
                                    'visibility': ''
                                });
                            }
                        }, animationDelay - 500); // Hide 0.5s before next activation
                        
                        // Schedule the next point activation
                        currentIndex = (index + 1) % totalPoints;
                        animationTimer = setTimeout(function() {
                            activatePoint(currentIndex);
                        }, animationDelay);
                    }
                    
                    // Start the animation sequence with a slight delay to ensure DOM is ready
                    setTimeout(function() {
                        activatePoint(0);
                    }, 500);
                }
                
                // Initialize animation with a delay to ensure everything is loaded
                setTimeout(initSequentialAnimation, 1000);
            });
        })(jQuery);
        </script>
    ";
    
    // Add the generic script for all maps
    wp_enqueue_script('jquery');
    
    // Get the buffered content
    $html_output = ob_get_clean();
    
    // Return the HTML with the script appended
    return $html_output . $inline_js;
}
add_shortcode('interactive_map', 'bw_interactive_map_shortcode');

// Helper shortcode for map points with HTML support
function bw_map_point_shortcode($atts, $content = '') {
    // During REST API or AJAX requests, return empty string
    if ((defined('REST_REQUEST') && REST_REQUEST) || wp_doing_ajax()) {
        return '';
    }
    
    // Store in global variable for the parent shortcode to use
    global $bw_map_points;
    if (!is_array($bw_map_points)) {
        $bw_map_points = array();
    }
    
    // Get attributes
    $atts = shortcode_atts(array(
        'x' => '50',
        'y' => '50',
        'title' => '',
        'description' => $content, // Get description from content if available
    ), $atts);
    
    // Add to points array
    $bw_map_points[] = array(
        'x' => $atts['x'],
        'y' => $atts['y'],
        'title' => $atts['title'],
        'description' => !empty($content) ? $content : $atts['description'],
    );
    
    return ''; // Just a marker for the parent shortcode
}
add_shortcode('map_point', 'bw_map_point_shortcode');