import mapConfig from '@/config/mapConfig';
import { parseMapCoordinates } from '@/utils/mapCoordinates';

/* ============================================================================
   STATIC MAP URL — a single, non-interactive thumbnail of a creation's place
   of origin, used as the preview image on the map teaser card. It mirrors the
   live Google map (same custom style from mapConfig) so the still and the modal
   read as the same place, just frozen vs. interactive.
   ========================================================================== */

const MARKER_COLOR = '0x3b3f58'; // mma-blue — same accent the pin uses elsewhere

/* mapConfig.styles speaks the JS Maps API dialect (arrays of styler objects);
   the Static Maps API wants flat `feature:…|element:…|rule:value` segments.
   Hex colours also switch from `#RRGGBB` to `0xRRGGBB`. */
function styleToParams(): string[] {
  return mapConfig.styles.map((entry) => {
    const segments: string[] = [];
    if (entry.featureType) segments.push(`feature:${entry.featureType}`);
    if (entry.elementType) segments.push(`element:${entry.elementType}`);

    for (const styler of entry.stylers ?? []) {
      for (const [rule, value] of Object.entries(styler)) {
        const serialized =
          typeof value === 'string' && value.startsWith('#')
            ? value.replace('#', '0x')
            : String(value);
        segments.push(`${rule}:${serialized}`);
      }
    }

    return `style=${segments.join('|')}`;
  });
}

type BuildStaticMapUrlOptions = {
  coordinates: string | null | undefined;
  /** CSS pixels of the thumbnail; the request uses scale=2 for retina. */
  width?: number;
  height?: number;
  zoom?: number;
};

export function buildStaticMapUrl({
  coordinates,
  width = 400,
  height = 225,
  zoom = 13,
}: BuildStaticMapUrlOptions): string | null {
  const apiKey = process.env.NEXT_PUBLIC_GMAPS_JAVASCRIPT_API_KEY;
  const point = parseMapCoordinates(coordinates);
  if (!apiKey || !point) return null;

  const center = `${point.lat},${point.lng}`;
  const params = [
    `center=${center}`,
    `zoom=${zoom}`,
    // Static Maps caps a single request at 640×640 logical px before scale.
    `size=${Math.min(width, 640)}x${Math.min(height, 640)}`,
    'scale=2',
    `markers=color:${MARKER_COLOR}|${center}`,
    ...styleToParams(),
    `key=${apiKey}`,
  ];

  return `https://maps.googleapis.com/maps/api/staticmap?${params.join('&')}`;
}
