"use client"

import { useQuery } from "@tanstack/react-query"
import { apiClient } from "@/lib/api/client"
import type { DocsFontDefinition, DocsFontsResponse } from "@/lib/drive/docs-styles-types"
import { DOCS_FONT_FAMILIES } from "@/lib/drive/docs-font-family"

const FALLBACK_FONTS: DocsFontDefinition[] = DOCS_FONT_FAMILIES.map((font) => ({
  name: font.name,
  stack: font.stack,
  source: "system",
}))

export function useDocsFonts() {
  return useQuery({
    queryKey: ["richtext", "fonts"],
    queryFn: async () => {
      try {
        const res = await apiClient.get<DocsFontsResponse>("/richtext/fonts")
        return res.fonts?.length ? res.fonts : FALLBACK_FONTS
      } catch {
        return FALLBACK_FONTS
      }
    },
    staleTime: 5 * 60_000,
  })
}

export function docsFontStackByName(
  fonts: DocsFontDefinition[],
  name: string
): string {
  return fonts.find((font) => font.name === name)?.stack ?? name
}
