import { createContext, useContext, useEffect, type ReactNode } from "react";
import { useQuery } from "@tanstack/react-query";
import { useServerFn } from "@tanstack/react-start";
import { getSiteConfig } from "@/lib/games.functions";

export type SiteTheme = {
  accent?: string;
  neon?: string;
  bg?: string;
  surface?: string;
};

export type SiteContextValue = {
  slug: string;
  name: string;
  tagline: string | null;
  meta_title: string | null;
  meta_description: string | null;
  logo_primary: string;
  logo_accent: string;
  theme: SiteTheme;
  gameCount: number;
};

const SiteCtx = createContext<SiteContextValue | null>(null);

const DEFAULT_SITE: SiteContextValue = {
  slug: "main",
  name: "GameOrbit",
  tagline: "Тысячи HTML5 игр онлайн",
  meta_title: null,
  meta_description: null,
  logo_primary: "GAME",
  logo_accent: "ORBIT",
  theme: { accent: "#ea580c", neon: "#0284c7", bg: "#f4f6fa", surface: "#ffffff" },
  gameCount: 0,
};

export function SiteProvider({ children }: { children: ReactNode }) {
  const fetchSite = useServerFn(getSiteConfig);
  const { data } = useQuery({
    queryKey: ["site-config"],
    queryFn: () => fetchSite(),
    staleTime: 120_000,
    retry: 1,
  });

  const site: SiteContextValue = data ?? DEFAULT_SITE;

  useEffect(() => {
    const root = document.documentElement;
    root.style.setProperty("--bg", "#f4f6fa");
    root.style.setProperty("--surface", "#ffffff");
    root.style.setProperty("--surface-elevated", "#eef2f8");
    root.style.setProperty("--text", "#1e293b");
    root.style.setProperty("--text-dim", "#64748b");
    root.style.setProperty("--text-muted", "#94a3b8");
    root.style.setProperty("--border-soft", "rgba(15, 23, 42, 0.1)");
    const t = site.theme;
    if (t?.accent) root.style.setProperty("--accent", t.accent);
    if (t?.neon) root.style.setProperty("--neon", t.neon);
  }, [site.theme]);

  return <SiteCtx.Provider value={site}>{children}</SiteCtx.Provider>;
}

export function useSite() {
  const ctx = useContext(SiteCtx);
  if (!ctx) throw new Error("useSite outside SiteProvider");
  return ctx;
}
