"use client";

import { createContext, useContext, useEffect, useState } from "react";
import { fallbackSettings, publicFetch, type SiteSettings } from "@/lib/api";

const BrandContext = createContext<SiteSettings>(fallbackSettings);

export function useBrand() {
  return useContext(BrandContext);
}

export function BrandProvider({ children, initialSettings }: { children: React.ReactNode; initialSettings?: SiteSettings | null }) {
  const [settings, setSettings] = useState<SiteSettings>(initialSettings || fallbackSettings);

  useEffect(() => {
    if (initialSettings) return;
    publicFetch<SiteSettings>("/settings")
      .then((data) => {
        if (data) setSettings({ ...fallbackSettings, ...data });
      })
      .catch(() => undefined);
  }, [initialSettings]);

  useEffect(() => {
    const root = document.documentElement;
    root.style.setProperty("--brand-primary", settings.primary_color);
    root.style.setProperty("--brand-secondary", settings.secondary_color);
    root.style.setProperty("--brand-accent", settings.accent_color);
    root.style.setProperty("--brand-bg", settings.background_color);
    root.style.setProperty("--brand-text", settings.text_color);

    if (settings.favicon_url) {
      let favicon = document.querySelector<HTMLLinkElement>("link[rel='icon']");
      if (!favicon) {
        favicon = document.createElement("link");
        favicon.rel = "icon";
        document.head.appendChild(favicon);
      }
      favicon.href = settings.favicon_url;
    }
  }, [settings]);

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