<template>
    <main class="splash">
        <svg-wordmark />

        <div class="content">
            <strapi-blocks v-if="content" :content="content" />
        </div>

        <a :href="downloadUrl" download>
            <btn :disabled="loading">
                {{ loading ? 'Checking for updates…' : `Download for ${os}` }}
            </btn>
        </a>
    </main>
</template>

<script setup>
import { StrapiBlocks } from 'vue-strapi-blocks-renderer'
import { ref, computed, onMounted } from 'vue'
import SvgWordmark from '@/components/svg/Wordmark.vue'
import useDetectOS from '@/composables/useDetectOS'
import Btn from '@/components/Btn.vue'
import { useData } from 'vike-vue/useData'

const BASE_URL = 'https://s3.takerofnotes.com'

const { os } = useDetectOS()
const { data } = useData()

const version = ref(null)
const downloadPath = ref(null)
const loading = ref(true)

const downloadUrl = computed(() => {
    if (!downloadPath.value || os.value === 'Unknown') return null
    return `${BASE_URL}/dist/${os.value.toLowerCase()}/${version.value}/${downloadPath.value}`
})
const content = computed(() => data?.content)

onMounted(async () => {
    try {
        const response = await fetch(
            `${BASE_URL}/dist/latest-${os.value.toLowerCase()}.yml`,
        )
        if (!response.ok) throw new Error(response.statusText)
        const yaml = await response.text()

        const versionMatch = yaml.match(/^version:\s*(.+)/m)
        const pathMatch = yaml.match(/^path:\s*(.+)/m)

        if (versionMatch) version.value = versionMatch[1].trim()
        if (pathMatch) downloadPath.value = pathMatch[1].trim()
    } catch {
        // fallback to placeholder
        // downloadPath.value = `takerofnotes-app-0.2.0.${os.value === 'Windows' ? 'exe' : os.value === 'macOS' ? 'dmg' : 'AppImage'}`
        console.error('Failed to fetch latest version info')
    } finally {
        loading.value = false
    }
})
</script>

<style lang="scss">
main.splash {
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    gap: desktop-vw(40px);

    .svg-wordmark {
        width: 70%;
        height: auto;
        display: block;
    }

    .content {
        margin: var(--layout-margin);

        p {
            max-width: desktop-vw(500px);
        }
    }
}
</style>
