"use client";
import { jsx } from "react/jsx-runtime";
import React from "react";
const componentCache = /* @__PURE__ */ new Map();
const ImportResolverContext = React.createContext(null);
function ImportResolverProvider({
  children,
  theme
}) {
  const resolveComponent = React.useCallback(
    async function resolveComponentImpl(componentPath, fallback) {
      var _a, _b;
      if (!theme) {
        return fallback;
      }
      const cacheKey = `${theme.name}:${componentPath}`;
      const cached = componentCache.get(cacheKey);
      if (cached) {
        return cached;
      }
      try {
        const override = (_b = (_a = theme.components) == null ? void 0 : _a.overrides) == null ? void 0 : _b[componentPath];
        if (override) {
          let resolvedComponent;
          if (typeof override === "function") {
            const imported = await override();
            resolvedComponent = imported.default || imported;
          } else {
            resolvedComponent = override;
          }
          componentCache.set(cacheKey, resolvedComponent);
          console.log(`[ImportResolver] Using override for ${componentPath} from theme ${theme.name}`);
          return resolvedComponent;
        }
        return fallback;
      } catch (error) {
        console.error(`[ImportResolver] Error resolving component ${componentPath}:`, error);
        return fallback;
      }
    },
    [theme]
  );
  const clearComponentCache = React.useCallback(() => {
    componentCache.clear();
    console.log("[ImportResolver] Component cache cleared");
  }, []);
  React.useEffect(() => {
    clearComponentCache();
  }, [theme == null ? void 0 : theme.name, clearComponentCache]);
  const contextValue = {
    currentTheme: theme,
    resolveComponent,
    clearComponentCache
  };
  return /* @__PURE__ */ jsx(ImportResolverContext.Provider, { value: contextValue, children });
}
function useImportResolver() {
  const context = React.useContext(ImportResolverContext);
  if (!context) {
    throw new Error("useImportResolver must be used within ImportResolverProvider");
  }
  return context;
}
function withThemeOverride(componentPath, OriginalComponent) {
  const WrappedComponent = React.forwardRef((props, ref) => {
    const { resolveComponent } = useImportResolver();
    const [ResolvedComponent, setResolvedComponent] = React.useState(OriginalComponent);
    React.useEffect(() => {
      resolveComponent(componentPath, OriginalComponent).then((resolved) => {
        setResolvedComponent(resolved);
      });
    }, [resolveComponent]);
    return React.createElement(ResolvedComponent, { ...props, ref });
  });
  WrappedComponent.displayName = `withThemeOverride(${OriginalComponent.displayName || OriginalComponent.name})`;
  return WrappedComponent;
}
function createThemedComponent(componentPath, OriginalComponent, options) {
  const ThemedComponent = React.forwardRef((props, ref) => {
    const { currentTheme, resolveComponent } = useImportResolver();
    const [ResolvedComponent, setResolvedComponent] = React.useState(
      (options == null ? void 0 : options.fallback) || OriginalComponent
    );
    const [isLoading, setIsLoading] = React.useState(false);
    React.useEffect(() => {
      if (!currentTheme) {
        setResolvedComponent(OriginalComponent);
        return;
      }
      setIsLoading(true);
      resolveComponent(componentPath, OriginalComponent).then((resolved) => {
        setResolvedComponent(resolved);
      }).finally(() => {
        setIsLoading(false);
      });
    }, [currentTheme, resolveComponent]);
    if (isLoading && (options == null ? void 0 : options.fallback)) {
      return React.createElement(options.fallback, props);
    }
    return React.createElement(ResolvedComponent, { ...props, ref });
  });
  ThemedComponent.displayName = (options == null ? void 0 : options.displayName) || `Themed(${OriginalComponent.displayName || OriginalComponent.name})`;
  return ThemedComponent;
}
async function getCustomComponent(theme, componentName) {
  var _a, _b;
  if (!((_b = (_a = theme.components) == null ? void 0 : _a.custom) == null ? void 0 : _b[componentName])) {
    return null;
  }
  try {
    const customComponent = theme.components.custom[componentName];
    if (typeof customComponent === "function") {
      const imported = await customComponent();
      return imported.default || imported;
    }
    return customComponent;
  } catch (error) {
    console.error(`[ImportResolver] Error loading custom component ${componentName}:`, error);
    return null;
  }
}
function refreshThemeComponents() {
  if (process.env.NODE_ENV === "development") {
    componentCache.clear();
    console.log("[ImportResolver] Component cache refreshed for hot reload");
  }
}
function getImportResolverStats() {
  return {
    cachedComponents: componentCache.size,
    cacheKeys: Array.from(componentCache.keys())
  };
}
export {
  ImportResolverProvider,
  createThemedComponent,
  getCustomComponent,
  getImportResolverStats,
  refreshThemeComponents,
  useImportResolver,
  withThemeOverride
};
