<script lang="ts">
    import StreamPage from './StreamPage.svelte';
    import MetadataEditor from './MetadataEditor.svelte';
    import Player from './Player.svelte';
    import { dev } from '$app/environment';
    import { getStreamContext } from '$lib/streamContext.svelte.ts';
    import * as streamCache from '$lib/streamCache.svelte.ts';

    let { data } = $props();
    const ctx = getStreamContext();
    let playerSrc = $state<string | null>(null);

    // reactivity runs on `stream` and `streamCache.cached` here
    $effect(() => {
        const stream = data.stream;
        ctx.setCurrent(stream);
        playerSrc = null;
        if (streamCache.cached.has(stream.id)) {
            streamCache.getUrl(stream.id).then((url) => {
                playerSrc = url ?? `/media/tracks/${stream.filename}`;
            });
        } else {
            playerSrc = `/media/tracks/${stream.filename}`;
        }
    });
</script>

<div id="streamContainer">
    <div id="streamPage" class="panel">
        {#if dev}
            <MetadataEditor {...data} />
        {/if}
        <StreamPage />
    </div>
    <div id="player">
        {#key playerSrc}
            {#if playerSrc}
                <Player display={true} src={playerSrc} />
            {/if}
        {/key}
    </div>
</div>

<style>
    #streamContainer {
        display: grid;
        grid-template-rows: 1fr auto;
        height: 100%;
        gap: 0.5em;
    }

    #streamPage {
        grid-row: 1 / 2;
        overflow: auto;
        background:
            local url('/assets/result.png') top right / 50% no-repeat,
            rgba(0, 0, 0, 0.8);
    }

    #player {
        grid-row: 2 / 3;
        margin-left: 1px;
        margin-right: 1px;
        height: 100%;
    }

    @media (max-width: 575px) {
        #streamPage {
            background:
                local url('/assets/result.png') top right / 80% no-repeat,
                rgba(0, 0, 0, 0.8);
        }
    }
</style>
