import { useEffect, useState } from "preact/hooks";
import type { ZuzuSpec } from "@/types/spec";
import { applyTheme } from "@/theme/accents";

/** Poll /api/spec every 3s. Applies theme on change. */
export function useSpec(): ZuzuSpec | null {
  const [spec, setSpec] = useState<ZuzuSpec | null>(null);

  useEffect(() => {
    let mounted = true;

    async function fetchSpec() {
      try {
        const res = await fetch("/api/spec");
        const data: ZuzuSpec = await res.json();
        if (!mounted) return;
        setSpec((prev) => {
          if (JSON.stringify(prev) !== JSON.stringify(data)) {
            if (data.app) applyTheme(
                data.app.accent, data.app.theme,
                data.app.radius, data.app.card_style,
                data.app.density, data.app.content_width,
              );
            return data;
          }
          return prev;
        });
      } catch {
        // Server not ready yet
      }
    }

    fetchSpec();
    const id = setInterval(fetchSpec, 3000);
    return () => { mounted = false; clearInterval(id); };
  }, []);

  return spec;
}
