"use client";

import GoogleMapView from "@/components/GoogleMapView";
import NaverMapView from "@/components/NaverMapView";
import { isKoreaCoord, type MapBounds, type FlyTo, type MapViewProps } from "@/components/MapView.types";

export type { MapBounds, FlyTo };

const NAVER_KEY = process.env.NEXT_PUBLIC_NAVER_MAP_CLIENT_ID || "";

/**
 * #363 — 메인 지도 dispatcher.
 * - 키 미설정: GoogleMap (회귀 0)
 * - flyTo 또는 selected 좌표가 KR bbox: NaverMap
 * - 그 외 (해외 + 좌표 추정): GoogleMap
 * - 초기 마운트 시 화면 중심을 추정할 수 없으면 식당 평균 좌표로.
 */
export default function MapView(props: MapViewProps) {
  if (!NAVER_KEY) return <GoogleMapView {...props} />;

  const targetLat = props.flyTo?.lat ?? props.selected?.latitude ?? avgLat(props.restaurants);
  const targetLng = props.flyTo?.lng ?? props.selected?.longitude ?? avgLng(props.restaurants);

  if (targetLat != null && targetLng != null && isKoreaCoord(targetLat, targetLng)) {
    return <NaverMapView {...props} />;
  }
  return <GoogleMapView {...props} />;
}

function avgLat(rs: MapViewProps["restaurants"]): number | null {
  if (!rs.length) return null;
  return rs.reduce((s, r) => s + r.latitude, 0) / rs.length;
}
function avgLng(rs: MapViewProps["restaurants"]): number | null {
  if (!rs.length) return null;
  return rs.reduce((s, r) => s + r.longitude, 0) / rs.length;
}
