---
import { Icon } from "astro-icon/components";

import { getCategoryUrl, getTagUrl, url } from "@utils/url";
import { formatDateToYYYYMMDD } from "@utils/date";
import { umamiConfig } from '@/config';
import { i18n } from "@i18n/translation";
import I18nKey from "@i18n/i18nKey";


export interface Props {
    published: Date;
    updated?: Date;
    category?: string | null;
    tags?: string[];
    hideUpdateDate?: boolean;
    hideTagsForMobile?: boolean;
    isHome?: boolean;
    className?: string;
    slug?: string;
    postUrl?: string;
}

const {
    published,
    updated,
    category,
    tags,
    hideUpdateDate,
    hideTagsForMobile,
    isHome,
    className = "",
    slug,
    postUrl
} = Astro.props;
const finalPostUrl = postUrl || (slug ? url(`/posts/${slug}/`) : "");

// 解析 umami
const umamiEnabled = umamiConfig.enabled || false;
const umamiWebsiteId = umamiConfig.scripts.match(/data-website-id="([^"]+)"/)?.[1] || "";
const umamiApiKey = umamiConfig.apiKey || "";
const umamiBaseUrl = umamiConfig.baseUrl || "";
---

<div class:list={["flex flex-wrap text-neutral-500 dark:text-neutral-400 items-center gap-x-4 gap-y-2", className]}>
    <!-- publish date -->
    <div class="flex items-center">
        <div class="meta-icon">
            <Icon name="material-symbols:calendar-today-outline-rounded" class="text-xl"></Icon>
        </div>
        <span class="text-50 text-sm font-medium">{formatDateToYYYYMMDD(published)}</span>
    </div>
    <!-- update date -->
    {!hideUpdateDate && updated && updated.getTime() !== published.getTime() && (
        <div class="flex items-center">
            <div class="meta-icon">
                <Icon name="material-symbols:edit-calendar-outline-rounded" class="text-xl"></Icon>
            </div>
            <span class="text-50 text-sm font-medium">{formatDateToYYYYMMDD(updated)}</span>
        </div>
    )}
    <!-- categories -->
    <div class="flex items-center">
        <div class="meta-icon">
            <Icon name="material-symbols:book-2-outline-rounded" class="text-xl"></Icon>
        </div>
        <div class="flex flex-row flex-nowrap items-center">
            <a href={getCategoryUrl(category || null)} aria-label={`View all posts in the ${category} category`}
                class="link-lg transition text-50 text-sm font-medium
                            hover:text-(--primary) dark:hover:text-(--primary) whitespace-nowrap">
                {category || i18n(I18nKey.uncategorized)}
            </a>
        </div>
    </div>
    <!-- tags -->
    <div class:list={["items-center", {"flex": !hideTagsForMobile, "hidden md:flex": hideTagsForMobile}]}>
        <div class="meta-icon">
            <Icon name="material-symbols:tag-rounded" class="text-xl"></Icon>
        </div>
        <div class="flex flex-row flex-nowrap items-center">
            {(tags && tags.length > 0) && tags.map((tag, i) => (
                <div class:list={[{"hidden": i == 0}, "mx-1.5 text-(--meta-divider) text-sm"]}>/</div>
                <a href={getTagUrl(tag)} aria-label={`View all posts with the ${tag.trim()} tag`}
                    class="link-lg transition text-50 text-sm font-medium
                                hover:text-(--primary) dark:hover:text-(--primary) whitespace-nowrap">
                    {tag.trim()}
                </a>
            ))}
            {!(tags && tags.length > 0) && <div class="transition text-50 text-sm font-medium">{i18n(I18nKey.noTags)}</div>}
        </div>
    </div>
    <!-- 访问量（首页不显示，且umami.enabled为true时显示） -->
    {!isHome && umamiEnabled && finalPostUrl && (
        <div class="flex items-center page-views-container"
            data-page-url={finalPostUrl}
            data-umami-base-url={umamiBaseUrl}
            data-umami-api-key={umamiApiKey}
            data-umami-website-id={umamiWebsiteId}
            data-i18n-views={i18n(I18nKey.pageViews)}
            data-i18n-visitors={i18n(I18nKey.visitors)}
            data-i18n-error={i18n(I18nKey.statsError)}
        >
            <div class="meta-icon">
                <Icon name="material-symbols:visibility-outline-rounded" class="text-xl"></Icon>
            </div>
            <span class="text-50 text-sm font-medium page-views-display">{i18n(I18nKey.statsLoading)}</span>
        </div>
    )}
</div>

<!-- 只有在非首页且启用umami且有finalPostUrl时才加载脚本 -->
{!isHome && umamiEnabled && finalPostUrl && (
    <script>
        import "@/plugins/umami-share";

        // 客户端统计文案生成函数
        function generateStatsText(pageViews, visitors, i18n_views, i18n_visitors) {
            return `${i18n_views} ${pageViews} · ${i18n_visitors} ${visitors}`;
        }
        // 获取访问量统计
        async function fetchPageViews() {
            const containers = document.querySelectorAll('.page-views-container');
            
            containers.forEach(async (containerElement) => {
                const container = containerElement;
                if (container.hasAttribute('data-processed')) return;
                container.setAttribute('data-processed', 'true');

                const pageUrl = container.getAttribute('data-page-url');
                const umamiBaseUrl = container.getAttribute('data-umami-base-url');
                const umamiApiKey = container.getAttribute('data-umami-api-key');
                const umamiWebsiteId = container.getAttribute('data-umami-website-id');
                const i18n_views = container.getAttribute('data-i18n-views');
                const i18n_visitors = container.getAttribute('data-i18n-visitors');
                const i18n_error = container.getAttribute('data-i18n-error');

                try {
                    // 动态加载 umami-share 插件
                    // 调用全局工具获取特定页面的 Umami 统计数据
                    // @ts-ignore
                    const stats = await window.getUmamiPageStats(umamiBaseUrl, umamiApiKey, umamiWebsiteId, pageUrl);
                    // 从返回的数据中提取页面浏览量和访客数
                    const pageViews = stats.pageviews || 0;
                    const visitors = stats.visitors || 0;
                    // 更新页面上的显示内容
                    const displayElement = container.querySelector('.page-views-display');
                    if (displayElement) {
                        displayElement.textContent = generateStatsText(pageViews, visitors, i18n_views, i18n_visitors);
                    }
                } catch (error) {
                    console.error('Error fetching page views:', error);
                    const displayElement = container.querySelector('.page-views-display');
                    if (displayElement) {
                        displayElement.textContent = i18n_error || null;
                    }
                }
            });
        }
        // 页面加载完成后获取统计数据
        fetchPageViews();
        document.addEventListener('astro:page-load', fetchPageViews);
    </script>
)}