"use client";

import { useEffect, useMemo } from "react";
import { useNoteTemplatesStore } from "@/stores/note-templates-store";
import { NOTE_TEMPLATES, type NoteTemplate } from "@/lib/notes/note-templates";

// Merges Mindavio's built-in templates with user-created templates published
// to the marketplace, so the quick-start gallery and the marketplace tab see
// the same combined catalog.
export function useNoteTemplates() {
  const { customTemplates, loading, initialized, refetch } = useNoteTemplatesStore();

  useEffect(() => {
    if (!initialized) void refetch();
  }, [initialized, refetch]);

  const allTemplates: NoteTemplate[] = useMemo(
    () => [...NOTE_TEMPLATES, ...customTemplates],
    [customTemplates]
  );

  function getTemplate(id: string | null | undefined): NoteTemplate | null {
    if (!id) return null;
    return allTemplates.find((template) => template.id === id) ?? null;
  }

  return { allTemplates, customTemplates, loading, getTemplate, refetch };
}
