'use client';

import { useEffect } from 'react';

import { useLocale } from 'next-intl';

import {
  APIProvider,
  Map as GoogleMap,
  type MapMouseEvent,
  Marker,
  useMap,
} from '@vis.gl/react-google-maps';

import { HOMEPAGE_MAP_CARPATHIAN_BASIN_INITIAL_VIEW } from '@/components/home/blocks/homepageMapShowcaseConfig';

import { GameSpinner } from './GameStage';

export type LatLng = { lat: number; lng: number };
export type HintArea = { center: LatLng; radiusKm: number };

interface GuessMapProps {
  guess: LatLng | null;
  /** Set once the round is revealed. */
  answer: LatLng | null;
  /** Changes with every round, so the view goes back to the whole basin. */
  roundKey: string;
  /** A circle around the answer, shown as the strongest hint. */
  hintArea: HintArea | null;
  onGuess: (position: LatLng) => void;
}

// One step further out than the homepage map, so the whole country fits the minimap.
const INITIAL_VIEW = {
  center: HOMEPAGE_MAP_CARPATHIAN_BASIN_INITIAL_VIEW.center,
  zoom: HOMEPAGE_MAP_CARPATHIAN_BASIN_INITIAL_VIEW.zoom - 1,
};
// On reveal the minimap grows to fill the stage; fit the view once it has.
const REVEAL_FIT_DELAY_MS = 550;
// On a tall map the result card covers its lower part.
const TALL_MAP_PX = 500;
const pinIconUrl = '/assets/images/icons/map-pin.svg';

// Muted base map that keeps the place names, which are the clues.
const MAP_STYLES: google.maps.MapTypeStyle[] = [
  { stylers: [{ saturation: -80 }] },
  { featureType: 'poi', stylers: [{ visibility: 'off' }] },
  { featureType: 'transit', stylers: [{ visibility: 'off' }] },
  { featureType: 'road', elementType: 'labels', stylers: [{ visibility: 'off' }] },
];

/** Resets the view per round and, on reveal, joins the guess to the answer and fits both. */
function RevealController({
  guess,
  answer,
  roundKey,
}: Pick<GuessMapProps, 'guess' | 'answer' | 'roundKey'>) {
  const map = useMap();

  useEffect(() => {
    if (!map) return;
    map.panTo(INITIAL_VIEW.center);
    map.setZoom(INITIAL_VIEW.zoom);
  }, [map, roundKey]);

  useEffect(() => {
    if (!map || !guess || !answer) return;

    const line = new google.maps.Polyline({
      map,
      path: [guess, answer],
      strokeOpacity: 0,
      icons: [
        {
          icon: { path: 'M 0,-1 0,1', strokeOpacity: 1, strokeColor: '#151720', scale: 3 },
          offset: '0',
          repeat: '14px',
        },
      ],
    });

    const timer = window.setTimeout(() => {
      const bounds = new google.maps.LatLngBounds();
      bounds.extend(guess);
      bounds.extend(answer);
      const tall = map.getDiv().clientHeight > TALL_MAP_PX;
      map.fitBounds(bounds, tall ? { top: 96, right: 96, bottom: 280, left: 96 } : 48);
      // Guesses right on the spot would otherwise zoom in to street level.
      google.maps.event.addListenerOnce(map, 'idle', () => {
        if ((map.getZoom() ?? 0) > 12) map.setZoom(12);
      });
    }, REVEAL_FIT_DELAY_MS);

    return () => {
      window.clearTimeout(timer);
      line.setMap(null);
    };
  }, [map, guess, answer]);

  return null;
}

/** Draws the hint circle and zooms to it once it appears. */
function HintAreaLayer({ hintArea }: { hintArea: HintArea | null }) {
  const map = useMap();

  useEffect(() => {
    if (!map || !hintArea) return;
    const circle = new google.maps.Circle({
      map,
      center: hintArea.center,
      radius: hintArea.radiusKm * 1000,
      // Clicks must reach the map, so a guess can be placed inside the circle.
      clickable: false,
      strokeColor: '#151720',
      strokeOpacity: 0.7,
      strokeWeight: 2,
      fillColor: '#dfcf6f',
      fillOpacity: 0.25,
    });
    const bounds = circle.getBounds();
    if (bounds) map.fitBounds(bounds, 24);
    return () => circle.setMap(null);
  }, [map, hintArea]);

  return null;
}

export default function GuessMap({ guess, answer, roundKey, hintArea, onGuess }: GuessMapProps) {
  const locale = useLocale();
  const apiKey = process.env.NEXT_PUBLIC_GMAPS_JAVASCRIPT_API_KEY || '';

  if (!apiKey) {
    return (
      <div className="flex h-full w-full items-center justify-center text-sm text-[#9f1239]">
        A térkép átmenetileg nem elérhető.
      </div>
    );
  }

  const handleClick = (event: MapMouseEvent) => {
    if (answer || !event.detail.latLng) return;
    onGuess(event.detail.latLng);
  };

  return (
    <div className="relative h-full w-full bg-[#151720]">
      {/* Under the map: seen only until Google Maps has drawn its tiles over it. */}
      <div className="absolute inset-0 flex items-center justify-center">
        <GameSpinner label="A térkép betöltése…" />
      </div>
      <APIProvider apiKey={apiKey} language={locale} region={locale === 'hu' ? 'HU' : 'EN'}>
        <GoogleMap
          defaultCenter={INITIAL_VIEW.center}
          defaultZoom={INITIAL_VIEW.zoom}
          minZoom={5}
          maxZoom={16}
          mapTypeId="roadmap"
          styles={MAP_STYLES}
          gestureHandling="greedy"
          disableDefaultUI
          zoomControl
          clickableIcons={false}
          draggableCursor={answer ? undefined : 'crosshair'}
          onClick={handleClick}
          className="h-full w-full"
        >
          <RevealController guess={guess} answer={answer} roundKey={roundKey} />
          <HintAreaLayer hintArea={hintArea} />
          {guess ? (
            <Marker
              position={guess}
              zIndex={20}
              icon={{
                path: google.maps.SymbolPath.CIRCLE,
                fillColor: '#dfcf6f',
                fillOpacity: 1,
                strokeColor: '#151720',
                strokeWeight: 3,
                scale: 9,
              }}
            />
          ) : null}
          {answer ? (
            <Marker
              position={answer}
              zIndex={30}
              icon={{
                url: pinIconUrl,
                scaledSize: new google.maps.Size(38, 50),
                anchor: new google.maps.Point(19, 50),
              }}
            />
          ) : null}
        </GoogleMap>
      </APIProvider>
    </div>
  );
}
