"use client"

import { useEffect, useRef } from "react"
import { useMap } from "react-map-gl/mapbox"

export interface BaseLayerProps {
    visible?: boolean
    beforeId?: string
}

export default function BaseLayer({ visible = true, beforeId }: BaseLayerProps) {
    const { current: map } = useMap()
    const layersAdded = useRef(false)

    // Find the first symbol layer in the map style to insert layers before it
    const getBeforeLayerId = (): string | undefined => {
        if (!map || !beforeId) return undefined

        if (beforeId) return beforeId

        const layers = map.getStyle().layers
        for (const layer of layers) {
            if (layer.type === "symbol") {
                return layer.id
            }
        }
        return undefined
    }

    return { map, layersAdded, getBeforeLayerId }
}
