<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Loading Article...</title>
</head>
<body>
<div id="loader">Loading article...</div>

<script>
(async function () {
    const params = new URLSearchParams(location.search);
    const id = params.get("id") || "";

    // Require an 8-character alphanumeric ID
    if (!/^[a-z0-9]{8}$/i.test(id)) {
        document.getElementById("loader").textContent = "Invalid article ID.";
        return;
    }

    // Get the article slug from the empty query parameter
    const slug = [...params.keys()].find(
        key => key !== "id" && params.get(key) === ""
    ) || "";

    if (!slug) {
        document.getElementById("loader").textContent = "Article slug missing.";
        return;
    }

    try {
        const response = await fetch("/posts.json");
        if (!response.ok) throw new Error("Post list unavailable");

        const posts = await response.json();
        const post = posts.find(item => item.slug === slug);

        if (!post || !post.path) throw new Error("Article not found");

        const articleResponse = await fetch(post.path);
        if (!articleResponse.ok) throw new Error("Article unavailable");

        const html = await articleResponse.text();
        const doc = new DOMParser().parseFromString(html, "text/html");

        const base = doc.createElement("base");
        base.href = new URL(post.path, location.origin).href;
        doc.head.prepend(base);

        document.open();
        document.write("<!DOCTYPE html>\n" + doc.documentElement.outerHTML);
        document.close();

    } catch (error) {
        document.getElementById("loader").textContent = error.message;
    }
})();
</script>
</body>
</html>