<script lang="ts">
    import Island from "$lib/islands/island.svelte";
    import { apiGet } from "$lib/scripts/apiFetch";
    import { getCurrentLocation } from "$lib/scripts/getLocation";
    import { location } from "$lib/stores/location";
    import { uuid } from "$lib/stores/uuid";
    import toast from "svelte-french-toast";
    //import { NearestStationResponse } from "@owlboard/ts-types";
    export let variables = {
        title: "Near to Me",
    };

    function turnOnLocation() {
        location.set(true);
        toast("To disable location, go to settings");
    }

    async function getNearestStations() {
        const currLocation = await getCurrentLocation();
        console.debug(`Current Latitude: ${currLocation.latitude}, Current Longitude: ${currLocation.longitude}`);
        const apiPath = `/api/v2/live/station/nearest/${currLocation.latitude}/${currLocation.longitude}`;
        const res = await apiGet(apiPath);
        console.log(res);
        return res as any[];
    }
</script>

<Island {variables}>
    {#if !$location}
        <p>Coming Soon</p>
        <!--
        <br>
        <button on:click={turnOnLocation}>Turn on Location</button>
        -->
    {:else if $location}
        {#await getNearestStations()}
            <p>Fetching Location</p>
        {:then stations}
            <div id="buttons">
                {#each stations as station}
                    <a class="link" href="/ldb?station={station['3ALPHA']}">{station.NLCDESC} - {station.miles}mi</a>
                {/each}
            </div>
        {:catch err}
            <p>Error: {err.message}</p>
        {/await}
    {/if}
</Island>

<style>
    button {
        flex: 1;
        width: 70%;
        min-width: 50px;
        height: 30px;
        margin-top: 10px;
        margin-bottom: 5px;
        border: none;
        border-radius: 20px;
        font-family: urwgothic, "Lucida Sans", "Lucida Sans Regular", "Lucida Grande", "Lucida Sans Unicode", Geneva, Verdana, sans-serif;
        font-size: 16px;
        font-weight: 400;
        text-decoration: none;
        background-color: var(--island-button-color);
        color: var(--island-link-color);
        box-shadow: var(--box-shadow);
    }

    #buttons {
        display: flex;
        flex-wrap: wrap;
        justify-content: center;
        align-items: center;
        width: 95%;
        margin: auto;
        padding-top: 5px;
    }
    .link {
        display: inline-flex;
        margin: 5px;
        border: none;
        border-radius: 20px;
        padding: 5px 10px;
        font-family: urwgothic, "Lucida Sans", "Lucida Sans Regular", "Lucida Grande", "Lucida Sans Unicode", Geneva, Verdana, sans-serif;
        font-size: 16px;
        font-weight: 400;
        text-decoration: none;
        background-color: var(--island-button-color);
        color: var(--island-link-color);
        box-shadow: var(--box-shadow);
        white-space: nowrap;
    }
</style>
