"use client";

import { useEffect, useState } from "react";
import { api } from "@/lib/api";
import { resolveTenantHost } from "@/lib/tenant-host";
import { applyTheme, loadTheme, type ThemeConfig } from "@/lib/theme";

/** بارگذاری و اعمال تم White-label — روی ساب‌دامین tenant از API عمومی. */
export function useTheme() {
  const [theme, setTheme] = useState<ThemeConfig | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    let cancelled = false;
    (async () => {
      const host = resolveTenantHost(
        typeof window !== "undefined" ? window.location.hostname : ""
      );
      let next: ThemeConfig;
      if (host.isTenantHost) {
        try {
          const site = await api.public.tenantSite({
            slug: host.slug,
            host: host.hostname,
          });
          next = {
            site_name: site.name,
            primary_color: site.primary_color || "#0284c7",
            secondary_color: site.secondary_color || "#0f172a",
            logo_url: site.logo_url || "",
            support_email: "",
          };
        } catch {
          next = await loadTheme();
        }
      } else {
        next = await loadTheme();
      }
      if (cancelled) return;
      applyTheme(next);
      if (typeof document !== "undefined" && host.isTenantHost) {
        document.title = next.site_name;
      }
      setTheme(next);
      setLoading(false);
    })();
    return () => {
      cancelled = true;
    };
  }, []);

  return { theme, loading };
}
