---
import type { MarkdownHeading } from "astro";
import Profile from "@/components/content/Profile.astro";
import Advertisement from "@/components/widget/Advertisement.astro";
import Announcement from "@/components/widget/Announcement.astro";
import Calendar from "@/components/widget/Calendar.astro";
import Categories from "@/components/widget/Categories.astro";
import SidebarTOC from "@/components/widget/SidebarTOC.astro";
import SiteStats from "@/components/widget/SiteStats.astro";
import Tags from "@/components/widget/Tags.astro";
import type { WidgetComponentConfig } from "@/types/config";
import { widgetManager } from "@/utils/widget-manager";

interface Props {
	class?: string;
	headings?: MarkdownHeading[];
}

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

// 获取右侧边栏的组件列表
const topComponents = widgetManager.getComponentsByPosition("top", "right");
const stickyComponents = widgetManager.getComponentsByPosition(
	"sticky",
	"right",
);

// 组件类型到ID的映射
const componentTypeToId = {
	stats: "site-stats",
	calendar: "calendar-widget",
	sidebarToc: "sidebar-toc",
	profile: "profile",
	announcement: "announcement",
	categories: "categories",
	tags: "tags",
	advertisement: "advertisement",
};

// 提取客户端需要的数据 - 包含组件的 showOnPostPage 配置
const rightComponentsConfig = widgetManager
	.getConfig()
	.rightComponents.filter((c) => c.enable)
	.map((c) => ({
		id: componentTypeToId[c.type as keyof typeof componentTypeToId],
		showOnPostPage: c.showOnPostPage ?? true, // 默认为 true
	}));

// 组件映射表
const componentMap = {
	profile: Profile,
	announcement: Announcement,
	categories: Categories,
	tags: Tags,
	sidebarToc: SidebarTOC,
	advertisement: Advertisement,
	stats: SiteStats,
	calendar: Calendar,
};

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

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

	return {
		Component: ComponentToRender,
		props: {
			class: componentClass,
			style: componentStyle,
			headings: headings ?? [],
			configId: component.configId,
			showOnPostPage: component.showOnPostPage,
			...component.customProps,
		},
	};
}
---

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

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

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

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

<!-- 响应式样式和JavaScript -->
<style>
  /* 响应式断点样式 */
  @media (max-width: 768px) {
    #right-sidebar {
      display: var(--sidebar-mobile-display, block);
    }
  }

  @media (min-width: 769px) and (max-width: 1024px) {
    #right-sidebar {
      display: var(--sidebar-tablet-display, block);
    }
  }

  @media (min-width: 1025px) {
    #right-sidebar {
      display: var(--sidebar-desktop-display, block);
    }
  }
</style>

<script is:inline define:vars={{ rightComponentsConfig }}>
  // 根据 showOnPostPage 配置控制组件显示
  function toggleComponentsVisibility() {
    const isPostPage = window.location.pathname.includes("/posts/");
    
    // 获取所有右侧边栏组件
    const rightSidebar = document.getElementById('right-sidebar');
    if (!rightSidebar) return;
    
    // 查找所有 widget-layout 元素
    const widgets = rightSidebar.querySelectorAll('widget-layout');
    
    widgets.forEach((widget) => {
      const widgetId = widget.getAttribute('data-id');
      
      // 从配置中查找该组件的 showOnPostPage 设置
      const componentConfig = rightComponentsConfig.find(c => c.id === widgetId);
      
      if (componentConfig) {
        // 特殊处理：侧边栏TOC只在文章详情页显示
        if (widgetId === 'sidebar-toc') {
          widget.style.display = isPostPage ? '' : 'none';
        }
        // 其他组件的 showOnPostPage 含义：
        // true: 在文章页和非文章页都显示（默认行为）
        // false: 只在非文章页显示，文章页隐藏
        else if (isPostPage && !componentConfig.showOnPostPage) {
          // 文章页 且 showOnPostPage 为 false：隐藏
          widget.style.display = 'none';
        } else {
          // 其他情况：显示
          widget.style.display = '';
        }
      }
    });
  }

  // 页面加载时执行
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', toggleComponentsVisibility);
  } else {
    toggleComponentsVisibility();
  }

  // 页面切换时重新检查
  document.addEventListener('swup:contentReplaced', () => {
    setTimeout(toggleComponentsVisibility, 100);
  });
</script>
