<script lang="ts">
    import { getCachedEntry } from "../api"
    import NotFound from "./NotFound.svelte"

    export let location: LocationStore | undefined = undefined
    export let id: string | null = null

    let loading = true
    let contentEntry: ContentEntry | null = null
    let errorMessage = ""

    const loadContent = async () => {
        loading = true
        errorMessage = ""
        contentEntry = null

        try {
            if (id) {
                contentEntry = await getCachedEntry("content", { _id: id })
            } else if (location?.path) {
                contentEntry = await getCachedEntry("content", {
                    $or: [{ path: location.path }, { "alternativePaths.path": location.path }],
                })
            }
        } catch (error) {
            console.error("Failed to load content", error)
            errorMessage = "Beim Laden der Inhalte ist ein Fehler aufgetreten."
        } finally {
            loading = false
        }
    }

    $: if (location?.path || id) {
        loadContent()
    }
</script>

{#if loading}

{:else}
    <NotFound />
{/if}

<style lang="less">
    .content-loading,
    .content-error,
    .content-article {
        max-width: 920px;
        margin: 4rem auto;
        padding: 0 1.5rem;
    }

    .content-article {
        display: flex;
        flex-direction: column;
        gap: 2rem;

        header {
            display: flex;
            flex-direction: column;
            gap: 0.8rem;

            h1 {
                font-size: clamp(2.2rem, 4vw, 3.2rem);
                margin: 0;
            }

            .lead {
                font-size: 1.1rem;
                color: rgba(0, 0, 0, 0.7);
            }
        }

        .content-debug {
            background: rgba(0, 0, 0, 0.04);
            border-radius: 12px;
            padding: 1.5rem;

            pre {
                margin: 0;
                white-space: pre-wrap;
                word-break: break-word;
            }
        }
    }
</style>
