import {
  createContext,
  useCallback,
  useContext,
  useEffect,
  useMemo,
  useState,
  type ReactNode
} from "react";
import type { SiteConfig } from "./api";
import { fetchConfig } from "./api";

const Ctx = createContext<SiteConfig | null>(null);

export function ConfigProvider({ children }: { children: ReactNode }) {
  const [cfg, setCfg] = useState<SiteConfig | null>(null);

  const load = useCallback(async () => {
    try {
      setCfg(await fetchConfig());
    } catch {
      setCfg({
        siteTitle: "萌芽小窝",
        siteTitleEn: "SproutBlog",
        cwdApiBase: "https://cwd.api.smyhub.com"
      });
    }
  }, []);

  useEffect(() => {
    load();
  }, [load]);

  const value = useMemo(() => cfg, [cfg]);

  if (!value) {
    return (
      <main style={{ padding: 24 }}>
        <p>加载站点配置…</p>
      </main>
    );
  }

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

export function useSiteConfig(): SiteConfig {
  const v = useContext(Ctx);
  if (!v) throw new Error("useSiteConfig");
  return v;
}
