<?php

/**
 * Google Map Block Template.
 */

$wrapper_attributes = get_block_wrapper_attributes([
  'class' => 'wp-block-orphic-ui-google-map',
  'data-border-width' => $attributes['borderWidth'] ?? 0,
  'data-border-color' => $attributes['borderColor'] ?? '#000000',
  'data-border-radius' => $attributes['borderRadius'] ?? 0
]);

$style_array = [
  '--google-map-border-width' => ($attributes['borderWidth'] ?? 0) . 'px',
  '--google-map-border-color' => $attributes['borderColor'] ?? '#000000',
  '--google-map-border-radius' => ($attributes['borderRadius'] ?? 0) . 'px'
];

// Convert style array to inline CSS string
$style_string = '';
foreach ($style_array as $property => $value) {
  $style_string .= $property . ':' . $value . ';';
}

$zoom = $attributes['zoom'] ?? 12;
$markers = $attributes['markers'] ?? [];
$api_key = get_option(ConstBlockVariable::GOOGLE_MAP_API_KEY) ?? '';

$unique_id = uniqid('map_');
?>

<div <?php echo $wrapper_attributes; ?> style="<?php echo esc_attr($style_string); ?>">
  <?php if (is_admin()): ?>
    <div class="map-placeholder">
      <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
        <path d="M34.5 420.4c-1.6 2.8-2.5 6-2.5 9.3c0 10.2 8.2 18.4 18.4 18.4l411.2 0c10.2 0 18.4-8.2 18.4-18.4c0-3.3-.9-6.4-2.5-9.3L276.5 75.8C272.2 68.5 264.4 64 256 64s-16.2 4.5-20.5 11.8L34.5 420.4z" />
      </svg>
      <?php if (empty($api_key)): ?>
        <h4>Set the API key in the block settings</h4>
      <?php endif; ?>
      <h4>Note: The Google Map preview is only available on the frontend</h4>
    </div>
  <?php return;
  endif; ?>

  <div id="<?php echo esc_attr($unique_id); ?>" class="google-map-container"></div>
</div>

<?php if (!empty($markers)): ?>
  <script>
    (function() {
      async function initMap_<?php echo $unique_id; ?>() {
        const {
          Map
        } = await google.maps.importLibrary("maps");
        const {
          AdvancedMarkerElement
        } = await google.maps.importLibrary("marker");

        const map = new Map(document.getElementById('<?php echo $unique_id; ?>'), {
          zoom: <?php echo esc_js($zoom); ?>,
          center: {
            lat: <?php echo esc_js($markers[0]['latitude']); ?>,
            lng: <?php echo esc_js($markers[0]['longitude']); ?>
          },
          mapId: '<?php echo esc_js($unique_id); ?>'
        });

        <?php foreach ($markers as $index => $marker): ?>
          const marker<?php echo $index; ?> = new AdvancedMarkerElement({
            map,
            position: {
              lat: <?php echo esc_js($marker['latitude']); ?>,
              lng: <?php echo esc_js($marker['longitude']); ?>
            }
          });

          <?php if (!empty($marker['markerUrl'])): ?>
            marker<?php echo $index; ?>.addListener('click', () => {
              window.open('<?php echo esc_js($marker['markerUrl']); ?>', '_blank');
            });
          <?php endif; ?>
        <?php endforeach; ?>
      }

      // Load the Google Maps script only once
      if (!window.googleMapsInitialized) {
        const script = document.createElement('script');
        script.src = `https://maps.googleapis.com/maps/api/js?key=<?php echo esc_js($api_key); ?>&callback=initMaps&loading=async&v=beta`;
        script.async = true;
        document.head.appendChild(script);
        window.googleMapsInitialized = true;
        window.initMapFunctions = [];
      }

      // Add this map's init function to the queue
      window.initMapFunctions = window.initMapFunctions || [];
      window.initMapFunctions.push(initMap_<?php echo $unique_id; ?>);

      // Global callback for when the API is loaded
      if (typeof window.initMaps !== 'function') {
        window.initMaps = async function() {
          for (const initFn of window.initMapFunctions) {
            await initFn();
          }
        };
      }
    })();
  </script>
<?php endif; ?>