<script>
   import Header from '$lib/navigation/header.svelte'
   import Nav from '$lib/navigation/nav.svelte'
   
   import {onMount} from 'svelte'

   const title = "Public Board"

   async function getHeadcode() {
        return new URLSearchParams(window.location.search).get('station');
    }

    let jsonData = {}; // Extract train data from the object to pass to #each
    let services = [];

    $: {
        if (jsonData && jsonData.GetStationBoardResult && jsonData.GetStationBoardResult.trainServices && jsonData.GetStationBoardResult.trainServices.service) {
            services = [...jsonData.GetStationBoardResult.trainServices.service];
        } else {
            services = ["No train services available"];
        }
    }

    onMount(async () => {
        const station = await getHeadcode();
        document.getElementById('station').textContent = station;
        const data = await fetch(`https://owlboard.info/api/v1/ldb/${station}`);
        jsonData = await data.json();
    })

</script>

<Header {title} />

<p>Station: <span id="station"></span></p>
<p>
{#each services as service}
    <span>{service.origin?.location?.locationName || 'Unknown'}</span>
{/each}
</p>
<p>{JSON.stringify(jsonData)}</p>


<Nav />