---
import type { MarkdownHeading } from "astro";

import { widgetManager } from "@utils/widget";
import Profile from "@components/sidebar/profile.astro";
import Announcement from "@components/sidebar/announcement.astro";
import Categories from "@components/sidebar/categories.astro";
import Tags from "@components/sidebar/tags.astro";
import Statistics from "@components/sidebar/statistics.astro";
import TOC from "@components/sidebar/toc.astro";


interface Props {
    id?: string;
    class?: string;
    headings?: MarkdownHeading[];
    side: "left" | "right" | "middle";
}

const { id, class: className, headings, side } = Astro.props;

// 获取配置的组件列表（按侧边栏和位置划分）
const topComponents = widgetManager.getComponentsBySideAndPosition(side, "top");
const stickyComponents = widgetManager.getComponentsBySideAndPosition(side, "sticky");

// 组件映射表
const componentMap = {
    profile: Profile,
    announcement: Announcement,
    categories: Categories,
    tags: Tags,
    statistics: Statistics,
    toc: TOC,
};

// 渲染组件的辅助函数
function renderComponent(component: any, index: number) {
    const ComponentToRender =
        componentMap[component.type as keyof typeof componentMap];
    if (!ComponentToRender) return null;

    const componentClass = widgetManager.getComponentClass(component, index, side);
    const componentStyle = widgetManager.getComponentStyle(component, index);

    return {
        Component: ComponentToRender,
        props: {
            class: componentClass,
            style: componentStyle,
            headings: component.type === "toc" ? headings : undefined,
            ...component.customProps,
        },
    };
}
---

<div id={id || "sidebar"} data-side={side} class:list={[className, "w-full h-full"]}>
    <!-- 顶部固定组件区域 -->
    {topComponents.length > 0 && (
        <div class:list={["flex flex-col w-full gap-4", { "mb-4": stickyComponents.length > 0 }]}>
            {topComponents.map((component, index) => {
                const renderData = renderComponent(component, index);
                if (!renderData) return null;

                const { Component, props } = renderData;
                return <Component {...props} side={side} />;
            })}
        </div>
    )}

    <!-- 粘性组件区域 -->
    {stickyComponents.length > 0 && (
        <div id="sidebar-sticky" class="flex flex-col w-full gap-4 sticky top-4">
            {stickyComponents.map((component, index) => {
                const renderData = renderComponent(component, index);
                if (!renderData) return null;

                const { Component, props } = renderData;
                return <Component {...props} side={side} />;
            })}
        </div>
    )}
</div>