"use client";

import "leaflet/dist/leaflet.css";
import { MapContainer, Polygon, TileLayer } from "react-leaflet";

import type { GeoJSONPolygon } from "@/types/provider";

import { getBounds, getCenter, toLeafletRings } from "./lib/geo";

/**
 * Read-only map of a provider's coverage polygon.
 *
 * Leaflet + OpenStreetMap: free, no API key, no billing account. This is the
 * ONLY module that imports Leaflet — its parent loads it through `next/dynamic`
 * with `ssr: false`, because Leaflet touches `window` at import time and would
 * crash a server render. Keep that boundary intact when editing.
 *
 * The polygon is styled through a CSS class rather than `pathOptions.color`
 * so it uses the design tokens: CSS rules override the `stroke`/`fill`
 * presentation attributes Leaflet writes onto the SVG path.
 */
export function CoverageMap({ polygon }: { polygon: GeoJSONPolygon }) {
  const rings = toLeafletRings(polygon);
  const bounds = getBounds(polygon);
  const center = getCenter(polygon);

  if (!bounds || !center) return null;

  return (
    <MapContainer
      bounds={bounds}
      boundsOptions={{ padding: [24, 24] }}
      center={center}
      // Trackpad/wheel zoom is off so scrolling the page over the map doesn't
      // hijack the scroll — the +/- control and drag still work.
      scrollWheelZoom={false}
      className="h-[320px] w-full rounded-[12px] sm:h-[420px]"
    >
      <TileLayer
        url="https://tile.openstreetmap.org/{z}/{x}/{y}.png"
        attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
        maxZoom={19}
      />
      <Polygon
        positions={rings}
        pathOptions={{
          className: "fill-primary-blue/20 stroke-primary-blue",
          weight: 2,
        }}
      />
    </MapContainer>
  );
}
