<script>
    // Lead 1: https://codepen.io/edankwan/pen/emqgpr
    // Lead 2: ThreeJS globe: https://github.com/vasturiano/globe.gl
    // Lead 3: https://www.bypeople.com/css-js-webgl-rotating-3d-globe-effect/

    import { onMount } from 'svelte'
    import { locations } from '../store'


    // Props
    export let type = ''

    // Variable
    let mapWidth
    let mapHeight
    let resizeWindow
    let init

    // Get positions from lat/long
    const getPosition = coordinates => {
        if (mapWidth && mapHeight) {
            const x = (coordinates.lng + 180) * (mapWidth / 360)
            const rad = coordinates.lat * Math.PI / 180
            const mercN = Math.log(Math.tan((Math.PI / 4) + (rad / 2)))
            const y = (mapHeight / 2) - (mapWidth * mercN / (2 * Math.PI))

            console.log(coordinates.lng)
            console.log(x, y)
            return { x, y }
        } else {
            return { x: 0, y: 0 }
        }
    }


    /*
    ** Run code on browser only
    */
    onMount(() => {
        // const globe = document.querySelector('.globe img')
        // const places = document.querySelectorAll('.globe .pin--place')

        // // Init function
        // init = () => {
        //     mapWidth = globe.getBoundingClientRect().width
        //     mapHeight = globe.getBoundingClientRect().height

        //     places.forEach(place => {
        //         const coordinates = { lat: place.dataset.lat, lng: place.dataset.lng }
        //         place.style.left = getPosition(coordinates).x + 'px'
        //         place.style.top = getPosition(coordinates).y + 'px'
        //     })
        // }

        // resizeWindow = () => {
        //     mapWidth = globe.offsetWidth
        //     mapHeight = globe.offsetHeight

        //     init()
        // }

        // // init()
    })
</script>

<svelte:window on:resize={resizeWindow} on:load={init} />

<div class="globe" class:globe--part={type === 'part'}>
    <div class="wrap">
        <div class="globe__pins">
            {#if type !== 'part'}
            {#each $locations as location}
            <div class="pin pin--place" data-lat="{location.coordinates.lat}" data-lng="{location.coordinates.lng}">
                <a href="/location/{location.country.slug}/{location.slug}" class="pin__dot" rel="prefetch">
                    <i class="pin__dot"></i>
                </a>
                <a href="/location/{location.country.slug}/{location.slug}" class="pin__name" rel="prefetch">
                    <span>{location.name}</span>
                </a>
            </div>
            {/each}

            <!-- <span class="pin pin--country">France</span> -->
            {/if}
        </div>

        <img src="/img/globe.png" alt="">
    </div>
</div>
