"use client";

import React, {useEffect, useRef} from 'react';
import 'ol/ol.css';
import Map from 'ol/Map';
import View from 'ol/View';
import TileLayer from 'ol/layer/Tile';
import OSM from 'ol/source/OSM';
import {fromLonLat} from 'ol/proj';

const MapComponent = () => {
    const mapContainer = useRef(null);
    const mapInstance = useRef(null); // 保存地图实例

    useEffect(() => {
        if (!mapContainer.current) return;
        // 确保容器有明确的高度（修复100vh可能为0的问题）
        mapContainer.current.style.height = 'calc(100vh - 2px)'; // 减去边框宽度

        // 创建地图实例
        mapInstance.current = new Map({
            target: mapContainer.current,
            layers: [
                new TileLayer({
                    source: new OSM()
                })
            ],
            view: new View({
                // 正确转换坐标到EPSG:3857
                center: fromLonLat([116.4074, 39.9042]),
                zoom: 4
            })
        });

        // 添加窗口大小变化监听
        const handleResize = () => {
            setTimeout(() => {
                if (mapInstance.current) {
                    mapInstance.current.updateSize();
                }
            }, 100);
        };

        window.addEventListener('resize', handleResize);

        // 组件卸载时清理
        return () => {
            window.removeEventListener('resize', handleResize);
            if (mapInstance.current) {
                mapInstance.current.setTarget(null); // 解除地图与容器的绑定
                mapInstance.current = null;
            }
        };
    }, []);

    return (
        <div
            ref={mapContainer}
            style={{
                width: '100%',
                height: '100vh', // 保留100vh但添加安全计算
                border: '1px solid red',
                boxSizing: 'border-box' // 确保边框不增加额外尺寸
            }}
        />
    );
};

export default MapComponent;