// src/components/LocalMap.jsx
import React, { useEffect, useRef } from 'react';
import { MapContainer, TileLayer, Marker, Popup } from 'react-leaflet';
import 'leaflet/dist/leaflet.css'; // ต้อง import CSS ของ Leaflet ด้วย

// Fix default icon issue with Leaflet and Webpack/Vite
import L from 'leaflet';
import icon from 'leaflet/dist/images/marker-icon.png';
import iconRetina from 'leaflet/dist/images/marker-icon-2x.png';
import shadow from 'leaflet/dist/images/marker-shadow.png';

let DefaultIcon = L.icon({
    iconRetinaUrl: iconRetina,
    iconUrl: icon,
    shadowUrl: shadow,
    iconSize: [25, 41],
    iconAnchor: [12, 41],
    popupAnchor: [1, -34],
    shadowSize: [41, 41]
});
L.Marker.prototype.options.icon = DefaultIcon;

export default function LocalMap({ center, zoom, points, onPointClick }) {
    const mapRef = useRef();

    useEffect(() => {
        if (mapRef.current) {
            mapRef.current.setView(center, zoom);
        }
    }, [center, zoom]);

    return (
        <MapContainer
            center={center}
            zoom={zoom}
            scrollWheelZoom={true} // ให้ซูมด้วย scroll wheel ได้
            className="w-full h-full rounded-lg shadow-lg" // Tailwind classes
            ref={mapRef}
        >
            <TileLayer
                attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
                url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
            />
            {points.map(point => (
                <Marker position={[point.lat, point.lon]} key={point.id} eventHandlers={{ click: () => onPointClick(point) }}>
                    <Popup>
                        <b>{point.name}</b>
                        <br />
                        {point.news && point.news[0]} {/* แสดงข่าวแรก */}
                    </Popup>
                </Marker>
            ))}
        </MapContainer>
    );
}