import {Controller} from '@hotwired/stimulus';
import mapboxgl from 'mapbox-gl';
import 'mapbox-gl/dist/mapbox-gl.css';

export default class extends Controller {
    static values = {
        token: String,
        lat: Number,
        lng: Number,
        zoom: { type: Number, default: 15 }
    }

    declare readonly tokenValue: string;
    declare readonly latValue: number;
    declare readonly lngValue: number;
    declare readonly zoomValue: number;

    private map: mapboxgl.Map | null = null;

    connect() {
        if (localStorage.getItem('mapbox-consent') === 'true') {
            this.initMap();
        } else {
            window.addEventListener('mapbox-consent-given', () => {
                this.initMap();
            }, { once: true });
        }
    }

    private initMap() {
        const token = this.tokenValue;
        if (!token || !this.latValue || !this.lngValue || this.map) return;

        mapboxgl.accessToken = token;

        try {
            this.map = new mapboxgl.Map({
                container: this.element as HTMLElement,
                style: 'mapbox://styles/mapbox/streets-v12',
                center: [this.lngValue, this.latValue],
                zoom: this.zoomValue,
                minZoom: 10,
                maxZoom: 18
            });

            new mapboxgl.Marker()
                .setLngLat([this.lngValue, this.latValue])
                .addTo(this.map);

            this.map.on('load', () => {
                this.map?.resize();
            });

            setTimeout(() => {
                this.map?.resize();
            }, 200);
        } catch (e) {
            console.error('Mapbox error:', e);
        }
    }
}
