import type { RenderableTreeNode } from '@markdoc/markdoc';
import type { Sidenote } from '@/lib/types/components';

export function hasComponents(
  renderable: RenderableTreeNode,
  components: string[]
): boolean {
  const renderablestring = JSON.stringify(renderable);
  return components.some((component) => renderablestring.includes(component));
}

export function collectSideNotes(
  node: RenderableTreeNode | RenderableTreeNode[]
): Sidenote[] {
  const sidenotes: Sidenote[] = [];

  function walk(n: any) {
    if (!n) return;
    if (Array.isArray(n)) {
      n.forEach(walk);
    } else if (n.name === 'Sidenote' && n.attributes) {
      sidenotes.push({
        id: n.attributes.id,
        marker: n.attributes.marker,
        content: n.attributes.content,
        type: n.attributes.type || 'default',
      });
    }
    if (n.children) walk(n.children);
  }

  walk(node);
  return sidenotes;
}
