import { ThemeService } from "../services/theme.service.js";
import { preloadThemeOverrides, clearOverrideCache } from "./override-resolver.js";
function getThemes() {
  return ThemeService.getAll();
}
function loadThemeConfig(themeName) {
  const theme = ThemeService.getByName(themeName);
  if (!theme) {
    console.error(`[Theme] Theme not found in registry: ${themeName}`);
    return null;
  }
  console.log(`[Theme] Loaded theme from registry: ${themeName}`);
  return theme;
}
function loadThemeWithDependencies(themeName) {
  var _a, _b;
  const theme = loadThemeConfig(themeName);
  if (!theme) {
    return null;
  }
  if (theme.parent) {
    console.log(`[Theme] Loading parent theme: ${theme.parent}`);
    const parentTheme = loadThemeWithDependencies(theme.parent);
    if (parentTheme) {
      const mergedTheme = {
        ...parentTheme,
        ...theme,
        components: {
          ...parentTheme.components,
          ...theme.components,
          overrides: {
            ...(_a = parentTheme.components) == null ? void 0 : _a.overrides,
            ...(_b = theme.components) == null ? void 0 : _b.overrides
          }
        },
        config: {
          ...parentTheme.config,
          ...theme.config
        }
      };
      console.log(`[Theme] Merged theme ${themeName} with parent ${theme.parent}`);
      return mergedTheme;
    }
  }
  return theme;
}
function applyThemeWithOptimizations(themeName) {
  var _a;
  try {
    console.log(`[Theme] Applying theme: ${themeName}`);
    const theme = loadThemeWithDependencies(themeName);
    if (!theme) {
      console.error(`[Theme] Failed to load theme: ${themeName}`);
      return false;
    }
    clearOverrideCache();
    preloadThemeOverrides(theme);
    if ((_a = theme.styles) == null ? void 0 : _a.globals) {
      applyThemeStyles(theme);
    }
    console.log(`[Theme] Successfully applied theme: ${themeName}`);
    return true;
  } catch (error) {
    console.error(`[Theme] Error applying theme ${themeName}:`, error);
    return false;
  }
}
let currentThemeConfig = null;
let darkModeObserver = null;
function isDarkMode() {
  if (typeof window === "undefined") return false;
  return document.documentElement.classList.contains("dark");
}
function applyColorVariables(colors) {
  const root = document.documentElement;
  Object.entries(colors).forEach(([key, value]) => {
    root.style.setProperty(`--${key}`, String(value));
    root.style.setProperty(`--theme-color-${key}`, String(value));
  });
}
function hasJSColors(theme) {
  var _a, _b;
  return !!(((_a = theme.config) == null ? void 0 : _a.colors) || ((_b = theme.config) == null ? void 0 : _b.darkColors));
}
function applyCurrentModeColors(theme) {
  var _a, _b;
  if (!hasJSColors(theme)) return;
  const darkMode = isDarkMode();
  const colors = darkMode && ((_a = theme.config) == null ? void 0 : _a.darkColors) ? theme.config.darkColors : (_b = theme.config) == null ? void 0 : _b.colors;
  if (colors) {
    applyColorVariables(colors);
  }
}
function setupDarkModeObserver(theme) {
  if (typeof window === "undefined") return;
  if (darkModeObserver) {
    darkModeObserver.disconnect();
    darkModeObserver = null;
  }
  if (!hasJSColors(theme)) return;
  darkModeObserver = new MutationObserver((mutations) => {
    for (const mutation of mutations) {
      if (mutation.attributeName === "class") {
        applyCurrentModeColors(theme);
      }
    }
  });
  darkModeObserver.observe(document.documentElement, {
    attributes: true,
    attributeFilter: ["class"]
  });
}
function applyThemeStyles(theme) {
  var _a, _b, _c;
  if (typeof window === "undefined") {
    return;
  }
  try {
    const root = document.documentElement;
    currentThemeConfig = theme;
    applyCurrentModeColors(theme);
    setupDarkModeObserver(theme);
    if ((_a = theme.config) == null ? void 0 : _a.fonts) {
      Object.entries(theme.config.fonts).forEach(([key, value]) => {
        root.style.setProperty(`--font-${key}`, String(value));
        root.style.setProperty(`--theme-font-${key}`, String(value));
      });
    }
    if ((_b = theme.config) == null ? void 0 : _b.spacing) {
      Object.entries(theme.config.spacing).forEach(([key, value]) => {
        root.style.setProperty(`--${key}`, String(value));
      });
    }
    if ((_c = theme.config) == null ? void 0 : _c.shadows) {
      Object.entries(theme.config.shadows).forEach(([key, value]) => {
        root.style.setProperty(`--${key}`, String(value));
      });
    }
    console.log(`[Theme] Applied CSS variables for theme: ${theme.name}`);
  } catch (error) {
    console.error("[Theme] Error applying theme styles:", error);
  }
}
function cleanupThemeObserver() {
  if (darkModeObserver) {
    darkModeObserver.disconnect();
    darkModeObserver = null;
  }
}
function getThemeLoadingStats() {
  const themes = ThemeService.getAll();
  return {
    totalThemes: themes.length,
    loadMethod: "build-time-registry",
    performanceNotes: "Ultra-fast loading via static registry (zero I/O, <3ms)"
  };
}
function clearThemeCache() {
  clearOverrideCache();
  console.log("[Theme] Cleared theme override cache (registry is immutable)");
}
function validateThemeConfig(theme) {
  const errors = [];
  if (!theme.name) {
    errors.push("Theme name is required");
  }
  if (!theme.displayName) {
    errors.push("Theme display name is required");
  }
  if (!theme.version) {
    errors.push("Theme version is required");
  }
  if (theme.parent && theme.parent === theme.name) {
    errors.push("Theme cannot be its own parent");
  }
  return {
    valid: errors.length === 0,
    errors
  };
}
export {
  applyThemeStyles,
  applyThemeWithOptimizations,
  cleanupThemeObserver,
  clearThemeCache,
  getThemeLoadingStats,
  getThemes,
  loadThemeConfig,
  loadThemeWithDependencies,
  validateThemeConfig
};
