"use client";

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

interface PortRouteMapProps {
  portA: { lat: number; lng: number };
  portB: { lat: number; lng: number };
  height?: string;
}

// Fix Leaflet marker icons
const DefaultIcon = L.icon({
  iconUrl: "https://unpkg.com/leaflet@1.9.4/dist/images/marker-icon.png",
  shadowUrl: "https://unpkg.com/leaflet@1.9.4/dist/images/marker-shadow.png",
  iconSize: [25, 41],
  iconAnchor: [12, 41],
});
L.Marker.prototype.options.icon = DefaultIcon;

export default function PortRouteMap({ portA, portB, height = "500px" }: PortRouteMapProps) {
  const center = {
    lat: (portA.lat + portB.lat) / 2,
    lng: (portA.lng + portB.lng) / 2,
  };

  const positions: [number, number][] = [
    [portA.lat, portA.lng],
    [portB.lat, portB.lng],
  ];

  return (
    <div style={{ height }}>
      <MapContainer
        center={[center.lat, center.lng]}
        zoom={4}
        style={{ height: "100%", width: "100%" }}
        scrollWheelZoom={false}
      >
        <TileLayer
          url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
          attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
        />

        <Marker position={[portA.lat, portA.lng]} />
        <Marker position={[portB.lat, portB.lng]} />

        <Polyline positions={positions} pathOptions={{ color: "#2563eb", weight: 3, opacity: 0.7 }} />
      </MapContainer>
    </div>
  );
}
