/**
 * @ai-summary Google Maps utility helpers using AdvancedMarkerElement
 */

import { getGoogleMapsApi } from './maps-loader';
import { Station, MapMarker } from '../types/stations.types';
import { formatDistance } from './distance';

type AdvancedMarker = google.maps.marker.AdvancedMarkerElement;

function createMarkerElement(color: string, label?: string): HTMLElement {
  const marker = document.createElement('div');
  marker.style.width = '24px';
  marker.style.height = '24px';
  marker.style.borderRadius = '50%';
  marker.style.backgroundColor = color;
  marker.style.border = '2px solid #ffffff';
  marker.style.boxShadow = '0 1px 4px rgba(0,0,0,0.4)';
  marker.style.display = 'flex';
  marker.style.alignItems = 'center';
  marker.style.justifyContent = 'center';
  marker.style.color = '#000';
  marker.style.fontSize = '12px';
  marker.style.fontWeight = 'bold';
  marker.style.lineHeight = '1';
  marker.style.transform = 'translate(-50%, -50%)';

  if (label) {
    marker.textContent = label;
  }

  return marker;
}

export function createStationMarker(
  station: Station,
  map: google.maps.Map,
  isSaved: boolean
): AdvancedMarker {
  const maps = getGoogleMapsApi();
  const markerColor = isSaved ? '#FFD700' : '#4285F4';
  const content = createMarkerElement(markerColor, isSaved ? '★' : undefined);

  const marker = new maps.marker.AdvancedMarkerElement({
    position: {
      lat: station.latitude,
      lng: station.longitude
    },
    map,
    title: station.name,
    content
  });

  (marker as any).stationData = station;
  (marker as any).isSaved = isSaved;

  return marker;
}

export function createInfoWindow(
  station: Station,
  isSaved: boolean
): google.maps.InfoWindow {
  const maps = getGoogleMapsApi();
  const distanceText = station.distance
    ? `Distance: ${formatDistance(station.distance)}`
    : '';

  const content = `
    <div style="font-family: Roboto, sans-serif; padding: 8px;">
      <h3 style="margin: 0 0 4px 0; font-size: 16px;">${station.name}</h3>
      <p style="margin: 4px 0; font-size: 12px; color: #666;">${station.address}</p>
      ${
        distanceText
          ? `<p style="margin: 4px 0; font-size: 12px; color: #666;">${distanceText}</p>`
          : ''
      }
      ${
        station.rating
          ? `<p style="margin: 4px 0; font-size: 12px;">Rating: ⭐ ${station.rating.toFixed(
              1
            )}</p>`
          : ''
      }
      <div style="margin-top: 8px;">
        <a href="https://www.google.com/maps/search/${encodeURIComponent(
          station.address
        )}" target="_blank" style="color: #4285F4; text-decoration: none; font-size: 12px; margin-right: 8px;">
          Directions
        </a>
        ${isSaved ? '<span style="color: #FFD700; font-size: 12px;">★ Saved</span>' : ''}
      </div>
    </div>
  `;

  return new maps.InfoWindow({ content });
}

export function fitBoundsToMarkers(
  map: google.maps.Map,
  markers: AdvancedMarker[]
): void {
  if (markers.length === 0) return;

  const maps = getGoogleMapsApi();
  const bounds = new maps.LatLngBounds();

  markers.forEach((marker) => {
    const positionLiteral = marker.position;
    if (!positionLiteral) {
      return;
    }

    const latLng =
      positionLiteral instanceof maps.LatLng
        ? positionLiteral
        : new maps.LatLng(positionLiteral.lat, positionLiteral.lng);
    bounds.extend(latLng);
  });

  map.fitBounds(bounds, { top: 50, right: 50, bottom: 50, left: 50 });
}

export function createCurrentLocationMarker(
  latitude: number,
  longitude: number,
  map: google.maps.Map
): AdvancedMarker {
  const maps = getGoogleMapsApi();
  const content = createMarkerElement('#FF0000');

  return new maps.marker.AdvancedMarkerElement({
    position: { lat: latitude, lng: longitude },
    map,
    title: 'Your Location',
    content
  });
}

export function stationToMapMarker(
  station: Station,
  isSaved: boolean
): MapMarker {
  return {
    placeId: station.placeId,
    name: station.name,
    latitude: station.latitude,
    longitude: station.longitude,
    isSaved,
    distance: station.distance
  };
}
