import type { CompletionContext, CompletionResult, Completion } from "@codemirror/autocomplete";
import type { MutableRefObject } from "react";
import type { PageMeta } from "@/stores/editorStore";

export function wikiLinkSource(pagesRef: MutableRefObject<PageMeta[]>) {
  return (context: CompletionContext): CompletionResult | null => {
    const match = context.matchBefore(/\[\[[\w-]*/);
    if (!match || (match.from === match.to && !context.explicit)) return null;

    const options: Completion[] = pagesRef.current.map((page) => ({
      label: page.title ?? page.name,
      detail: page.name,
      apply: (view, _completion, from, to) => {
        const title = page.title ?? page.name;
        view.dispatch({
          changes: { from, to, insert: `[${title}\`${page.name}]` },
        });
      },
    }));

    return { from: match.from, options, filter: true };
  };
}
