"use client";

/**
 * Map.ir helpers — جایگزین Google Maps
 * https://help.map.ir / https://support.map.ir/
 */
import maplibregl from "maplibre-gl";

export const MAPIR_STYLE = "https://map.ir/vector/styles/main/mapir-xyz-style.json";
export const MAPIR_REVERSE_URL = "https://map.ir/reverse";
export const MAPIR_SEARCH_URL = "https://map.ir/search/v2/autocomplete";
export const MAPIR_STATIC_URL = "https://map.ir/static";

export function mapIrStyleUrl(apiKey: string) {
  return `${MAPIR_STYLE}?x-api-key=${encodeURIComponent(apiKey)}`;
}

/** شکل‌دهی درست حروف فارسی/عربی روی MapLibre — از public لود می‌شود */
let rtlPluginPromise: Promise<void> | null = null;

export function ensureMapRtlTextPlugin() {
  if (rtlPluginPromise) return rtlPluginPromise;
  rtlPluginPromise = (async () => {
    try {
      const status = maplibregl.getRTLTextPluginStatus?.();
      if (status === "loaded" || status === "requested") return;
      const url = `${typeof window !== "undefined" ? window.location.origin : ""}/mapbox-gl-rtl-text.js`;
      await maplibregl.setRTLTextPlugin(url, false);
    } catch (e) {
      console.warn("RTL text plugin failed", e);
    }
  })();
  return rtlPluginPromise;
}

export function mapIrHeaders(apiKey: string) {
  return {
    "x-api-key": apiKey,
    "Mapir-SDK": "reactjs",
  };
}

/** JWT ناقص (قطع‌شده در varchar) را رد می‌کند */
export function isValidMapIrKey(apiKey?: string) {
  const k = String(apiKey || "").trim();
  if (k.length < 20) return false;
  if (k.startsWith("eyJ")) {
    const parts = k.split(".");
    if (parts.length !== 3 || parts.some((p) => !p)) return false;
  }
  return true;
}

export function mapIrTransformRequest(apiKey: string) {
  return (url: string) => ({
    url,
    headers: mapIrHeaders(apiKey),
  });
}

export async function mapIrReverseGeocode(
  location: { lat: number; lng: number },
  _apiKey?: string
) {
  if (location?.lat == null || location?.lng == null) return "";
  try {
    // پروکسی همان‌origin تا CORS بلاک نکند
    const res = await fetch(`/api/map-reverse?lat=${location.lat}&lon=${location.lng}`, {
      cache: "no-store",
    });
    if (!res.ok) return "";
    const data = await res.json();
    return data?.address || "";
  } catch {
    return "";
  }
}

export type MapIrSearchItem = {
  id: string;
  title: string;
  address: string;
  lat: number;
  lng: number;
};

function normalizeSearchItems(data: any, text: string): MapIrSearchItem[] {
  const list = Array.isArray(data) ? data : data?.value || data?.data || [];
  return list
    .map((item: Record<string, any>, i: number) => {
      const geom = item?.geom?.coordinates || item?.geometry?.coordinates;
      const lngLat = Array.isArray(geom) ? { lng: geom[0], lat: geom[1] } : null;
      return {
        id: String(item?.id || item?.place_id || `${item?.title || text}-${i}`),
        title: item?.title || item?.address || item?.name || text,
        address: item?.address || item?.address_compact || item?.title || "",
        lat: Number(lngLat?.lat ?? item?.geographic?.lat ?? item?.lat),
        lng: Number(lngLat?.lng ?? item?.geographic?.lon ?? item?.lon ?? item?.lng),
      };
    })
    .filter(
      (x: MapIrSearchItem) =>
        Number.isFinite(x.lat) && Number.isFinite(x.lng) && !(x.lat === 0 && x.lng === 0)
    );
}

export async function mapIrSearch(
  text: string,
  _apiKey?: string,
  near?: { lat: number; lng: number }
): Promise<MapIrSearchItem[]> {
  if (!text?.trim()) return [];
  const params = new URLSearchParams({ text: text.trim() });
  if (near?.lat != null && near?.lng != null) {
    params.set("lat", String(near.lat));
    params.set("lon", String(near.lng));
  }
  try {
    // پروکسی همان‌origin — جلوگیری از CORS مرورگر با map.ir
    const res = await fetch(`/api/map-search?${params}`, { cache: "no-store" });
    if (!res.ok) return [];
    return normalizeSearchItems(await res.json(), text);
  } catch {
    return [];
  }
}

export function mapIrStaticUrl({
  lat,
  lng,
  width = 600,
  height = 400,
  zoom = 15,
  apiKey,
}: {
  lat: number;
  lng: number;
  width?: number;
  height?: number;
  zoom?: number;
  apiKey?: string;
}) {
  const params = new URLSearchParams({
    width: String(width),
    height: String(height),
    zoom_level: String(zoom),
    lat: String(lat),
    lon: String(lng),
    markers: `color:red|${lat},${lng}`,
  });
  if (apiKey) params.set("x-api-key", apiKey);
  return `${MAPIR_STATIC_URL}?${params}`;
}
