// Font loading with performance optimization
// Feature Registration Pattern implementation

import type { ReaderContext } from "../core/reader-context";

export function init(context: ReaderContext): void {
  const userPreferredFont = localStorage.getItem("reader-font") || "literata";

  context.events.on("reader:loaded", async () => {
    await preloadFonts(userPreferredFont);
  });

  context.events.on("font:change", async (detail: { fontId: string }) => {
    const stack = getFontStack(detail.fontId);
    applyFontStack(stack);
    await preloadFonts(detail.fontId);
  });

  context.events.on("font:get-stack", (detail: { fontId: string }) => {
    const stack = getFontStack(detail.fontId);
    context.events.emit("font:stack-ready", { stack });
  });
}

const READING_FONTS = [
  {
    id: "literata",
    name: "Literata",
    stack: "Literata, serif",
    description: "Designed for Google Play Books",
  },
  {
    id: "crimson",
    name: "Crimson Text",
    stack: "Crimson Text, serif",
    description: "Optimized for screen reading",
  },
  {
    id: "source-serif",
    name: "Source Serif 4",
    stack: "Source Serif 4, serif",
    description: "Professional Adobe quality",
  },
  {
    id: "eb-garamond",
    name: "EB Garamond",
    stack: "EB Garamond, serif",
    description: "Classic elegance",
  },
  {
    id: "libertinus",
    name: "Libertinus Serif",
    stack: "Libertinus Serif, serif",
    description: "Excellent for technical content",
  },
  {
    id: "noto-serif",
    name: "Noto Serif",
    stack: "Noto Serif, serif",
    description: "Maximum language support",
  },
  {
    id: "charis-sil",
    name: "Charis SIL",
    stack: "Charis SIL, serif",
    description: "Multilingual specialist",
  },
  {
    id: "ibm-plex",
    name: "IBM Plex Serif",
    stack: "IBM Plex Serif, serif",
    description: "Modern & versatile",
  },
];

async function preloadFonts(userPreferredFont: string): Promise<void> {
  const fontsToPreload = new Set(["literata", userPreferredFont]);

  for (const fontId of fontsToPreload) {
    const font = READING_FONTS.find((f) => f.id === fontId);
    if (font) {
      document.fonts.load(`16px "${font.stack}"`);
    }
  }
}

function getFontStack(fontId: string): string {
  const font = READING_FONTS.find((f) => f.id === fontId);
  return font?.stack || "Literata, serif";
}

function applyFontStack(stack: string): void {
  document.documentElement.style.setProperty("--reader-font-family", stack);
}

export { READING_FONTS, preloadFonts, getFontStack };