import React, { useMemo } from 'react';
import LeafletMapWrapper, { PlaceData } from '@/components/ui/LeafletMapWrapper';
import { MapMarker } from '@/types/trip-ui';

interface MapViewProps {
  markers: MapMarker[];
  center?: { lat: number; lng: number };
  onMarkerClick: (id: string) => void;
  onMarkerHover: (id: string | null) => void;
  hoveredPlaceId: string | null;
  selectedPlaceId: string | null;
}

const MapGradientOverlays: React.FC = () => (
  <>
    <div className="absolute inset-0 pointer-events-none border-l border-border/10 shadow-[inset_20px_0_40px_-20px_rgba(0,0,0,0.1)]" />
    <div className="absolute top-0 left-0 right-0 h-24 bg-gradient-to-b from-background/20 to-transparent pointer-events-none" />
    <div className="absolute bottom-0 left-0 right-0 h-24 bg-gradient-to-t from-background/20 to-transparent pointer-events-none" />
  </>
);

export const MapView: React.FC<MapViewProps> = ({
  markers,
  center,
  onMarkerClick,
  onMarkerHover,
  hoveredPlaceId,
  selectedPlaceId,
}) => {
  // Auto Center Calculation: Calculate average lat/lng from markers
  const computedCenter = useMemo(() => {
    if (!markers || markers.length === 0) return undefined;
    const sumLat = markers.reduce((acc, m) => acc + m.lat, 0);
    const sumLng = markers.reduce((acc, m) => acc + m.lng, 0);
    return {
      lat: sumLat / markers.length,
      lng: sumLng / markers.length,
    };
  }, [markers]);

  // MapMarker → PlaceData Mapping: Transform markers for the map component
  const mappedPlaces = useMemo<PlaceData[]>(() => 
    markers.map(marker => ({
      id: marker.id,
      lat: marker.lat,
      lng: marker.lng,
      title: marker.title
    })), 
    [markers]
  );

  return (
    <div className="w-full h-full relative group">
      <LeafletMapWrapper
        places={mappedPlaces}
        center={center || computedCenter}
        onMarkerClick={onMarkerClick}
        onMarkerHover={onMarkerHover}
        hoveredPlaceId={hoveredPlaceId}
        selectedPlaceId={selectedPlaceId}
        showPolyline={true}
        className="w-full h-full"
      />
      
      <MapGradientOverlays />
    </div>
  );
};
