---
import type { Widget } from "../widgets/types.js";
import { getMenu } from "../menus/index.js";
import { sanitizeHref } from "../utils/url.js";
import PortableText from "./PortableText.astro";
import RecentPosts from "./widgets/RecentPosts.astro";
import Categories from "./widgets/Categories.astro";
import Tags from "./widgets/Tags.astro";
import Search from "./widgets/Search.astro";
import Archives from "./widgets/Archives.astro";

interface Props {
	widget: Widget;
}

const { widget } = Astro.props;

// Component map for core widgets
const componentMap = {
	"core:recent-posts": RecentPosts,
	"core:categories": Categories,
	"core:tags": Tags,
	"core:search": Search,
	"core:archives": Archives,
};

// For menu widgets, get menu data
let menuData = null;
if (widget.type === "menu" && widget.menuName) {
	menuData = await getMenu(widget.menuName);
}

// For component widgets, get the component
let WidgetComponent = null;
if (widget.type === "component" && widget.componentId) {
	WidgetComponent = componentMap[widget.componentId as keyof typeof componentMap];
}
---

<div class="widget" data-widget-id={widget.id} data-widget-type={widget.type}>
	{widget.title && <h3 class="widget__title">{widget.title}</h3>}

	<div class="widget__content">
		{
			widget.type === "content" && widget.content && (
				<PortableText value={widget.content} />
			)
		}

		{
			widget.type === "menu" && menuData && (
				<nav class="widget__menu">
					<ul>
						{menuData.items.map((item) => (
							<li>
								<a href={sanitizeHref(item.url)} title={item.titleAttr || undefined}>
									{item.label}
								</a>
							</li>
						))}
					</ul>
				</nav>
			)
		}

		{
			widget.type === "component" && WidgetComponent && (
				<WidgetComponent {...(widget.componentProps || {})} />
			)
		}
	</div>
</div>
