<?php
/**
 * BW Image Hotspot - Shortcodes
 *
 * 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]
 */

// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

/**
 * Interactive Map Shortcode
 */
function bw_hotspot_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 );

    // Reset global map points array
    global $bw_hotspot_map_points;
    $bw_hotspot_map_points = array();

    // Process nested shortcodes first to populate $bw_hotspot_map_points
    do_shortcode( $content );

    // Use the points from the global variable
    $points = $bw_hotspot_map_points;

    // Start output buffer
    ob_start();

    // Instance-specific styles
    ?>
    <style>
        #<?php echo esc_attr( $atts['id'] ); ?> .map-marker svg circle.marker-bg {
            fill: #FF7063;
        }
        #<?php echo esc_attr( $atts['id'] ); ?> .map-tooltip {
            background-color: #FFFFFF;
            color: #333333;
        }
        #<?php echo esc_attr( $atts['id'] ); ?> .map-tooltip:after {
            border-top-color: #FFFFFF;
        }
    </style>

    <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($) {
            $(document).ready(function() {
                if ($('#" . $map_id . "').length === 0) {
                    return;
                }

                // Adjust tooltip positions for edge cases
                $('#" . $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();

                        \$tooltip.css({
                            'left': '50%',
                            'right': 'auto',
                            'transform': 'translateX(-50%)'
                        });

                        if (tooltipRight > windowWidth) {
                            \$tooltip.css({
                                'left': 'auto',
                                'right': '0',
                                'transform': 'none'
                            });
                        }

                        if (tooltipLeft < 0) {
                            \$tooltip.css({
                                'left': '0',
                                'right': 'auto',
                                'transform': 'none'
                            });
                        }
                    });
                });

                // Sequential animation function
                function initSequentialAnimation() {
                    var \$points = $('#" . $map_id . " .map-point');
                    var totalPoints = \$points.length;
                    var animationDelay = 3000;
                    var currentIndex = 0;
                    var animationPaused = false;
                    var animationTimer = null;

                    if (totalPoints === 0) return;

                    \$points.removeClass('active');

                    \$points.on('mouseenter', function() {
                        animationPaused = true;
                        clearTimeout(animationTimer);
                    });

                    \$points.on('mouseleave', function() {
                        setTimeout(function() {
                            animationPaused = false;
                            activatePoint(currentIndex);
                        }, 500);
                    });

                    function activatePoint(index) {
                        if (animationPaused) return;

                        clearTimeout(animationTimer);

                        \$points.removeClass('active');

                        var \$currentPoint = \$points.eq(index);
                        \$currentPoint.addClass('active');

                        var \$tooltip = \$currentPoint.find('.map-tooltip');
                        \$tooltip.css({
                            'opacity': 1,
                            'visibility': 'visible'
                        });

                        setTimeout(function() {
                            if (!animationPaused) {
                                \$tooltip.css({
                                    'opacity': '',
                                    'visibility': ''
                                });
                            }
                        }, animationDelay - 500);

                        currentIndex = (index + 1) % totalPoints;
                        animationTimer = setTimeout(function() {
                            activatePoint(currentIndex);
                        }, animationDelay);
                    }

                    setTimeout(function() {
                        activatePoint(0);
                    }, 500);
                }

                setTimeout(initSequentialAnimation, 1000);
            });
        })(jQuery);
        </script>
    ";

    // Enqueue jQuery
    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_hotspot_interactive_map_shortcode' );

/**
 * Map Point Shortcode
 */
function bw_hotspot_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_hotspot_map_points;
    if ( ! is_array( $bw_hotspot_map_points ) ) {
        $bw_hotspot_map_points = array();
    }

    // Get attributes
    $atts = shortcode_atts( array(
        'x'           => '50',
        'y'           => '50',
        'title'       => '',
        'description' => $content,
    ), $atts );

    // Add to points array
    $bw_hotspot_map_points[] = array(
        'x'           => $atts['x'],
        'y'           => $atts['y'],
        'title'       => $atts['title'],
        'description' => ! empty( $content ) ? $content : $atts['description'],
    );

    return '';
}
add_shortcode( 'map_point', 'bw_hotspot_map_point_shortcode' );
