"use client";
import { jsx } from "react/jsx-runtime";
import React, { createContext, useContext, useEffect, useState } from "react";
import { ThemeService } from "../services/theme.service.js";
import { ImportResolverProvider } from "./import-resolver.js";
import { applyThemeStyles } from "./theme-loader.js";
const ThemeContext = createContext(null);
function ThemeProvider({ children, defaultTheme = "default" }) {
  const [currentTheme, setCurrentTheme] = useState(null);
  const [availableThemes, setAvailableThemes] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState();
  const loadTheme = React.useCallback((themeName) => {
    var _a;
    try {
      setLoading(true);
      setError(void 0);
      const activeThemeName = themeName || process.env.NEXT_PUBLIC_ACTIVE_THEME;
      const activeTheme = ThemeService.getByName(activeThemeName || "");
      if (!activeTheme) {
        throw new Error(`Theme not found: ${activeThemeName}`);
      }
      setCurrentTheme(activeTheme);
      if ((_a = activeTheme.styles) == null ? void 0 : _a.globals) {
        applyThemeStyles(activeTheme);
      }
      console.log(`[ThemeProvider] Loaded theme: ${activeTheme.name} (build-time registry)`);
    } catch (error2) {
      const errorMsg = error2 instanceof Error ? error2.message : "Unknown error";
      console.error("[ThemeProvider] Error loading theme:", error2);
      setError(errorMsg);
    } finally {
      setLoading(false);
    }
  }, []);
  const loadAvailableThemes = React.useCallback(() => {
    try {
      const themes = ThemeService.getAll();
      setAvailableThemes(themes);
      console.log(`[ThemeProvider] Loaded ${themes.length} themes from registry`);
    } catch (error2) {
      console.error("[ThemeProvider] Error loading themes:", error2);
      setAvailableThemes([]);
    }
  }, []);
  const switchTheme = (themeName) => {
    return new Promise((resolve) => {
      try {
        setLoading(true);
        loadTheme(themeName);
        if (typeof window !== "undefined") {
          localStorage.setItem("selected-theme", themeName);
          console.log(`[ThemeProvider] Persisted theme preference: ${themeName}`);
        }
        resolve(true);
      } catch (error2) {
        console.error("[ThemeProvider] Failed to switch theme:", error2);
        resolve(false);
      }
    });
  };
  const reloadTheme = React.useCallback(() => {
    return new Promise((resolve) => {
      if (currentTheme) {
        console.log(`[ThemeProvider] Reloading theme: ${currentTheme.name}`);
        loadTheme(currentTheme.name);
      }
      resolve();
    });
  }, [currentTheme, loadTheme]);
  const refreshThemes = React.useCallback(() => {
    return new Promise((resolve) => {
      console.log("[ThemeProvider] Refreshing available themes");
      loadAvailableThemes();
      resolve();
    });
  }, [loadAvailableThemes]);
  useEffect(() => {
    const initTheme = async () => {
      const themeToLoad = process.env.NEXT_PUBLIC_ACTIVE_THEME;
      if (themeToLoad) {
        console.log(`[ThemeProvider] Using ENV theme: ${themeToLoad}`);
      } else {
        console.warn("[ThemeProvider] No NEXT_PUBLIC_ACTIVE_THEME set in ENV");
      }
      loadAvailableThemes();
      loadTheme(themeToLoad);
    };
    initTheme();
  }, [loadAvailableThemes, loadTheme]);
  useEffect(() => {
    if (process.env.NODE_ENV === "development") {
      const handleHotReload = () => {
        console.log("[ThemeProvider] Hot reload detected, refreshing themes");
        refreshThemes();
        if (currentTheme) {
          reloadTheme();
        }
      };
      if (typeof window !== "undefined" && window.webpackHotUpdate) {
        window.addEventListener("webpack-hot-update", handleHotReload);
        return () => {
          window.removeEventListener("webpack-hot-update", handleHotReload);
        };
      }
    }
  }, [currentTheme, refreshThemes, reloadTheme]);
  const contextValue = {
    currentTheme,
    availableThemes,
    loading,
    error,
    switchTheme,
    reloadTheme,
    refreshThemes
  };
  return /* @__PURE__ */ jsx(ThemeContext.Provider, { value: contextValue, children: /* @__PURE__ */ jsx(ImportResolverProvider, { theme: currentTheme, children }) });
}
function useTheme() {
  const context = useContext(ThemeContext);
  if (!context) {
    throw new Error("useTheme must be used within a ThemeProvider");
  }
  return context;
}
function useComponentOverride(componentPath) {
  var _a, _b;
  const { currentTheme } = useTheme();
  const override = (_b = (_a = currentTheme == null ? void 0 : currentTheme.components) == null ? void 0 : _a.overrides) == null ? void 0 : _b[componentPath];
  return {
    hasOverride: !!override,
    Override: override,
    originalPath: componentPath,
    themeName: currentTheme == null ? void 0 : currentTheme.name
  };
}
function useCustomComponent(componentName) {
  var _a, _b;
  const { currentTheme } = useTheme();
  const customComponent = (_b = (_a = currentTheme == null ? void 0 : currentTheme.components) == null ? void 0 : _a.custom) == null ? void 0 : _b[componentName];
  return {
    hasCustom: !!customComponent,
    CustomComponent: customComponent,
    themeName: currentTheme == null ? void 0 : currentTheme.name
  };
}
function useThemeConfig() {
  var _a, _b, _c, _d;
  const { currentTheme } = useTheme();
  return {
    colors: ((_a = currentTheme == null ? void 0 : currentTheme.config) == null ? void 0 : _a.colors) || {},
    fonts: ((_b = currentTheme == null ? void 0 : currentTheme.config) == null ? void 0 : _b.fonts) || {},
    spacing: ((_c = currentTheme == null ? void 0 : currentTheme.config) == null ? void 0 : _c.spacing) || {},
    breakpoints: ((_d = currentTheme == null ? void 0 : currentTheme.config) == null ? void 0 : _d.breakpoints) || {},
    themeName: currentTheme == null ? void 0 : currentTheme.name
  };
}
export {
  ThemeProvider,
  useComponentOverride,
  useCustomComponent,
  useTheme,
  useThemeConfig
};
