---
import { Icon } from "astro-icon/components";
import { render } from "astro:content";
import type { CollectionEntry } from "astro:content";
import dayjs from "dayjs";
import utc from "dayjs/plugin/utc";

import { siteConfig, profileConfig, postConfig } from "@/config";
import { getSortedPosts } from "@utils/content";
import { formatDateToYYYYMMDD } from "@utils/date";
import { getFileDirFromPath, getPostUrl, getPostUrlBySlug, removeFileExtension} from "@utils/url";
import { i18n } from "@i18n/translation";
import I18nKey from "@i18n/i18nKey";
import License from "@components/post/license.astro";
import Markdown from "@components/common/markdown.astro";
import ImageWrapper from "@components/common/imageWrapper.astro";
import Comment from "@components/post/comment.astro";
import PasswordProtection from "@components/common/passwordProtection.astro";
import PostMetadata from "@components/post/postMeta.astro";
import GridLayout from "@layouts/grid.astro";



export async function getStaticPaths() {
    const blogEntries = await getSortedPosts();
    const paths: {
        params: { slug: string };
        props: { entry: CollectionEntry<"posts"> };
    }[] = [];

    for (const entry of blogEntries) {
        // 将 id 转换为 slug（移除扩展名）以匹配路由参数
        const slug = removeFileExtension(entry.id);
        // 为每篇文章创建默认的 slug 路径
        paths.push({
            params: { slug },
            props: { entry },
        });
        // 如果文章有自定义固定链接，也创建对应的路径
        if (entry.data.routeName) {
            // 移除开头的斜杠和结尾的斜杠
            // 同时移除可能的 "posts/" 前缀，避免重复
            let routeName = entry.data.routeName
                .replace(/^\/+/, "")
                .replace(/\/+$/, "");
            if (routeName.startsWith("posts/")) {
                routeName = routeName.replace(/^posts\//, "");
            }
            paths.push({
                params: { slug: routeName },
                props: { entry },
            });
        }
    }

    return paths;
}


const { entry } = Astro.props;
const { Content, headings } = await render(entry);

const { remarkPluginFrontmatter } = await render(entry);

// 处理加密逻辑
let isEncrypted = !!(entry.data.encrypted && entry.data.password);

dayjs.extend(utc);
const lastModified = dayjs(entry.data.updated || entry.data.published)
    .utc()
    .format("YYYY-MM-DDTHH:mm:ss");

const jsonLd = {
    "@context": "https://schema.org",
    "@type": "BlogPosting",
    headline: entry.data.title,
    description: entry.data.description || entry.data.title,
    keywords: entry.data.tags,
    author: {
        "@type": "Person",
        name: profileConfig.name,
        url: Astro.site,
    },
    datePublished: formatDateToYYYYMMDD(entry.data.published),
    inLanguage: entry.data.lang
        ? entry.data.lang.replace("_", "-")
        : siteConfig.lang.replace("_", "-"),
    // TODO include cover image here
};
---

<GridLayout
    banner={entry.data.cover}
    title={entry.data.title}
    description={entry.data.description}
    lang={entry.data.lang}
    setOGTypeArticle={true}
    postSlug={entry.id}
    headings={headings}
>
    <script
        is:inline
        slot="head"
        type="application/ld+json"
        set:html={JSON.stringify(jsonLd)}
    />
    <div
        class="flex w-full rounded-(--radius-large) overflow-hidden relative mb-4"
    >
        <div
            id="post-container"
            class:list={[
                "card-base z-10 px-6 md:px-9 pt-6 pb-4 relative w-full ",
                {},
            ]}
        >
            <!-- word count and reading time -->
            <div
                class="flex flex-row text-black/30 dark:text-white/30 gap-5 mb-3 transition onload-animation-up"
            >
                <div class="flex flex-row items-center">
                    <div
                        class="transition h-6 w-6 rounded-md bg-black/5 dark:bg-white/10 text-black/50 dark:text-white/50 flex items-center justify-center mr-2"
                    >
                        <Icon name="material-symbols:notes-rounded" />
                    </div>
                    <div class="text-sm">
                        {remarkPluginFrontmatter.words}
                        {" " + i18n(I18nKey.wordsCount)}
                    </div>
                </div>
                <div class="flex flex-row items-center">
                    <div
                        class="transition h-6 w-6 rounded-md bg-black/5 dark:bg-white/10 text-black/50 dark:text-white/50 flex items-center justify-center mr-2"
                    >
                        <Icon
                            name="material-symbols:schedule-outline-rounded"
                        />
                    </div>
                    <div class="text-sm">
                        {remarkPluginFrontmatter.minutes}
                        {
                            " " +
                                i18n(
                                    remarkPluginFrontmatter.minutes === 1
                                        ? I18nKey.minuteCount
                                        : I18nKey.minutesCount,
                                )
                        }
                    </div>
                </div>
            </div>
            <!-- title -->
            <div class="relative onload-animation-up">
                <div
                    data-pagefind-body
                    data-pagefind-weight="10"
                    data-pagefind-meta="title"
                    class="transition w-full block font-bold mb-3
                    text-3xl md:text-[2.25rem]/[2.75rem]
                    text-black/90 dark:text-white/90
                    md:before:w-1 before:h-5 before:rounded-md before:bg-(--primary)
                    before:absolute before:top-3 before:-left-4.5"
                >
                    {entry.data.title}
                </div>
            </div>
            <!-- metadata -->
            <div class="onload-animation-up">
                <PostMetadata
                    className="mb-5"
                    published={entry.data.published}
                    updated={entry.data.updated}
                    tags={entry.data.tags}
                    category={entry.data.category}
                    postUrl={getPostUrl(entry)}
                />
                {
                    (!entry.data.cover || (entry.data.cover && !postConfig.showCoverInContent)) && (
                        <div class="mt-4 border-(--line-divider) border-dashed border-b mb-5" />
                    )
                }
            </div>
            <!-- always show cover as long as it has one -->
            {
                entry.data.cover && postConfig.showCoverInContent && (
                    <>
                        <div class="mt-4" />
                        <ImageWrapper
                            id="post-cover"
                            src={entry.data.cover}
                            basePath={getFileDirFromPath(entry.filePath || '')}
                            class="mb-8 rounded-xl banner-container onload-animation-up"
                            loading="lazy"
                        />
                    </>
                )
            }
            <PasswordProtection
                isEncrypted={isEncrypted}
                password={entry.data.password}
            >
                <Markdown class="mb-6 markdown-content onload-animation-up">
                    <Content />
                </Markdown>
                {
                    postConfig.license.enable && (
                        <License
                            title={entry.data.title}
                            id={entry.id}
                            pubDate={entry.data.published}
                            author={entry.data.author}
                            sourceLink={entry.data.sourceLink}
                            licenseName={entry.data.licenseName}
                            licenseUrl={entry.data.licenseUrl}
                            postUrl={getPostUrl(entry)}
                            class="mb-6 rounded-xl license-container onload-animation-up"
                        />
                    )
                }
            </PasswordProtection>
        </div>
    </div>
    <!-- 评论 -->
    <Comment post={entry} />
    {postConfig.showLastModified && (
        <>
            <div
                id="last-modified"
                data-last-modified={lastModified}
                data-prefix={i18n(I18nKey.lastModifiedPrefix)}
                data-year={i18n(I18nKey.year)}
                data-month={i18n(I18nKey.month)}
                data-day={i18n(I18nKey.day)}
                data-hour={i18n(I18nKey.hour)}
                data-minute={i18n(I18nKey.minute)}
                data-second={i18n(I18nKey.second)}
                style="display: none;"
            ></div>

            <div class="card-base p-6 mb-4">
                <script is:inline>
                    function runtime() {
                        const lastModifiedElement = document.getElementById('last-modified');
                        if (!lastModifiedElement) return;
                        const startDate = new Date(lastModifiedElement.dataset.lastModified);
                        const currentDate = new Date();
                        const diff = currentDate - startDate;
                        const seconds = Math.floor(diff / 1000);
                        const days = Math.floor(seconds / 86400);
                        const hours = Math.floor((seconds % 86400) / 3600);
                        const minutes = Math.floor((seconds % 3600) / 60);
                        const secs = seconds % 60;
                        const years = Math.floor(days / 365);
                        const months = Math.floor((days % 365) / 30);
                        const remainingDays = days % 30;
                        const prefix = lastModifiedElement.dataset.prefix;
                        const yearKey = lastModifiedElement.dataset.year;
                        const monthKey = lastModifiedElement.dataset.month;
                        const dayKey = lastModifiedElement.dataset.day;
                        const hourKey = lastModifiedElement.dataset.hour;
                        const minuteKey = lastModifiedElement.dataset.minute;
                        const secondKey = lastModifiedElement.dataset.second;
                        let runtimeString = prefix + ' ';
                        if (years > 0) {
                            runtimeString += `${years} ${yearKey} `;
                        }
                        if (months > 0) {
                            runtimeString += `${months} ${monthKey} `;
                        }
                        if (remainingDays > 0) {
                            runtimeString += `${remainingDays} ${dayKey} `;
                        }
                        runtimeString += `${hours} ${hourKey} `;
                        if (minutes < 10) {
                            runtimeString += `0${minutes} ${minuteKey} `;
                        } else {
                            runtimeString += `${minutes} ${minuteKey} `;
                        }
                        if (secs < 10) {
                            runtimeString += `0${secs} ${secondKey}`;
                        } else {
                            runtimeString += `${secs} ${secondKey}`;
                        }
                        document.getElementById("modifiedtime").innerHTML = runtimeString;
                    }
                    setInterval(runtime, 1000);
                </script>
                <div class="card-base p-1 mb-0.1">
                    <div class="flex items-center gap-2">
                        <div class="transition h-9 w-9 rounded-lg overflow-hidden relative flex items-center justify-center mr-0">
                            <Icon
                                name="material-symbols:history-rounded"
                                class="text-4xl text-(--primary) transition-transform group-hover:translate-x-0.5 bg-(--enter-btn-bg) p-2 rounded-md"
                            />
                        </div>
                        <div class="flex flex-col gap-0.1">
                            <div id="modifiedtime" class="text-[1.0rem] leading-tight text-black/75 dark:text-white/75"></div>
                            <p class="text-[0.8rem] leading-tight text-black/75 dark:text-white/75">
                                {i18n(I18nKey.lastModifiedOutdated)}
                            </p>
                        </div>
                    </div>
                </div>
            </div>
        </>
    )}
    <div
        class="flex flex-col md:flex-row justify-between mb-4 gap-4 overflow-hidden w-full"
    >
        <a
            href={entry.data.nextSlug
                ? getPostUrlBySlug(entry.data.nextSlug)
                : "#"}
            class:list={[
                "w-full font-bold overflow-hidden active:scale-95",
                { "pointer-events-none": !entry.data.nextSlug },
            ]}
        >
            {
                entry.data.nextSlug && (
                    <div class="btn-card rounded-2xl w-full h-15 max-w-full px-4 flex items-center justify-start! gap-4">
                        <Icon
                            name="material-symbols:chevron-left-rounded"
                            class="text-[2rem] text-(--primary)"
                        />
                        <div class="overflow-hidden transition text-ellipsis whitespace-nowrap max-w-[calc(100%-3rem)] text-black/75 dark:text-white/75">
                            {entry.data.nextTitle}
                        </div>
                    </div>
                )
            }
        </a>
        <a
            href={entry.data.prevSlug
                ? getPostUrlBySlug(entry.data.prevSlug)
                : "#"}
            class:list={[
                "w-full font-bold overflow-hidden active:scale-95",
                { "pointer-events-none": !entry.data.prevSlug },
            ]}
        >
            {
                entry.data.prevSlug && (
                    <div class="btn-card rounded-2xl w-full h-15 max-w-full px-4 flex items-center justify-end! gap-4">
                        <div class="overflow-hidden transition text-ellipsis whitespace-nowrap max-w-[calc(100%-3rem)] text-black/75 dark:text-white/75">
                            {entry.data.prevTitle}
                        </div>
                        <Icon
                            name="material-symbols:chevron-right-rounded"
                            class="text-[2rem] text-(--primary)"
                        />
                    </div>
                )
            }
        </a>
    </div>
</GridLayout>