import { useEffect, useMemo, ReactNode } from "react";

export interface PublicPageThemeValues {
  bg_color?: string | null;
  section_bg_color?: string | null;
  text_color?: string | null;
  heading_color?: string | null;
  accent_color?: string | null;
  font_family?: string | null;
  heading_font_family?: string | null;
}

const DEFAULTS = {
  bg: "#FFFFFF",
  section: "#F9FAFB",
  text: "#111827",
  heading: "#0F172A",
  accent: "#2563EB",
  font: "Inter",
  headingFont: "Inter",
};

// A curated set of safe Google Fonts. Falls back to system if not in list.
export const PUBLIC_PAGE_FONTS = [
  "Inter",
  "Roboto",
  "Open Sans",
  "Lato",
  "Montserrat",
  "Poppins",
  "Source Sans 3",
  "Nunito",
  "Raleway",
  "Merriweather",
  "Playfair Display",
  "Lora",
  "PT Serif",
  "Georgia",
  "System UI",
];

function loadGoogleFont(family: string) {
  if (!family) return;
  if (family === "Georgia" || family === "System UI") return;
  const id = `gf-${family.replace(/\s+/g, "-").toLowerCase()}`;
  if (document.getElementById(id)) return;
  const link = document.createElement("link");
  link.id = id;
  link.rel = "stylesheet";
  const fam = family.replace(/\s+/g, "+");
  link.href = `https://fonts.googleapis.com/css2?family=${fam}:wght@400;500;600;700&display=swap`;
  document.head.appendChild(link);
}

export function usePublicPageThemeStyle(theme: PublicPageThemeValues | null | undefined) {
  const bg = theme?.bg_color || DEFAULTS.bg;
  const section = theme?.section_bg_color || DEFAULTS.section;
  const text = theme?.text_color || DEFAULTS.text;
  const heading = theme?.heading_color || DEFAULTS.heading;
  const accent = theme?.accent_color || DEFAULTS.accent;
  const font = theme?.font_family || DEFAULTS.font;
  const headingFont = theme?.heading_font_family || font || DEFAULTS.headingFont;

  useEffect(() => {
    loadGoogleFont(font);
    loadGoogleFont(headingFont);
  }, [font, headingFont]);

  const style = useMemo(
    () =>
      ({
        "--pp-bg": bg,
        "--pp-section": section,
        "--pp-text": text,
        "--pp-heading": heading,
        "--pp-accent": accent,
        "--pp-font": `'${font}', system-ui, -apple-system, sans-serif`,
        "--pp-heading-font": `'${headingFont}', system-ui, -apple-system, sans-serif`,
        backgroundColor: bg,
        color: text,
        fontFamily: `var(--pp-font)`,
      }) as React.CSSProperties,
    [bg, section, text, heading, accent, font, headingFont],
  );

  return { style, bg, section, text, heading, accent, font, headingFont };
}

interface ThemeWrapperProps {
  theme: PublicPageThemeValues | null | undefined;
  className?: string;
  children: ReactNode;
}

/**
 * Wrap a public page with this to apply association branding.
 * Children can use CSS vars: var(--pp-bg) var(--pp-section) var(--pp-text)
 * var(--pp-heading) var(--pp-accent) var(--pp-font) var(--pp-heading-font).
 *
 * Headings (h1-h6) inside automatically use heading font + color.
 */
export function PublicPageThemeWrapper({ theme, className, children }: ThemeWrapperProps) {
  const { style } = usePublicPageThemeStyle(theme);
  return (
    <div className={`public-page-themed ${className || ""}`} style={style}>
      <style>{`
        .public-page-themed h1,
        .public-page-themed h2,
        .public-page-themed h3,
        .public-page-themed h4,
        .public-page-themed h5,
        .public-page-themed h6 {
          font-family: var(--pp-heading-font);
          color: var(--pp-heading);
        }
      `}</style>
      {children}
    </div>
  );
}
