"use client";

import { useEffect } from "react";
import type { AdminFontItem } from "@/components/dashboard/settings/settings-api-types";
import { useGlobalSettings } from "./global-settings-provider";

export function SiteFontLoader() {
  const { settings } = useGlobalSettings();

  useEffect(() => {
    if (!settings?.fonts) return;

    const { primary, secondary, tertiary } = settings.fonts;

    // Remove any existing font styles
    const existingStyle = document.getElementById("global-font-styles");
    if (existingStyle) {
      existingStyle.remove();
    }

    // Create style element for font imports and variables
    const style = document.createElement("style");
    style.id = "global-font-styles";

    let css = "";

    // Add Google Fonts imports if needed
    const fonts = [primary, secondary, tertiary].filter(Boolean) as AdminFontItem[];
    const googleFonts = fonts.filter((f) => f.source === "google" && f.url);

    if (googleFonts.length > 0) {
      const fontUrls = [...new Set(googleFonts.map((f) => f.url))];
      fontUrls.forEach((url) => {
        css += `@import url('${url}');\n`;
      });
    }

    // Drive the dashboard-controlled font variables consumed by globals.css.
    // These are separate from the --font-primary/secondary color tokens.
    // Body uses the primary font; headings use the secondary (falls back to primary).
    css += ":root {\n";
    if (primary) {
      css += `  --app-font-body: '${primary.font_family}', system-ui, sans-serif;\n`;
    }
    const heading = secondary ?? primary;
    if (heading) {
      css += `  --app-font-heading: '${heading.font_family}', system-ui, sans-serif;\n`;
    }
    css += "}\n";

    style.textContent = css;
    document.head.appendChild(style);

    // Cleanup
    return () => {
      if (style.parentNode) {
        style.parentNode.removeChild(style);
      }
    };
  }, [settings?.fonts]);

  return null;
}
