"use client";

/**
 * MiniMap — compact Leaflet map (400×320) showing parcel polygon + top POI.
 * Dynamic import of react-leaflet (ssr:false) to avoid SSR breakage.
 * Wraps SiteMap with fixed dimensions for Section 1 layout.
 */

import dynamic from "next/dynamic";
import type { ParcelAnalyzeResponse } from "@/lib/site-finder-api";
import type { ParcelAnalysis } from "@/types/site-finder";
import type { Geometry } from "geojson";

// Lazy-mount to avoid SSR breakage (Leaflet uses window)
const SiteMap = dynamic(
  () =>
    import("@/components/site-finder/SiteMap").then((m) => ({
      default: m.SiteMap,
    })),
  {
    ssr: false,
    loading: () => (
      <div
        style={{
          height: 320,
          background: "var(--bg-card-alt)",
          borderRadius: 12,
          border: "1px solid var(--border-card)",
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
          color: "var(--fg-tertiary)",
          fontSize: 13,
        }}
      >
        Загрузка карты...
      </div>
    ),
  },
);

interface Props {
  data: ParcelAnalyzeResponse;
}

/**
 * Adapts ParcelAnalyzeResponse → ParcelAnalysis shape expected by SiteMap.
 * SiteMap only reads: cad_num, geom_geojson, score_breakdown.
 * Other required fields are filled with safe defaults.
 */
function toSiteMapData(data: ParcelAnalyzeResponse): ParcelAnalysis {
  return {
    cad_num: data.cad_num,
    source: data.source === "cad_building" ? "cad_building" : "cad_quarter",
    geom_geojson: (data.geom_geojson as Geometry) ?? null,
    score_breakdown: data.score_breakdown,
    score: data.score,
    poi_count: data.poi_count,
    competitors: [],
    noise: null,
    air_quality: null,
    wind: null,
    district: data.district ?? null,
  };
}

export function MiniMap({ data }: Props) {
  const adapted = toSiteMapData(data);

  return (
    <div
      style={{
        width: "100%",
        maxWidth: 400,
        height: 320,
        borderRadius: 12,
        overflow: "hidden",
        border: "1px solid var(--border-card)",
        flexShrink: 0,
      }}
    >
      <div style={{ height: 320 }}>
        <SiteMap data={adapted} />
      </div>
    </div>
  );
}
