<template>
    <main class="container">
        <div v-if="activeDrop" class="drops theme-dark layout-grid">
            <panel
                :drop="activeDrop"
                :index="activeIndex"
                :previousActive="activeIndex > 0"
                :nextActive="activeIndex < drops.length - 1"
                @previous="onPrevious"
                @next="onNext"
            />

            <div class="drop">
                <iframe :src="activeDrop.src" />
            </div>
        </div>

        <div v-else class="splash theme-light">
            <h1>Braindrops</h1>
            <btn @click="activeIndex = 0">View Drops</btn>
        </div>
    </main>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import Panel from '@/components/Panel.vue'
import { wrapValue } from './libs/math'
import Btn from '@shared/Btn.vue'

const activeIndex = ref(-1)
const drops = ref([])

onMounted(async () => {
    const manifest = await fetch('/manifest.json').then((r) => r.json())

    drops.value = await Promise.all(
        manifest.map(async (name) => {
            // Try to fetch metadata, fallback to basic structure if not found
            try {
                const meta = await fetch(`/drops/${name}/meta.json`).then((r) => r.json())
                return {
                    ...meta,
                    src: `/drops/${name}/index.html`,
                }
            } catch (e) {
                return {
                    name,
                    src: `/drops/${name}/index.html`,
                }
            }
        })
    )
})

const onPrevious = () => {
    console.log(wrapValue(activeIndex.value - 1, 0, drops.value.length - 1))
    activeIndex.value = wrapValue(
        activeIndex.value - 1,
        0,
        drops.value.length - 1,
    )
}
const onNext = () => {
    activeIndex.value = wrapValue(
        activeIndex.value + 1,
        0,
        drops.value.length - 1,
    )
}

const activeDrop = computed(() => drops.value[activeIndex.value])
</script>

<style lang="scss">
.container {
    .splash, .drops {
        background: var(--theme-layout);
        color: var(--theme-fg);
        height: 100vh;
        padding-top: rs(20px);
        padding-bottom: rs(20px);
    }
    .panel {
        grid-column: span 4;
    }
    .drop {
        grid-column: 5 / -1;
        border-radius: rs(10px);
        overflow: hidden;
        position: relative;

        iframe {
            position: absolute;
            inset: 0;
            width: 100%;
            height: 100%;
            border: none;
        }
    }
}
</style>
