---
/**
 * EmDash Portable Text wrapper
 *
 * Pre-configured with EmDash's built-in components for images, code blocks,
 * embeds, galleries, tables, etc.
 *
 * In edit mode, renders a TipTap-based inline editor instead of static HTML.
 * The edit metadata is detected automatically from the value — no extra props needed.
 *
 * Plugin block rendering components are auto-merged from plugins that declare
 * a `componentsEntry`. Plugin components are merged between EmDash defaults
 * and user overrides, so users can still override individual block types.
 */
import {
	PortableText as BasePortableText,
	mergeComponents,
	type PortableTextProps,
} from "astro-portabletext";
import { getEditMeta } from "../query.js";
// @ts-ignore - virtual module
import { pluginBlockComponents } from "virtual:emdash/block-components";
import { emdashComponents } from "./index.js";
import InlineEditor from "./InlineEditor.astro";

export interface Props extends Omit<PortableTextProps, "value"> {
	value: PortableTextProps["value"];
}

const { value, components: userComponents, ...rest } = Astro.props;

// Check for edit metadata (attached as non-enumerable property by query functions)
const editMeta = getEditMeta(value);

// Merge: EmDash defaults < Plugin block components < User components
const withPlugins = mergeComponents(emdashComponents, { type: pluginBlockComponents });
const mergedComponents = userComponents
	? mergeComponents(withPlugins, userComponents)
	: withPlugins;
---

{editMeta ? (
	<InlineEditor
		value={value}
		collection={editMeta.collection}
		entryId={editMeta.id}
		field={editMeta.field}
	/>
) : (
	<BasePortableText value={value} components={mergedComponents} {...rest} />
)}
