'use strict';

var chunkAPBYI7AY_cjs = require('./chunk-APBYI7AY.cjs');
var chunkG7VZBCD6_cjs = require('./chunk-G7VZBCD6.cjs');

// src/utils/template-error-handler.ts
var template_error_handler_exports = {};
chunkG7VZBCD6_cjs.__export(template_error_handler_exports, {
  TemplateErrorHandler: () => exports.TemplateErrorHandler,
  TemplateValidationSystem: () => exports.TemplateValidationSystem
});
exports.TemplateErrorHandler = void 0; exports.TemplateValidationSystem = void 0;
var init_template_error_handler = chunkG7VZBCD6_cjs.__esm({
  "src/utils/template-error-handler.ts"() {
    exports.TemplateErrorHandler = class {
      static errorLog = [];
      static maxErrorLogSize = 100;
      /**
       * Render template with fallback on error
       */
      static renderWithFallback(template, data, renderer, options = {}) {
        try {
          this.validateTemplate(template);
          const result = renderer(template, data);
          if (typeof result !== "string") {
            throw new Error("Template renderer returned non-string result");
          }
          return result;
        } catch (error) {
          this.logError(error, template, data);
          if (options.enableErrorReporting) {
            this.reportError(error, template, data);
          }
          if (options.fallbackTemplate) {
            try {
              return renderer(options.fallbackTemplate, data);
            } catch (fallbackError) {
              console.error("[TEMPLATE] Fallback rendering error:", fallbackError);
              this.logError(fallbackError, options.fallbackTemplate, data);
            }
          }
          return this.renderErrorTemplate(error, data, options.isDevelopment);
        }
      }
      /**
       * Validate template for common issues
       */
      static validateTemplate(template) {
        if (!template || typeof template !== "string") {
          throw new Error("Invalid template: template must be a non-empty string");
        }
        const nestedQuotePattern = /onclick\s*=\s*["'][^"']*'[^']*\$\{[^}]*\}[^']*'[^"']*["']/g;
        if (nestedQuotePattern.test(template)) {
          throw new Error("Template contains nested quotes in onclick handlers that may cause JavaScript syntax errors");
        }
        const templateLiteralCount = (template.match(/`/g) || []).length;
        if (templateLiteralCount % 2 !== 0) {
          throw new Error("Template contains unmatched template literal backticks");
        }
      }
      /**
       * Log template error for debugging
       */
      static logError(error, template, data) {
        const templateError = {
          message: error.message,
          template: template.substring(0, 200) + (template.length > 200 ? "..." : ""),
          data: this.sanitizeData(data),
          stack: error.stack,
          timestamp: /* @__PURE__ */ new Date()
        };
        this.errorLog.push(templateError);
        if (this.errorLog.length > this.maxErrorLogSize) {
          this.errorLog.shift();
        }
        console.error("[TEMPLATE ERROR]", {
          message: error.message,
          template: templateError.template,
          timestamp: templateError.timestamp
        });
      }
      /**
       * Report error to monitoring system
       */
      static reportError(error, template, data) {
        console.warn("[TEMPLATE MONITORING]", {
          error: error.message,
          template: template.substring(0, 100),
          userAgent: typeof navigator !== "undefined" ? navigator.userAgent : "server",
          timestamp: (/* @__PURE__ */ new Date()).toISOString()
        });
      }
      /**
       * Render minimal error template
       */
      static renderErrorTemplate(error, data, isDevelopment = false) {
        const errorId = `error-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
        return `
      <div id="${errorId}" class="template-error bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800/50 rounded-lg p-4 my-4">
        <div class="flex items-start">
          <div class="flex-shrink-0">
            <svg class="h-5 w-5 text-red-400" viewBox="0 0 20 20" fill="currentColor">
              <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clip-rule="evenodd" />
            </svg>
          </div>
          <div class="ml-3 flex-1">
            <h3 class="text-sm font-semibold text-red-800 dark:text-red-200">Template Rendering Error</h3>
            <div class="mt-2 text-sm text-red-700 dark:text-red-300">
              <p>Unable to render template content. The page may not display correctly.</p>
              ${isDevelopment ? `
                <details class="mt-2">
                  <summary class="cursor-pointer font-medium">Error Details (Development Mode)</summary>
                  <pre class="mt-2 text-xs bg-red-100 dark:bg-red-900/30 p-2 rounded overflow-auto">${this.escapeHtml(error.message)}</pre>
                </details>
              ` : ""}
            </div>
            <div class="mt-3">
              <button 
                onclick="document.getElementById('${errorId}').style.display='none'"
                class="text-xs bg-red-600 hover:bg-red-700 text-white px-2 py-1 rounded transition-colors"
              >
                Dismiss
              </button>
            </div>
          </div>
        </div>
      </div>
    `;
      }
      /**
       * Get error log for debugging
       */
      static getErrorLog() {
        return [...this.errorLog];
      }
      /**
       * Clear error log
       */
      static clearErrorLog() {
        this.errorLog = [];
      }
      /**
       * Get error statistics
       */
      static getErrorStats() {
        const now = /* @__PURE__ */ new Date();
        const oneHourAgo = new Date(now.getTime() - 60 * 60 * 1e3);
        const recentErrors = this.errorLog.filter((error) => error.timestamp > oneHourAgo);
        const errorCounts = /* @__PURE__ */ new Map();
        this.errorLog.forEach((error) => {
          const count = errorCounts.get(error.message) || 0;
          errorCounts.set(error.message, count + 1);
        });
        const commonErrors = Array.from(errorCounts.entries()).sort(([, a], [, b]) => b - a).slice(0, 5).map(([message]) => message);
        return {
          totalErrors: this.errorLog.length,
          recentErrors: recentErrors.length,
          commonErrors
        };
      }
      /**
       * Sanitize data for logging (remove sensitive information)
       */
      static sanitizeData(data) {
        if (!data || typeof data !== "object") {
          return data;
        }
        const sanitized = { ...data };
        const sensitiveFields = ["password", "token", "secret", "key", "auth", "credential"];
        for (const field of sensitiveFields) {
          if (field in sanitized) {
            sanitized[field] = "[REDACTED]";
          }
        }
        return sanitized;
      }
      /**
       * Escape HTML for safe display
       */
      static escapeHtml(text) {
        const div = document?.createElement("div");
        if (div) {
          div.textContent = text;
          return div.innerHTML;
        }
        return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
      }
    };
    exports.TemplateValidationSystem = class {
      static validationRules = [];
      /**
       * Add custom validation rule
       */
      static addValidationRule(rule) {
        this.validationRules.push(rule);
      }
      /**
       * Validate template with all rules
       */
      static validateTemplate(template) {
        const errors = [];
        for (const rule of this.validationRules) {
          try {
            const ruleErrors = rule(template);
            errors.push(...ruleErrors);
          } catch (error) {
            errors.push(`Validation rule error: ${error.message}`);
          }
        }
        return {
          valid: errors.length === 0,
          errors
        };
      }
      /**
       * Initialize default validation rules
       */
      static initializeDefaultRules() {
        this.addValidationRule((template) => {
          const errors = [];
          const nestedQuotePattern = /onclick\s*=\s*["'][^"']*'[^']*\$\{[^}]*\}[^']*'[^"']*["']/g;
          const matches = template.match(nestedQuotePattern);
          if (matches) {
            errors.push(`Found ${matches.length} nested quote issues in onclick handlers`);
          }
          return errors;
        });
        this.addValidationRule((template) => {
          const errors = [];
          const innerHTMLPattern = /\.innerHTML\s*=\s*`[^`]*\$\{[^}]*\}[^`]*`/g;
          const matches = template.match(innerHTMLPattern);
          if (matches) {
            errors.push(`Found ${matches.length} potentially unsafe innerHTML assignments`);
          }
          return errors;
        });
        this.addValidationRule((template) => {
          const errors = [];
          const unescapedPattern = /\$\{[^}]*\.(?:innerHTML|outerHTML|textContent)\}/g;
          const matches = template.match(unescapedPattern);
          if (matches) {
            errors.push(`Found ${matches.length} potentially unsafe content insertions`);
          }
          return errors;
        });
      }
    };
    exports.TemplateValidationSystem.initializeDefaultRules();
  }
});

// src/utils/safe-template-renderer.ts
var safe_template_renderer_exports = {};
chunkG7VZBCD6_cjs.__export(safe_template_renderer_exports, {
  SafeTemplateRenderer: () => exports.SafeTemplateRenderer,
  setupGlobalTemplateErrorHandling: () => setupGlobalTemplateErrorHandling,
  withErrorBoundary: () => withErrorBoundary
});
function withErrorBoundary(templateName) {
  return function(target, propertyKey, descriptor) {
    const originalMethod = descriptor.value;
    descriptor.value = function(data) {
      return exports.SafeTemplateRenderer.render(originalMethod.bind(this), data, {
        templateName: `${target.constructor.name}.${propertyKey}`,
        enableErrorReporting: true
      });
    };
    return descriptor;
  };
}
function setupGlobalTemplateErrorHandling() {
  if (typeof window !== "undefined") {
    window.addEventListener("error", (event) => {
      if (event.error && event.error.message && event.error.message.includes("template")) {
        console.error("[GLOBAL TEMPLATE ERROR]", event.error);
        exports.TemplateErrorHandler.getErrorStats();
      }
    });
  }
  if (typeof setInterval !== "undefined") {
    setInterval(() => {
      const stats = exports.TemplateErrorHandler.getErrorStats();
      if (stats.recentErrors > 0) {
        console.warn("[TEMPLATE MONITORING] Recent template errors:", stats);
      }
    }, 5 * 60 * 1e3);
  }
}
exports.SafeTemplateRenderer = void 0;
var init_safe_template_renderer = chunkG7VZBCD6_cjs.__esm({
  "src/utils/safe-template-renderer.ts"() {
    init_template_error_handler();
    exports.SafeTemplateRenderer = class {
      /**
       * Safely render a template with error boundaries
       */
      static render(templateFunction, data, options = {}) {
        const templateName = options.templateName || "unknown";
        options.context || "template";
        try {
          if (data === null || data === void 0) {
            throw new Error(`Template data is null or undefined for ${templateName}`);
          }
          const result = templateFunction(data);
          if (typeof result !== "string") {
            throw new Error(`Template ${templateName} returned non-string result: ${typeof result}`);
          }
          if (result.trim().length === 0) {
            console.warn(`[TEMPLATE] Template ${templateName} returned empty result`);
          }
          return result;
        } catch (error) {
          console.error(`[TEMPLATE] Error rendering ${templateName}:`, error);
          return exports.TemplateErrorHandler.renderWithFallback(
            `Template: ${templateName}`,
            data,
            () => {
              throw error;
            },
            // Re-throw to trigger error handling
            {
              ...options,
              isDevelopment: process.env.NODE_ENV === "development"
            }
          );
        }
      }
      /**
       * Safely render admin layout with error boundaries
       */
      static renderAdminLayout(layoutFunction, data, layoutName = "admin-layout") {
        return this.render(layoutFunction, data, {
          templateName: layoutName,
          context: "admin-layout",
          enableErrorReporting: true,
          fallbackTemplate: this.getAdminLayoutFallback()
        });
      }
      /**
       * Safely render page content with error boundaries
       */
      static renderPageContent(pageFunction, data, pageName = "page") {
        return this.render(pageFunction, data, {
          templateName: pageName,
          context: "page-content",
          enableErrorReporting: true,
          fallbackTemplate: this.getPageContentFallback()
        });
      }
      /**
       * Safely render component with error boundaries
       */
      static renderComponent(componentFunction, data, componentName = "component") {
        return this.render(componentFunction, data, {
          templateName: componentName,
          context: "component",
          enableErrorReporting: false,
          // Less critical than layouts/pages
          fallbackTemplate: this.getComponentFallback(componentName)
        });
      }
      /**
       * Get fallback template for admin layout
       */
      static getAdminLayoutFallback() {
        return `
      <!DOCTYPE html>
      <html lang="en" class="dark">
      <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>CF-CMS Admin - Error</title>
        <script src="https://cdn.tailwindcss.com"></script>
      </head>
      <body class="bg-zinc-900 text-white">
        <div class="min-h-screen flex items-center justify-center">
          <div class="max-w-md w-full bg-zinc-800 rounded-lg p-6">
            <div class="text-center">
              <h1 class="text-xl font-semibold text-red-400 mb-4">Template Error</h1>
              <p class="text-zinc-300 mb-4">The admin interface encountered an error while loading.</p>
              <button onclick="window.location.reload()" class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded">
                Reload Page
              </button>
            </div>
          </div>
        </div>
      </body>
      </html>
    `;
      }
      /**
       * Get fallback template for page content
       */
      static getPageContentFallback() {
        return `
      <div class="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800/50 rounded-lg p-6 m-4">
        <div class="flex items-center">
          <div class="flex-shrink-0">
            <svg class="h-5 w-5 text-red-400" viewBox="0 0 20 20" fill="currentColor">
              <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clip-rule="evenodd" />
            </svg>
          </div>
          <div class="ml-3">
            <h3 class="text-sm font-medium text-red-800 dark:text-red-200">Page Content Error</h3>
            <div class="mt-2 text-sm text-red-700 dark:text-red-300">
              <p>This page content could not be loaded. Please try refreshing the page.</p>
            </div>
            <div class="mt-4">
              <button onclick="window.location.reload()" class="bg-red-600 hover:bg-red-700 text-white px-3 py-2 rounded text-sm">
                Refresh Page
              </button>
            </div>
          </div>
        </div>
      </div>
    `;
      }
      /**
       * Get fallback template for components
       */
      static getComponentFallback(componentName) {
        return `
      <div class="bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800/50 rounded p-3 my-2">
        <div class="flex items-center text-sm">
          <svg class="h-4 w-4 text-yellow-400 mr-2" viewBox="0 0 20 20" fill="currentColor">
            <path fill-rule="evenodd" d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" clip-rule="evenodd" />
          </svg>
          <span class="text-yellow-800 dark:text-yellow-200">Component "${componentName}" failed to load</span>
        </div>
      </div>
    `;
      }
      /**
       * Create a safe wrapper for existing template functions
       */
      static wrapTemplateFunction(templateFunction, templateName) {
        return (data) => {
          return this.render(templateFunction, data, {
            templateName,
            enableErrorReporting: true
          });
        };
      }
      /**
       * Batch render multiple templates safely
       */
      static renderBatch(templates) {
        return templates.map(
          (template) => this.render(template.function, template.data, {
            templateName: template.name,
            enableErrorReporting: true
          })
        );
      }
    };
  }
});

// src/utils/theme-manager.ts
var theme_manager_exports = {};
chunkG7VZBCD6_cjs.__export(theme_manager_exports, {
  DEFAULT_THEME: () => exports.DEFAULT_THEME,
  ThemeManager: () => exports.ThemeManager,
  getThemeManager: () => getThemeManager,
  initializeThemeSystem: () => initializeThemeSystem
});
function getThemeManager() {
  if (!globalThemeManager) {
    globalThemeManager = new exports.ThemeManager();
    globalThemeManager.registerTheme(exports.DEFAULT_THEME);
    globalThemeManager.switchTheme("default");
  }
  return globalThemeManager;
}
function initializeThemeSystem() {
  const manager = getThemeManager();
  manager.switchTheme("default");
}
exports.ThemeManager = void 0; exports.DEFAULT_THEME = void 0; var globalThemeManager;
var init_theme_manager = chunkG7VZBCD6_cjs.__esm({
  "src/utils/theme-manager.ts"() {
    exports.ThemeManager = class {
      themes = /* @__PURE__ */ new Map();
      activeTheme = "default";
      cssVariables = /* @__PURE__ */ new Map();
      injectedStyles = /* @__PURE__ */ new Set();
      themeAssets = /* @__PURE__ */ new Map();
      /**
       * Register a theme
       */
      registerTheme(config) {
        this.themes.set(config.name, config);
        if (config.assets && config.assets.size > 0) {
          this.themeAssets.set(config.name, config.assets);
        }
      }
      /**
       * Get registered theme
       */
      getTheme(name) {
        return this.themes.get(name) || null;
      }
      /**
       * List all registered themes
       */
      listThemes() {
        return Array.from(this.themes.keys());
      }
      /**
       * Switch to a theme
       */
      switchTheme(name) {
        const theme = this.themes.get(name);
        if (!theme) {
          throw new Error(`Theme "${name}" not found`);
        }
        this.activeTheme = name;
        this.applyCSSVariables(theme.variables);
        this.loadStylesheets(theme.stylesheets);
      }
      /**
       * Get active theme
       */
      getActiveTheme() {
        return this.activeTheme;
      }
      /**
       * Get active theme config
       */
      getActiveThemeConfig() {
        return this.themes.get(this.activeTheme) || null;
      }
      /**
       * Apply CSS variables
       */
      applyCSSVariables(variables) {
        this.cssVariables.clear();
        for (const [key, value] of Object.entries(variables)) {
          this.cssVariables.set(key, value);
        }
        this.injectCSSVariables();
      }
      /**
       * Inject CSS variables into document
       */
      injectCSSVariables() {
        if (typeof document === "undefined") {
          return;
        }
        const existingStyle = document.getElementById("theme-variables");
        if (existingStyle) {
          existingStyle.remove();
        }
        let css = ":root {\n";
        for (const [key, value] of this.cssVariables) {
          css += `  --${key}: ${value};
`;
        }
        css += "}\n";
        const style = document.createElement("style");
        style.id = "theme-variables";
        style.textContent = css;
        document.head.appendChild(style);
      }
      /**
       * Load stylesheets
       */
      loadStylesheets(stylesheets) {
        if (typeof document === "undefined") {
          return;
        }
        for (const id of this.injectedStyles) {
          const element = document.getElementById(id);
          if (element) {
            element.remove();
          }
        }
        this.injectedStyles.clear();
        let index = 0;
        for (const [name, css] of stylesheets) {
          const id = `theme-${name}-${index}`;
          const style = document.createElement("style");
          style.id = id;
          style.textContent = css;
          document.head.appendChild(style);
          this.injectedStyles.add(id);
          index++;
        }
      }
      /**
       * Get CSS variable value
       */
      getCSSVariable(name) {
        return this.cssVariables.get(name);
      }
      /**
       * Set CSS variable value
       */
      setCSSVariable(name, value) {
        this.cssVariables.set(name, value);
        this.injectCSSVariables();
      }
      /**
       * Update multiple CSS variables
       */
      updateCSSVariables(variables) {
        for (const [key, value] of Object.entries(variables)) {
          this.cssVariables.set(key, value);
        }
        this.injectCSSVariables();
      }
      /**
       * Get all CSS variables
       */
      getAllCSSVariables() {
        const result = {};
        for (const [key, value] of this.cssVariables) {
          result[key] = value;
        }
        return result;
      }
      /**
       * Get theme asset
       */
      getThemeAsset(themeName, assetName) {
        return this.themeAssets.get(themeName)?.get(assetName);
      }
      /**
       * Get all theme assets
       */
      getThemeAssets(themeName) {
        return this.themeAssets.get(themeName) || /* @__PURE__ */ new Map();
      }
      /**
       * Add theme asset
       */
      addThemeAsset(themeName, assetName, asset) {
        if (!this.themeAssets.has(themeName)) {
          this.themeAssets.set(themeName, /* @__PURE__ */ new Map());
        }
        this.themeAssets.get(themeName).set(assetName, asset);
      }
      /**
       * Create theme from options
       */
      static createTheme(options) {
        return {
          name: options.name,
          version: "1.0.0",
          description: `${options.name} theme`,
          variables: options.variables || {},
          stylesheets: options.stylesheets || /* @__PURE__ */ new Map(),
          assets: options.assets || /* @__PURE__ */ new Map()
        };
      }
      /**
       * Create theme from manifest
       */
      static createThemeFromManifest(manifest, stylesheets, assets) {
        const variables = {};
        if (manifest.config?.colors) {
          for (const [key, value] of Object.entries(manifest.config.colors)) {
            variables[`color-${key}`] = value;
          }
        }
        if (manifest.config?.typography) {
          for (const [key, value] of Object.entries(manifest.config.typography)) {
            variables[`font-${key}`] = value;
          }
        }
        if (manifest.config?.spacing) {
          for (const [key, value] of Object.entries(manifest.config.spacing)) {
            variables[`spacing-${key}`] = value;
          }
        }
        if (manifest.config?.radius) {
          for (const [key, value] of Object.entries(manifest.config.radius)) {
            variables[`radius-${key}`] = value;
          }
        }
        if (manifest.config?.shadows) {
          for (const [key, value] of Object.entries(manifest.config.shadows)) {
            variables[`shadow-${key}`] = value;
          }
        }
        return {
          name: manifest.name,
          version: manifest.version,
          description: manifest.description,
          author: manifest.author,
          variables,
          stylesheets: stylesheets || /* @__PURE__ */ new Map(),
          assets: assets || /* @__PURE__ */ new Map()
        };
      }
    };
    exports.DEFAULT_THEME = {
      name: "default",
      version: "1.0.0",
      description: "CF-CMS Default Theme",
      author: "CF-CMS Team",
      variables: {
        // Colors
        "color-primary": "#3b82f6",
        "color-primary-dark": "#2563eb",
        "color-primary-light": "#60a5fa",
        "color-primary-alpha": "rgba(59, 130, 246, 0.1)",
        "color-success": "#10b981",
        "color-success-dark": "#059669",
        "color-success-light": "#6ee7b7",
        "color-success-bg": "#d1fae5",
        "color-warning": "#f59e0b",
        "color-warning-dark": "#d97706",
        "color-warning-light": "#fbbf24",
        "color-warning-bg": "#fef3c7",
        "color-error": "#ef4444",
        "color-error-dark": "#dc2626",
        "color-error-light": "#f87171",
        "color-error-bg": "#fee2e2",
        "color-info": "#0ea5e9",
        "color-info-dark": "#0284c7",
        "color-info-light": "#38bdf8",
        "color-info-bg": "#cffafe",
        "color-surface": "#ffffff",
        "color-surface-secondary": "#f9fafb",
        "color-surface-tertiary": "#f3f4f6",
        "color-surface-hover": "#f0f1f3",
        "color-border": "#e5e7eb",
        "color-border-light": "#f3f4f6",
        "color-border-dark": "#d1d5db",
        "color-text-primary": "#111827",
        "color-text-secondary": "#6b7280",
        "color-text-tertiary": "#9ca3af",
        "color-text-disabled": "#d1d5db",
        "color-text-inverse": "#ffffff",
        // Typography
        "font-family": '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',
        "font-family-mono": '"Menlo", "Monaco", "Courier New", monospace',
        "font-size-xs": "0.75rem",
        "font-size-sm": "0.875rem",
        "font-size-base": "1rem",
        "font-size-lg": "1.125rem",
        "font-size-xl": "1.25rem",
        "font-size-2xl": "1.5rem",
        "font-size-3xl": "1.875rem",
        "font-size-4xl": "2.25rem",
        "font-weight-light": "300",
        "font-weight-normal": "400",
        "font-weight-medium": "500",
        "font-weight-semibold": "600",
        "font-weight-bold": "700",
        "line-height-tight": "1.25",
        "line-height-normal": "1.5",
        "line-height-relaxed": "1.75",
        // Spacing
        "spacing-xs": "0.25rem",
        "spacing-sm": "0.5rem",
        "spacing-md": "1rem",
        "spacing-lg": "1.5rem",
        "spacing-xl": "2rem",
        "spacing-2xl": "3rem",
        "spacing-3xl": "4rem",
        // Border Radius
        "radius-sm": "0.375rem",
        "radius-md": "0.5rem",
        "radius-lg": "0.75rem",
        "radius-xl": "1rem",
        "radius-full": "9999px",
        // Shadows
        "shadow-sm": "0 1px 2px 0 rgba(0, 0, 0, 0.05)",
        "shadow-md": "0 4px 6px -1px rgba(0, 0, 0, 0.1)",
        "shadow-lg": "0 10px 15px -3px rgba(0, 0, 0, 0.1)",
        "shadow-xl": "0 20px 25px -5px rgba(0, 0, 0, 0.1)",
        // Transitions
        "transition-fast": "150ms ease-in-out",
        "transition-normal": "200ms ease-in-out",
        "transition-slow": "300ms ease-in-out",
        // Z-Index
        "z-dropdown": "1000",
        "z-sticky": "1020",
        "z-fixed": "1030",
        "z-modal-backdrop": "1040",
        "z-modal": "1050",
        "z-popover": "1060",
        "z-tooltip": "1070"
      },
      stylesheets: /* @__PURE__ */ new Map(),
      assets: /* @__PURE__ */ new Map()
    };
    globalThemeManager = null;
  }
});

// src/utils/semantic-template-engine.ts
var semantic_template_engine_exports = {};
chunkG7VZBCD6_cjs.__export(semantic_template_engine_exports, {
  SemanticTemplateEngine: () => exports.SemanticTemplateEngine,
  getTemplateEngine: () => getTemplateEngine,
  initializeTemplateEngine: () => initializeTemplateEngine
});
function getTemplateEngine() {
  if (!globalTemplateEngine) {
    globalTemplateEngine = new exports.SemanticTemplateEngine();
  }
  return globalTemplateEngine;
}
function initializeTemplateEngine() {
  getTemplateEngine();
}
exports.SemanticTemplateEngine = void 0; var globalTemplateEngine;
var init_semantic_template_engine = chunkG7VZBCD6_cjs.__esm({
  "src/utils/semantic-template-engine.ts"() {
    exports.SemanticTemplateEngine = class {
      cache = /* @__PURE__ */ new Map();
      pluginTemplates = /* @__PURE__ */ new Map();
      helpers = /* @__PURE__ */ new Map();
      partials = /* @__PURE__ */ new Map();
      constructor() {
        this.registerBuiltinHelpers();
      }
      /**
       * Compile a template string
       */
      compile(template) {
        const validation = this.validate(template);
        if (!validation.valid) {
          throw new Error(`Template validation failed: ${validation.errors.join(", ")}`);
        }
        const cacheKey = this.getCacheKey(template);
        if (this.cache.has(cacheKey)) {
          return this.cache.get(cacheKey);
        }
        const compiled = this.compileTemplate(template);
        this.cache.set(cacheKey, compiled);
        return compiled;
      }
      /**
       * Render a template with data
       */
      render(template, data = {}) {
        try {
          const compiled = this.compile(template);
          return compiled(data);
        } catch (error) {
          throw new Error(`Template rendering failed: ${error.message}`);
        }
      }
      /**
       * Validate template for semantic compliance
       */
      validate(template) {
        const errors = [];
        const warnings = [];
        if (/class\s*=\s*["'][^"']*["']/i.test(template)) {
          errors.push("Templates must not contain hardcoded CSS classes. Use data attributes instead.");
        }
        if (/style\s*=\s*["'][^"']*["']/i.test(template)) {
          errors.push("Templates must not contain inline styles. Use CSS variables instead.");
        }
        if (/(bg-|text-|p-|m-|flex|grid|rounded|shadow|border|ring|dark:)/i.test(template)) {
          errors.push("Templates contain Tailwind CSS classes. Use semantic HTML with data attributes.");
        }
        if (/(container|row|col-|btn|alert|card|modal|navbar)/i.test(template)) {
          errors.push("Templates contain Bootstrap CSS classes. Use semantic HTML with data attributes.");
        }
        if (/\$\{[^}]*\}/g.test(template)) {
          const matches = template.match(/\$\{[^}]*\}/g) || [];
          if (matches.length > 10) {
            warnings.push(`High number of template variables (${matches.length}). Ensure proper escaping.`);
          }
        }
        if (!/<(article|section|header|footer|nav|main|aside|div|span|p|h[1-6]|ul|ol|li|table|form|button|input|label)/.test(template)) {
          warnings.push("Template does not contain semantic HTML elements.");
        }
        if (!/data-component|data-element|data-action/.test(template)) {
          warnings.push("Template does not use data attributes for styling hooks.");
        }
        return {
          valid: errors.length === 0,
          errors,
          warnings
        };
      }
      /**
       * Register a helper function
       */
      registerHelper(name, helper) {
        this.helpers.set(name, helper);
      }
      /**
       * Register a partial template
       */
      registerPartial(name, template) {
        const validation = this.validate(template);
        if (!validation.valid) {
          throw new Error(`Partial template validation failed: ${validation.errors.join(", ")}`);
        }
        this.partials.set(name, template);
      }
      /**
       * Register a plugin template
       */
      registerPluginTemplate(pluginName, templateName, template) {
        const validation = this.validate(template);
        if (!validation.valid) {
          throw new Error(`Plugin template validation failed: ${validation.errors.join(", ")}`);
        }
        if (!this.pluginTemplates.has(pluginName)) {
          this.pluginTemplates.set(pluginName, /* @__PURE__ */ new Map());
        }
        this.pluginTemplates.get(pluginName).set(templateName, template);
      }
      /**
       * Get a plugin template
       */
      getPluginTemplate(pluginName, templateName) {
        return this.pluginTemplates.get(pluginName)?.get(templateName) || null;
      }
      /**
       * Clear template cache
       */
      clearCache() {
        this.cache.clear();
      }
      /**
       * Get cache statistics
       */
      getCacheStats() {
        return {
          size: this.cache.size,
          entries: this.cache.size
        };
      }
      /**
       * Compile template string
       */
      compileTemplate(template) {
        return (data) => {
          let result = template;
          result = result.replace(/\{\{([^}]+)\}\}/g, (match, key) => {
            const value = this.getNestedValue(data, key.trim());
            return this.escapeHtml(String(value || ""));
          });
          result = result.replace(/\{\{#(\w+)\s+([^}]+)\}\}([\s\S]*?)\{\{\/\1\}\}/g, (match, helperName, args, content) => {
            const helper = this.helpers.get(helperName);
            if (!helper) {
              throw new Error(`Helper "${helperName}" not found`);
            }
            const argValue = this.getNestedValue(data, args.trim());
            return helper(argValue, content, data);
          });
          result = result.replace(/\{\{>\s*(\w+)\s*\}\}/g, (match, partialName) => {
            const partial = this.partials.get(partialName);
            if (!partial) {
              throw new Error(`Partial "${partialName}" not found`);
            }
            return this.render(partial, data);
          });
          return result;
        };
      }
      /**
       * Get nested value from object
       */
      getNestedValue(obj, path) {
        const keys = path.split(".");
        let value = obj;
        for (const key of keys) {
          if (value && typeof value === "object" && key in value) {
            value = value[key];
          } else {
            return void 0;
          }
        }
        return value;
      }
      /**
       * Escape HTML content
       */
      escapeHtml(str) {
        if (!str) return "";
        return str.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
      }
      /**
       * Register built-in helpers
       */
      registerBuiltinHelpers() {
        this.registerHelper("if", (condition, content) => {
          return condition ? content : "";
        });
        this.registerHelper("each", (items, content, data) => {
          if (!Array.isArray(items)) {
            return "";
          }
          return items.map((item, index) => {
            const itemData = { ...data, this: item, "@index": index };
            return this.render(content, itemData);
          }).join("");
        });
        this.registerHelper("eq", (a, b) => {
          return a === b;
        });
        this.registerHelper("escape", (str) => {
          return this.escapeHtml(str);
        });
        this.registerHelper("json", (obj) => {
          return JSON.stringify(obj);
        });
        this.registerHelper("uppercase", (str) => {
          return String(str).toUpperCase();
        });
        this.registerHelper("lowercase", (str) => {
          return String(str).toLowerCase();
        });
        this.registerHelper("titlecase", (str) => {
          return String(str).replace(/\w\S*/g, (txt) => txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase());
        });
        this.registerHelper("truncate", (str, length = 50) => {
          const text = String(str);
          return text.length > length ? text.substring(0, length) + "..." : text;
        });
        this.registerHelper("default", (value, defaultValue) => {
          return value !== void 0 && value !== null ? value : defaultValue;
        });
      }
      /**
       * Get cache key for template
       */
      getCacheKey(template) {
        let hash = 0;
        for (let i = 0; i < template.length; i++) {
          const char = template.charCodeAt(i);
          hash = (hash << 5) - hash + char;
          hash = hash & hash;
        }
        return `template_${hash}`;
      }
    };
    globalTemplateEngine = null;
  }
});

// src/utils/plugin-theme-registry.ts
var plugin_theme_registry_exports = {};
chunkG7VZBCD6_cjs.__export(plugin_theme_registry_exports, {
  PluginThemeRegistry: () => exports.PluginThemeRegistry,
  getPluginThemeRegistry: () => getPluginThemeRegistry,
  initializePluginThemeRegistry: () => initializePluginThemeRegistry
});
function getPluginThemeRegistry(themeManager) {
  if (!globalPluginThemeRegistry) {
    const manager = themeManager || (init_theme_manager(), chunkG7VZBCD6_cjs.__toCommonJS(theme_manager_exports)).getThemeManager();
    globalPluginThemeRegistry = new exports.PluginThemeRegistry(manager);
  }
  return globalPluginThemeRegistry;
}
function initializePluginThemeRegistry() {
  getPluginThemeRegistry();
}
exports.PluginThemeRegistry = void 0; var globalPluginThemeRegistry;
var init_plugin_theme_registry = chunkG7VZBCD6_cjs.__esm({
  "src/utils/plugin-theme-registry.ts"() {
    exports.PluginThemeRegistry = class {
      pluginThemes = /* @__PURE__ */ new Map();
      themeManager;
      themeAssets = /* @__PURE__ */ new Map();
      constructor(themeManager) {
        this.themeManager = themeManager;
      }
      /**
       * Register a plugin theme
       */
      registerTheme(pluginName, theme) {
        if (!this.pluginThemes.has(pluginName)) {
          this.pluginThemes.set(pluginName, /* @__PURE__ */ new Map());
        }
        this.pluginThemes.get(pluginName).set(theme.name, theme);
        const themeConfig = {
          name: `${pluginName}:${theme.name}`,
          version: theme.version,
          description: theme.description,
          author: theme.author,
          variables: theme.variables || {},
          stylesheets: theme.stylesheets || /* @__PURE__ */ new Map(),
          assets: theme.assets || /* @__PURE__ */ new Map()
        };
        this.themeManager.registerTheme(themeConfig);
        if (theme.assets && theme.assets.size > 0) {
          const assetMap = /* @__PURE__ */ new Map();
          for (const [name, data] of theme.assets) {
            assetMap.set(name, {
              name,
              data,
              mimeType: this.getMimeType(name)
            });
          }
          this.themeAssets.set(`${pluginName}:${theme.name}`, assetMap);
        }
      }
      /**
       * Get plugin theme
       */
      getTheme(pluginName, themeName) {
        return this.pluginThemes.get(pluginName)?.get(themeName) || null;
      }
      /**
       * Get all themes for a plugin
       */
      getPluginThemes(pluginName) {
        const themes = this.pluginThemes.get(pluginName);
        return themes ? Array.from(themes.values()) : [];
      }
      /**
       * Get all plugin themes
       */
      getAllPluginThemes() {
        const result = /* @__PURE__ */ new Map();
        for (const [pluginName, themes] of this.pluginThemes) {
          result.set(pluginName, Array.from(themes.values()));
        }
        return result;
      }
      /**
       * Switch to a plugin theme
       */
      switchToPluginTheme(pluginName, themeName) {
        const theme = this.getTheme(pluginName, themeName);
        if (!theme) {
          throw new Error(`Plugin theme not found: ${pluginName}:${themeName}`);
        }
        const fullThemeName = `${pluginName}:${themeName}`;
        this.themeManager.switchTheme(fullThemeName);
      }
      /**
       * Get theme asset
       */
      getThemeAsset(pluginName, themeName, assetName) {
        const fullThemeName = `${pluginName}:${themeName}`;
        return this.themeAssets.get(fullThemeName)?.get(assetName) || null;
      }
      /**
       * Get all theme assets
       */
      getThemeAssets(pluginName, themeName) {
        const fullThemeName = `${pluginName}:${themeName}`;
        return this.themeAssets.get(fullThemeName) || /* @__PURE__ */ new Map();
      }
      /**
       * Add theme asset
       */
      addThemeAsset(pluginName, themeName, assetName, data, mimeType) {
        const fullThemeName = `${pluginName}:${themeName}`;
        if (!this.themeAssets.has(fullThemeName)) {
          this.themeAssets.set(fullThemeName, /* @__PURE__ */ new Map());
        }
        this.themeAssets.get(fullThemeName).set(assetName, {
          name: assetName,
          data,
          mimeType: mimeType || this.getMimeType(assetName)
        });
        this.themeManager.addThemeAsset(fullThemeName, assetName, data);
      }
      /**
       * Update theme CSS variables
       */
      updateThemeVariables(pluginName, themeName, variables) {
        const theme = this.getTheme(pluginName, themeName);
        if (!theme) {
          throw new Error(`Plugin theme not found: ${pluginName}:${themeName}`);
        }
        theme.variables = { ...theme.variables, ...variables };
        this.themeManager.updateCSSVariables(variables);
      }
      /**
       * List all registered plugins with themes
       */
      listPlugins() {
        return Array.from(this.pluginThemes.keys());
      }
      /**
       * Unregister plugin themes
       */
      unregisterPlugin(pluginName) {
        const themes = this.pluginThemes.get(pluginName);
        if (themes) {
          for (const themeName of themes.keys()) {
            const fullThemeName = `${pluginName}:${themeName}`;
            this.themeAssets.delete(fullThemeName);
          }
        }
        this.pluginThemes.delete(pluginName);
      }
      /**
       * Get MIME type for asset
       */
      getMimeType(filename) {
        const ext = filename.split(".").pop()?.toLowerCase();
        const mimeTypes = {
          "png": "image/png",
          "jpg": "image/jpeg",
          "jpeg": "image/jpeg",
          "gif": "image/gif",
          "svg": "image/svg+xml",
          "webp": "image/webp",
          "woff": "font/woff",
          "woff2": "font/woff2",
          "ttf": "font/ttf",
          "otf": "font/otf",
          "eot": "application/vnd.ms-fontobject",
          "css": "text/css",
          "js": "application/javascript",
          "json": "application/json"
        };
        return mimeTypes[ext || ""] || "application/octet-stream";
      }
    };
    globalPluginThemeRegistry = null;
  }
});

// src/templates/filter-bar.template.ts
function renderFilterBar(data) {
  return `
    <div class="rounded-xl bg-white dark:bg-zinc-900 shadow-sm ring-1 ring-zinc-950/5 dark:ring-white/10 p-6 mb-6">
      <form id="filter-form" class="flex flex-wrap gap-4 items-center">
        ${data.filters.map((filter) => `
          <div class="flex items-center space-x-2">
            <label class="text-sm font-medium text-zinc-500 dark:text-zinc-400">${filter.label}:</label>
            <select
              name="${filter.name}"
              class="rounded-lg bg-white dark:bg-zinc-800 px-3 py-2 text-sm text-zinc-950 dark:text-white ring-1 ring-inset ring-zinc-950/10 dark:ring-white/10 focus:ring-2 focus:ring-blue-600 dark:focus:ring-blue-500 focus:outline-none transition-colors"
              onchange="updateFilters()"
            >
              ${filter.options.map((option) => `
                <option value="${option.value}" ${option.selected ? "selected" : ""}>
                  ${option.label}
                </option>
              `).join("")}
            </select>
          </div>
        `).join("")}

        ${data.actions && data.actions.length > 0 ? `
          <div class="flex items-center space-x-2 ml-auto">
            ${data.actions.map((action) => `
              <button
                type="button"
                class="inline-flex items-center rounded-lg bg-white dark:bg-zinc-800 px-3 py-2 text-sm font-semibold text-zinc-950 dark:text-white ring-1 ring-inset ring-zinc-950/10 dark:ring-white/10 hover:bg-zinc-50 dark:hover:bg-zinc-700 transition-colors"
                ${action.onclick ? `onclick="${action.onclick}"` : ""}
                ${action.hxGet ? `hx-get="${action.hxGet}"` : ""}
                ${action.hxTarget ? `hx-target="${action.hxTarget}"` : ""}
              >
                ${action.label}
              </button>
            `).join("")}
          </div>
        ` : ""}
      </form>

      <script>
        function updateFilters() {
          const form = document.getElementById('filter-form');
          const formData = new FormData(form);
          const params = new URLSearchParams(window.location.search);

          // Update params with form values
          for (const [key, value] of formData.entries()) {
            if (value) {
              params.set(key, value);
            } else {
              params.delete(key);
            }
          }

          // Reset to page 1 when filters change
          params.set('page', '1');

          // Update URL and reload
          window.location.href = window.location.pathname + '?' + params.toString();
        }
      </script>
    </div>
  `;
}

// src/templates/index.ts
chunkAPBYI7AY_cjs.init_admin_layout_catalyst_template();

// src/templates/layouts/safe-admin-layout.ts
init_safe_template_renderer();
chunkAPBYI7AY_cjs.init_admin_layout_catalyst_template();
function renderSafeAdminLayoutCatalyst(data) {
  return exports.SafeTemplateRenderer.renderAdminLayout(
    chunkAPBYI7AY_cjs.renderAdminLayoutCatalyst,
    data,
    "admin-layout-catalyst"
  );
}
function renderSafeAdminLayout(data) {
  return exports.SafeTemplateRenderer.renderAdminLayout(
    chunkAPBYI7AY_cjs.renderAdminLayout,
    data,
    "admin-layout-v2"
  );
}
function renderSafePageContent(pageRenderer, data, pageName) {
  return exports.SafeTemplateRenderer.renderPageContent(pageRenderer, data, pageName);
}
function renderSafeComponent(componentRenderer, data, componentName) {
  return exports.SafeTemplateRenderer.renderComponent(componentRenderer, data, componentName);
}
var TemplateMonitoring = class {
  /**
   * Get template error statistics
   */
  static getErrorStats() {
    const { TemplateErrorHandler: TemplateErrorHandler2 } = (init_template_error_handler(), chunkG7VZBCD6_cjs.__toCommonJS(template_error_handler_exports));
    return TemplateErrorHandler2.getErrorStats();
  }
  /**
   * Get recent template errors
   */
  static getRecentErrors() {
    const { TemplateErrorHandler: TemplateErrorHandler2 } = (init_template_error_handler(), chunkG7VZBCD6_cjs.__toCommonJS(template_error_handler_exports));
    return TemplateErrorHandler2.getErrorLog().slice(-10);
  }
  /**
   * Clear error log
   */
  static clearErrors() {
    const { TemplateErrorHandler: TemplateErrorHandler2 } = (init_template_error_handler(), chunkG7VZBCD6_cjs.__toCommonJS(template_error_handler_exports));
    TemplateErrorHandler2.clearErrorLog();
  }
  /**
   * Generate error report for admin dashboard
   */
  static generateErrorReport() {
    const stats = this.getErrorStats();
    this.getRecentErrors();
    const recommendations = [];
    if (stats.recentErrors > 5) {
      recommendations.push("High number of recent template errors detected. Consider reviewing template code.");
    }
    if (stats.commonErrors.some((error) => error.includes("nested quotes"))) {
      recommendations.push("Nested quote issues detected in onclick handlers. Use proper escaping.");
    }
    if (stats.commonErrors.some((error) => error.includes("innerHTML"))) {
      recommendations.push("Unsafe innerHTML usage detected. Consider using template engine.");
    }
    return {
      summary: `${stats.totalErrors} total errors, ${stats.recentErrors} in the last hour`,
      recentErrors: stats.recentErrors,
      commonIssues: stats.commonErrors,
      recommendations
    };
  }
};
function initializeTemplateMonitoring() {
  const { setupGlobalTemplateErrorHandling: setupGlobalTemplateErrorHandling2 } = (init_safe_template_renderer(), chunkG7VZBCD6_cjs.__toCommonJS(safe_template_renderer_exports));
  setupGlobalTemplateErrorHandling2();
  console.log("[TEMPLATE] Error monitoring initialized");
}

// src/templates/index.ts
init_template_error_handler();
init_safe_template_renderer();

// src/utils/template-validator.ts
var TemplateValidator = class {
  /**
   * Validate template string for common syntax errors
   */
  static validate(template, filename) {
    const errors = [];
    const warnings = [];
    const nestedQuotePattern = /`[^`]*onclick\s*=\s*["'][^"']*\$\{[^}]*\}[^"']*["'][^`]*`/g;
    const nestedQuoteMatches = template.match(nestedQuotePattern);
    if (nestedQuoteMatches) {
      errors.push(`Nested quotes in template literal with variable interpolation detected. This will cause JavaScript syntax errors.`);
      nestedQuoteMatches.forEach((match, index) => {
        errors.push(`  Match ${index + 1}: ${match.substring(0, 100)}${match.length > 100 ? "..." : ""}`);
      });
    }
    const unescapedQuotePattern = /onclick\s*=\s*["'][^"']*'[^"']*\$\{[^}]*\}[^"']*'[^"']*["']/g;
    const unescapedQuoteMatches = template.match(unescapedQuotePattern);
    if (unescapedQuoteMatches) {
      errors.push(`Unescaped quotes in onclick handlers detected.`);
      unescapedQuoteMatches.forEach((match, index) => {
        errors.push(`  Match ${index + 1}: ${match}`);
      });
    }
    const innerHTMLPattern = /\.innerHTML\s*=\s*`[^`]*\$\{[^}]*\}[^`]*`/g;
    const innerHTMLMatches = template.match(innerHTMLPattern);
    if (innerHTMLMatches) {
      warnings.push(`innerHTML assignment with template literals detected. Consider using template engine for better security.`);
      innerHTMLMatches.forEach((match, index) => {
        warnings.push(`  Match ${index + 1}: ${match.substring(0, 100)}${match.length > 100 ? "..." : ""}`);
      });
    }
    const concatenationPattern = /\.map\([^)]*=>\s*`[^`]*\$\{[^}]*\}[^`]*`\s*\)\.join\(/g;
    const concatenationMatches = template.match(concatenationPattern);
    if (concatenationMatches) {
      warnings.push(`Manual string concatenation with .map().join() detected. Consider using template engine.`);
    }
    const xssPattern = /\$\{[^}]*\}/g;
    const xssMatches = template.match(xssPattern);
    if (xssMatches && xssMatches.length > 5) {
      warnings.push(`High number of variable interpolations (${xssMatches.length}) detected. Ensure proper escaping.`);
    }
    return {
      valid: errors.length === 0,
      errors,
      warnings
    };
  }
  /**
   * Fix common template syntax errors
   */
  static fixCommonErrors(template) {
    let fixed = template;
    fixed = fixed.replace(
      /onclick\s*=\s*"([^"]*)'([^']*\$\{[^}]*\}[^']*)'([^"]*)"/g,
      `onclick="$1\\'$2\\'$3"`
    );
    fixed = fixed.replace(
      /onclick\s*=\s*'([^']*)"([^"]*\$\{[^}]*\}[^"]*)"([^']*)'/g,
      `onclick='$1\\"$2\\"$3'`
    );
    return fixed;
  }
  /**
   * Escape quotes in template strings
   */
  static escapeQuotes(str) {
    return str.replace(/'/g, "\\'").replace(/"/g, '\\"');
  }
  /**
   * Generate safe onclick handler
   */
  static generateSafeOnClick(functionName, ...args) {
    const escapedArgs = args.map((arg) => `'${this.escapeQuotes(arg)}'`).join(", ");
    return `onclick="${functionName}(${escapedArgs})"`;
  }
};

// src/templates/semantic-template.ts
function escapeHtml(str) {
  if (!str) return "";
  return str.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
}
var SemanticTemplates = {
  /**
   * Page header component
   */
  pageHeader: (title, subtitle) => {
    return `
      <header data-component="page-header">
        <h1 data-element="title">${escapeHtml(title)}</h1>
        ${subtitle ? `<p data-element="subtitle">${escapeHtml(subtitle)}</p>` : ""}
      </header>
    `;
  },
  /**
   * Card component
   */
  card: (content, status) => {
    return `
      <article data-component="card" ${status ? `data-status="${escapeHtml(status)}"` : ""}>
        ${content}
      </article>
    `;
  },
  /**
   * Badge/status indicator
   */
  badge: (text, status) => {
    return `
      <span data-component="badge" data-status="${escapeHtml(status)}">
        ${escapeHtml(text)}
      </span>
    `;
  },
  /**
   * Button component
   */
  button: (text, action, id) => {
    return `
      <button data-component="button" data-action="${escapeHtml(action)}" ${id ? `data-id="${escapeHtml(id)}"` : ""}>
        ${escapeHtml(text)}
      </button>
    `;
  },
  /**
   * Form input
   */
  input: (type, name, value, placeholder) => {
    return `
      <input 
        data-component="input" 
        data-type="${escapeHtml(type)}"
        name="${escapeHtml(name)}"
        ${value ? `value="${escapeHtml(value)}"` : ""}
        ${placeholder ? `placeholder="${escapeHtml(placeholder)}"` : ""}
      />
    `;
  },
  /**
   * Form label
   */
  label: (text, htmlFor) => {
    return `
      <label data-component="label" for="${escapeHtml(htmlFor)}">
        ${escapeHtml(text)}
      </label>
    `;
  },
  /**
   * Table component
   */
  table: (headers, rows) => {
    const headerRow = headers.map((h) => `<th data-element="header">${escapeHtml(h)}</th>`).join("");
    const bodyRows = rows.map((row) => `
        <tr data-element="row">
          ${row.map((cell) => `<td data-element="cell">${escapeHtml(cell)}</td>`).join("")}
        </tr>
      `).join("");
    return `
      <table data-component="table">
        <thead>
          <tr>${headerRow}</tr>
        </thead>
        <tbody>
          ${bodyRows}
        </tbody>
      </table>
    `;
  },
  /**
   * List component
   */
  list: (items, ordered = false) => {
    const tag = ordered ? "ol" : "ul";
    const itemsHtml = items.map((item) => `<li data-element="item">${escapeHtml(item)}</li>`).join("");
    return `
      <${tag} data-component="list">
        ${itemsHtml}
      </${tag}>
    `;
  },
  /**
   * Alert/notification component
   */
  alert: (message, type) => {
    return `
      <div data-component="alert" data-type="${escapeHtml(type)}" role="alert">
        <p data-element="message">${escapeHtml(message)}</p>
      </div>
    `;
  },
  /**
   * Modal/dialog component
   */
  modal: (title, content, id) => {
    return `
      <dialog data-component="modal" id="${escapeHtml(id)}">
        <header data-element="header">
          <h2 data-element="title">${escapeHtml(title)}</h2>
        </header>
        <div data-element="content">
          ${content}
        </div>
        <footer data-element="footer">
          <button data-action="close" data-modal-id="${escapeHtml(id)}">Close</button>
        </footer>
      </dialog>
    `;
  },
  /**
   * Tabs component
   */
  tabs: (tabs) => {
    const tabButtons = tabs.map((tab) => `
        <button data-component="tab-button" data-tab-id="${escapeHtml(tab.id)}">
          ${escapeHtml(tab.label)}
        </button>
      `).join("");
    const tabPanels = tabs.map((tab) => `
        <div data-component="tab-panel" data-tab-id="${escapeHtml(tab.id)}">
          ${tab.content}
        </div>
      `).join("");
    return `
      <div data-component="tabs">
        <div data-element="tab-buttons">
          ${tabButtons}
        </div>
        <div data-element="tab-panels">
          ${tabPanels}
        </div>
      </div>
    `;
  },
  /**
   * Grid layout
   */
  grid: (items, columns) => {
    return `
      <div data-component="grid" ${columns ? `data-columns="${columns}"` : ""}>
        ${items.map((item) => `<div data-element="grid-item">${item}</div>`).join("")}
      </div>
    `;
  },
  /**
   * Flex layout
   */
  flex: (items, direction) => {
    return `
      <div data-component="flex" ${direction ? `data-direction="${direction}"` : ""}>
        ${items.map((item) => `<div data-element="flex-item">${item}</div>`).join("")}
      </div>
    `;
  },
  /**
   * Section component
   */
  section: (title, content) => {
    return `
      <section data-component="section">
        <h2 data-element="title">${escapeHtml(title)}</h2>
        <div data-element="content">
          ${content}
        </div>
      </section>
    `;
  },
  /**
   * Sidebar layout
   */
  sidebarLayout: (sidebar, main) => {
    return `
      <div data-component="sidebar-layout">
        <aside data-element="sidebar">
          ${sidebar}
        </aside>
        <main data-element="main">
          ${main}
        </main>
      </div>
    `;
  },
  /**
   * Navigation component
   */
  navigation: (items) => {
    return `
      <nav data-component="navigation">
        <ul data-element="nav-list">
          ${items.map((item) => `
              <li data-element="nav-item" ${item.active ? 'data-active="true"' : ""}>
                <a href="${escapeHtml(item.href)}" data-element="nav-link">
                  ${escapeHtml(item.label)}
                </a>
              </li>
            `).join("")}
        </ul>
      </nav>
    `;
  },
  /**
   * Breadcrumb component
   */
  breadcrumb: (items) => {
    return `
      <nav data-component="breadcrumb" aria-label="Breadcrumb">
        <ol data-element="breadcrumb-list">
          ${items.map((item, index) => `
              <li data-element="breadcrumb-item">
                ${item.href ? `<a href="${escapeHtml(item.href)}">${escapeHtml(item.label)}</a>` : escapeHtml(item.label)}
                ${index < items.length - 1 ? '<span data-element="separator">/</span>' : ""}
              </li>
            `).join("")}
        </ol>
      </nav>
    `;
  },
  /**
   * Pagination component
   */
  pagination: (currentPage, totalPages) => {
    return `
      <nav data-component="pagination" aria-label="Pagination">
        <ul data-element="pagination-list">
          ${currentPage > 1 ? `<li><button data-action="prev-page" data-page="${currentPage - 1}">Previous</button></li>` : ""}
          ${Array.from({ length: totalPages }, (_, i) => i + 1).map((page) => `
              <li>
                <button data-action="goto-page" data-page="${page}" ${page === currentPage ? 'data-active="true"' : ""}>
                  ${page}
                </button>
              </li>
            `).join("")}
          ${currentPage < totalPages ? `<li><button data-action="next-page" data-page="${currentPage + 1}">Next</button></li>` : ""}
        </ul>
      </nav>
    `;
  },
  /**
   * Form component
   */
  form: (fields, submitText = "Submit") => {
    return `
      <form data-component="form">
        ${fields.map((field) => `
            <div data-element="form-group">
              ${SemanticTemplates.label(field.label, field.name)}
              ${SemanticTemplates.input(field.type, field.name, void 0, field.label)}
              ${field.required ? '<span data-element="required">*</span>' : ""}
            </div>
          `).join("")}
        <button type="submit" data-action="submit">
          ${escapeHtml(submitText)}
        </button>
      </form>
    `;
  }
};
function validateSemanticTemplate(template) {
  const errors = [];
  if (/class\s*=\s*["'][^"']*["']/i.test(template)) {
    errors.push("Template contains hardcoded CSS classes");
  }
  if (/style\s*=\s*["'][^"']*["']/i.test(template)) {
    errors.push("Template contains inline styles");
  }
  if (/(bg-|text-|p-|m-|flex|grid|rounded|shadow|border|ring|dark:)/i.test(template)) {
    errors.push("Template contains Tailwind CSS classes");
  }
  if (/(container|row|col-|btn|alert|card|modal|navbar)/i.test(template)) {
    errors.push("Template contains Bootstrap CSS classes");
  }
  return {
    valid: errors.length === 0,
    errors
  };
}
function toSemanticTemplate(template) {
  let semantic = template;
  semantic = semantic.replace(/\s+class\s*=\s*["'][^"']*["']/gi, "");
  semantic = semantic.replace(/\s+style\s*=\s*["'][^"']*["']/gi, "");
  semantic = semantic.replace(/<div>/gi, '<div data-component="container">');
  semantic = semantic.replace(/<section>/gi, '<section data-component="section">');
  semantic = semantic.replace(/<article>/gi, '<article data-component="article">');
  return semantic;
}

// src/templates/index.ts
init_theme_manager();

// src/utils/theme-loader.ts
init_theme_manager();
var ThemeLoader = class {
  manager;
  loadedThemes = /* @__PURE__ */ new Set();
  constructor(manager) {
    this.manager = manager;
  }
  /**
   * Load theme from manifest and CSS files
   */
  async loadTheme(themeName, manifest, cssFiles, assets) {
    const stylesheets = /* @__PURE__ */ new Map();
    for (const [name, css] of Object.entries(cssFiles)) {
      stylesheets.set(name, css);
    }
    const assetsMap = /* @__PURE__ */ new Map();
    if (assets) {
      for (const [name, buffer] of Object.entries(assets)) {
        assetsMap.set(name, buffer);
      }
    }
    const theme = exports.ThemeManager.createThemeFromManifest(manifest, stylesheets, assetsMap);
    this.manager.registerTheme(theme);
    this.loadedThemes.add(themeName);
  }
  /**
   * Load default theme with CSS files
   */
  async loadDefaultTheme(variablesCss, componentsCss) {
    const stylesheets = /* @__PURE__ */ new Map();
    stylesheets.set("variables", variablesCss);
    stylesheets.set("components", componentsCss);
    const defaultTheme = {
      name: "default",
      version: "1.0.0",
      description: "CF-CMS Default Theme",
      author: "CF-CMS Team",
      variables: {
        // Colors
        "color-primary": "#3b82f6",
        "color-primary-dark": "#2563eb",
        "color-primary-light": "#60a5fa",
        "color-primary-alpha": "rgba(59, 130, 246, 0.1)",
        "color-success": "#10b981",
        "color-success-dark": "#059669",
        "color-success-light": "#6ee7b7",
        "color-success-bg": "#d1fae5",
        "color-warning": "#f59e0b",
        "color-warning-dark": "#d97706",
        "color-warning-light": "#fbbf24",
        "color-warning-bg": "#fef3c7",
        "color-error": "#ef4444",
        "color-error-dark": "#dc2626",
        "color-error-light": "#f87171",
        "color-error-bg": "#fee2e2",
        "color-info": "#0ea5e9",
        "color-info-dark": "#0284c7",
        "color-info-light": "#38bdf8",
        "color-info-bg": "#cffafe",
        "color-surface": "#ffffff",
        "color-surface-secondary": "#f9fafb",
        "color-surface-tertiary": "#f3f4f6",
        "color-surface-hover": "#f0f1f3",
        "color-border": "#e5e7eb",
        "color-border-light": "#f3f4f6",
        "color-border-dark": "#d1d5db",
        "color-text-primary": "#111827",
        "color-text-secondary": "#6b7280",
        "color-text-tertiary": "#9ca3af",
        "color-text-disabled": "#d1d5db",
        "color-text-inverse": "#ffffff",
        // Typography
        "font-family": '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',
        "font-family-mono": '"Menlo", "Monaco", "Courier New", monospace',
        "font-size-xs": "0.75rem",
        "font-size-sm": "0.875rem",
        "font-size-base": "1rem",
        "font-size-lg": "1.125rem",
        "font-size-xl": "1.25rem",
        "font-size-2xl": "1.5rem",
        "font-size-3xl": "1.875rem",
        "font-size-4xl": "2.25rem",
        "font-weight-light": "300",
        "font-weight-normal": "400",
        "font-weight-medium": "500",
        "font-weight-semibold": "600",
        "font-weight-bold": "700",
        "line-height-tight": "1.25",
        "line-height-normal": "1.5",
        "line-height-relaxed": "1.75",
        // Spacing
        "spacing-xs": "0.25rem",
        "spacing-sm": "0.5rem",
        "spacing-md": "1rem",
        "spacing-lg": "1.5rem",
        "spacing-xl": "2rem",
        "spacing-2xl": "3rem",
        "spacing-3xl": "4rem",
        // Border Radius
        "radius-sm": "0.375rem",
        "radius-md": "0.5rem",
        "radius-lg": "0.75rem",
        "radius-xl": "1rem",
        "radius-full": "9999px",
        // Shadows
        "shadow-sm": "0 1px 2px 0 rgba(0, 0, 0, 0.05)",
        "shadow-md": "0 4px 6px -1px rgba(0, 0, 0, 0.1)",
        "shadow-lg": "0 10px 15px -3px rgba(0, 0, 0, 0.1)",
        "shadow-xl": "0 20px 25px -5px rgba(0, 0, 0, 0.1)",
        // Transitions
        "transition-fast": "150ms ease-in-out",
        "transition-normal": "200ms ease-in-out",
        "transition-slow": "300ms ease-in-out",
        // Z-Index
        "z-dropdown": "1000",
        "z-sticky": "1020",
        "z-fixed": "1030",
        "z-modal-backdrop": "1040",
        "z-modal": "1050",
        "z-popover": "1060",
        "z-tooltip": "1070"
      },
      stylesheets,
      assets: /* @__PURE__ */ new Map()
    };
    this.manager.registerTheme(defaultTheme);
    this.loadedThemes.add("default");
  }
  /**
   * Check if theme is loaded
   */
  isThemeLoaded(themeName) {
    return this.loadedThemes.has(themeName);
  }
  /**
   * Get loaded themes
   */
  getLoadedThemes() {
    return Array.from(this.loadedThemes);
  }
};
function createThemeLoader(manager) {
  return new ThemeLoader(manager);
}

// src/utils/theme-customizer.ts
var ThemeCustomizer = class {
  manager;
  customizations = /* @__PURE__ */ new Map();
  persistToStorage;
  storageKey;
  constructor(manager, options) {
    this.manager = manager;
    this.persistToStorage = options?.persistToStorage ?? false;
    this.storageKey = options?.storageKey ?? "cf-cms-theme-customizations";
  }
  /**
   * Customize a theme
   */
  customizeTheme(themeName, variables) {
    const customization = {
      themeName,
      variables,
      timestamp: Date.now()
    };
    this.customizations.set(themeName, customization);
    if (this.manager.getActiveTheme() === themeName) {
      this.manager.updateCSSVariables(variables);
    }
    if (this.persistToStorage) {
      this.persistCustomizations();
    }
  }
  /**
   * Update specific CSS variable
   */
  updateVariable(themeName, variableName, value) {
    const customization = this.customizations.get(themeName) || {
      themeName,
      variables: {},
      timestamp: Date.now()
    };
    customization.variables[variableName] = value;
    this.customizations.set(themeName, customization);
    if (this.manager.getActiveTheme() === themeName) {
      this.manager.setCSSVariable(variableName, value);
    }
    if (this.persistToStorage) {
      this.persistCustomizations();
    }
  }
  /**
   * Get customization for theme
   */
  getCustomization(themeName) {
    return this.customizations.get(themeName);
  }
  /**
   * Get all customizations
   */
  getAllCustomizations() {
    return Array.from(this.customizations.values());
  }
  /**
   * Reset customization for theme
   */
  resetCustomization(themeName) {
    this.customizations.delete(themeName);
    if (this.manager.getActiveTheme() === themeName) {
      const theme = this.manager.getTheme(themeName);
      if (theme) {
        this.manager.switchTheme(themeName);
      }
    }
    if (this.persistToStorage) {
      this.persistCustomizations();
    }
  }
  /**
   * Reset all customizations
   */
  resetAllCustomizations() {
    this.customizations.clear();
    const activeTheme = this.manager.getActiveTheme();
    const theme = this.manager.getTheme(activeTheme);
    if (theme) {
      this.manager.switchTheme(activeTheme);
    }
    if (this.persistToStorage) {
      this.persistCustomizations();
    }
  }
  /**
   * Export customization as JSON
   */
  exportCustomization(themeName) {
    const customization = this.customizations.get(themeName);
    if (!customization) {
      return "{}";
    }
    return JSON.stringify(customization, null, 2);
  }
  /**
   * Import customization from JSON
   */
  importCustomization(themeName, json) {
    try {
      const customization = JSON.parse(json);
      if (customization.variables && typeof customization.variables === "object") {
        this.customizeTheme(themeName, customization.variables);
      }
    } catch (error) {
      console.error("Failed to import customization:", error);
    }
  }
  /**
   * Persist customizations to storage
   */
  persistCustomizations() {
    if (typeof localStorage === "undefined") {
      return;
    }
    try {
      const data = Array.from(this.customizations.values());
      localStorage.setItem(this.storageKey, JSON.stringify(data));
    } catch (error) {
      console.error("Failed to persist customizations:", error);
    }
  }
  /**
   * Load customizations from storage
   */
  loadCustomizations() {
    if (typeof localStorage === "undefined") {
      return;
    }
    try {
      const data = localStorage.getItem(this.storageKey);
      if (data) {
        const customizations = JSON.parse(data);
        for (const customization of customizations) {
          this.customizations.set(customization.themeName, customization);
        }
      }
    } catch (error) {
      console.error("Failed to load customizations:", error);
    }
  }
  /**
   * Clear storage
   */
  clearStorage() {
    if (typeof localStorage === "undefined") {
      return;
    }
    try {
      localStorage.removeItem(this.storageKey);
    } catch (error) {
      console.error("Failed to clear storage:", error);
    }
  }
};
function createThemeCustomizer(manager, options) {
  return new ThemeCustomizer(manager, options);
}

// src/utils/theme-registry.ts
var ThemeRegistry = class {
  manager;
  loader;
  customizer;
  themeMetadata = /* @__PURE__ */ new Map();
  constructor(manager, customizationOptions) {
    this.manager = manager;
    this.loader = new ThemeLoader(manager);
    this.customizer = new ThemeCustomizer(manager, customizationOptions);
  }
  /**
   * Register theme metadata
   */
  registerThemeMetadata(themeName, metadata) {
    this.themeMetadata.set(themeName, metadata);
  }
  /**
   * Get theme info
   */
  getThemeInfo(themeName) {
    const theme = this.manager.getTheme(themeName);
    if (!theme) {
      return null;
    }
    const customization = this.customizer.getCustomization(themeName);
    const metadata = this.themeMetadata.get(themeName);
    return {
      name: theme.name,
      version: theme.version,
      description: theme.description,
      author: metadata?.author || theme.author,
      isActive: this.manager.getActiveTheme() === themeName,
      isCustomized: !!customization
    };
  }
  /**
   * List all themes
   */
  listThemes() {
    return this.manager.listThemes().map((name) => this.getThemeInfo(name)).filter(Boolean);
  }
  /**
   * Get active theme info
   */
  getActiveThemeInfo() {
    const activeTheme = this.manager.getActiveTheme();
    return this.getThemeInfo(activeTheme);
  }
  /**
   * Switch theme
   */
  switchTheme(themeName) {
    this.manager.switchTheme(themeName);
    const customization = this.customizer.getCustomization(themeName);
    if (customization) {
      this.manager.updateCSSVariables(customization.variables);
    }
  }
  /**
   * Get theme
   */
  getTheme(themeName) {
    return this.manager.getTheme(themeName);
  }
  /**
   * Register theme
   */
  registerTheme(theme, metadata) {
    this.manager.registerTheme(theme);
    if (metadata) {
      this.registerThemeMetadata(theme.name, metadata);
    }
  }
  /**
   * Load default theme
   */
  async loadDefaultTheme(variablesCss, componentsCss) {
    await this.loader.loadDefaultTheme(variablesCss, componentsCss);
  }
  /**
   * Load theme
   */
  async loadTheme(themeName, manifest, cssFiles, assets) {
    await this.loader.loadTheme(themeName, manifest, cssFiles, assets);
  }
  /**
   * Customize theme
   */
  customizeTheme(themeName, variables) {
    this.customizer.customizeTheme(themeName, variables);
  }
  /**
   * Update theme variable
   */
  updateVariable(themeName, variableName, value) {
    this.customizer.updateVariable(themeName, variableName, value);
  }
  /**
   * Reset theme customization
   */
  resetCustomization(themeName) {
    this.customizer.resetCustomization(themeName);
  }
  /**
   * Reset all customizations
   */
  resetAllCustomizations() {
    this.customizer.resetAllCustomizations();
  }
  /**
   * Export customization
   */
  exportCustomization(themeName) {
    return this.customizer.exportCustomization(themeName);
  }
  /**
   * Import customization
   */
  importCustomization(themeName, json) {
    this.customizer.importCustomization(themeName, json);
  }
  /**
   * Get CSS variable
   */
  getCSSVariable(name) {
    return this.manager.getCSSVariable(name);
  }
  /**
   * Set CSS variable
   */
  setCSSVariable(name, value) {
    this.manager.setCSSVariable(name, value);
  }
  /**
   * Get all CSS variables
   */
  getAllCSSVariables() {
    return this.manager.getAllCSSVariables();
  }
  /**
   * Get theme asset
   */
  getThemeAsset(themeName, assetName) {
    return this.manager.getThemeAsset(themeName, assetName);
  }
  /**
   * Get all theme assets
   */
  getThemeAssets(themeName) {
    return this.manager.getThemeAssets(themeName);
  }
  /**
   * Add theme asset
   */
  addThemeAsset(themeName, assetName, asset) {
    this.manager.addThemeAsset(themeName, assetName, asset);
  }
  /**
   * Load customizations from storage
   */
  loadCustomizations() {
    this.customizer.loadCustomizations();
  }
  /**
   * Clear customization storage
   */
  clearCustomizationStorage() {
    this.customizer.clearStorage();
  }
};
function createThemeRegistry(manager, customizationOptions) {
  return new ThemeRegistry(manager, customizationOptions);
}

// src/utils/theme-system.ts
init_theme_manager();
var ThemeSystem = class {
  manager;
  loader;
  customizer;
  registry;
  initialized = false;
  constructor(config) {
    this.manager = new exports.ThemeManager();
    this.loader = new ThemeLoader(this.manager);
    const customizationOptions = {
      persistToStorage: config?.persistCustomizations ?? false,
      storageKey: config?.customizationStorageKey ?? "cf-cms-theme-customizations"
    };
    this.customizer = new ThemeCustomizer(this.manager, customizationOptions);
    this.registry = new ThemeRegistry(this.manager, customizationOptions);
  }
  /**
   * Initialize theme system
   */
  async initialize(variablesCss, componentsCss) {
    if (this.initialized) {
      return;
    }
    this.manager.registerTheme(exports.DEFAULT_THEME);
    if (variablesCss && componentsCss) {
      await this.loader.loadDefaultTheme(variablesCss, componentsCss);
    }
    this.manager.switchTheme("default");
    if (typeof localStorage !== "undefined") {
      this.customizer.loadCustomizations();
    }
    this.initialized = true;
  }
  /**
   * Check if initialized
   */
  isInitialized() {
    return this.initialized;
  }
  /**
   * Get theme manager
   */
  getManager() {
    return this.manager;
  }
  /**
   * Get theme loader
   */
  getLoader() {
    return this.loader;
  }
  /**
   * Get theme customizer
   */
  getCustomizer() {
    return this.customizer;
  }
  /**
   * Get theme registry
   */
  getRegistry() {
    return this.registry;
  }
  /**
   * Switch theme
   */
  switchTheme(themeName) {
    this.registry.switchTheme(themeName);
  }
  /**
   * Get active theme
   */
  getActiveTheme() {
    return this.manager.getActiveTheme();
  }
  /**
   * List themes
   */
  listThemes() {
    return this.registry.listThemes();
  }
  /**
   * Customize theme
   */
  customizeTheme(themeName, variables) {
    this.registry.customizeTheme(themeName, variables);
  }
  /**
   * Update CSS variable
   */
  updateVariable(themeName, variableName, value) {
    this.registry.updateVariable(themeName, variableName, value);
  }
  /**
   * Get CSS variable
   */
  getCSSVariable(name) {
    return this.manager.getCSSVariable(name);
  }
  /**
   * Get all CSS variables
   */
  getAllCSSVariables() {
    return this.manager.getAllCSSVariables();
  }
  /**
   * Reset customization
   */
  resetCustomization(themeName) {
    this.registry.resetCustomization(themeName);
  }
  /**
   * Reset all customizations
   */
  resetAllCustomizations() {
    this.registry.resetAllCustomizations();
  }
  /**
   * Export customization
   */
  exportCustomization(themeName) {
    return this.registry.exportCustomization(themeName);
  }
  /**
   * Import customization
   */
  importCustomization(themeName, json) {
    this.registry.importCustomization(themeName, json);
  }
};
var globalThemeSystem = null;
function getThemeSystem(config) {
  if (!globalThemeSystem) {
    globalThemeSystem = new ThemeSystem(config);
  }
  return globalThemeSystem;
}
async function initializeThemeSystem2(config, variablesCss, componentsCss) {
  const system = getThemeSystem(config);
  await system.initialize(variablesCss, componentsCss);
  return system;
}
function resetThemeSystem() {
  globalThemeSystem = null;
}

// src/templates/index.ts
init_semantic_template_engine();

// src/utils/plugin-template-system.ts
var PluginTemplateSystem = class {
  templateEngine;
  pluginTemplates = /* @__PURE__ */ new Map();
  pluginThemes = /* @__PURE__ */ new Map();
  templateOverrides = /* @__PURE__ */ new Map();
  themeRegistry = null;
  constructor(templateEngine, themeRegistry) {
    this.templateEngine = templateEngine;
    this.themeRegistry = themeRegistry || null;
  }
  /**
   * Register plugin template
   */
  registerTemplate(pluginName, template) {
    if (!this.pluginTemplates.has(pluginName)) {
      this.pluginTemplates.set(pluginName, /* @__PURE__ */ new Map());
    }
    this.pluginTemplates.get(pluginName).set(template.name, template);
    this.templateEngine.registerPluginTemplate(pluginName, template.name, template.template);
    if (template.priority && template.priority > 0) {
      this.templateOverrides.set(template.name, `${pluginName}:${template.name}`);
    }
  }
  /**
   * Get plugin template
   */
  getTemplate(pluginName, templateName) {
    return this.pluginTemplates.get(pluginName)?.get(templateName) || null;
  }
  /**
   * Get all plugin templates for a plugin
   */
  getPluginTemplates(pluginName) {
    const templates = this.pluginTemplates.get(pluginName);
    return templates ? Array.from(templates.values()) : [];
  }
  /**
   * Check if template is overridden by plugin
   */
  isTemplateOverridden(templateName) {
    return this.templateOverrides.has(templateName);
  }
  /**
   * Get override for template
   */
  getTemplateOverride(templateName) {
    return this.templateOverrides.get(templateName) || null;
  }
  /**
   * Render plugin template
   */
  renderPluginTemplate(pluginName, templateName, data = {}) {
    const template = this.getTemplate(pluginName, templateName);
    if (!template) {
      throw new Error(`Plugin template not found: ${pluginName}:${templateName}`);
    }
    return this.templateEngine.render(template.template, data);
  }
  /**
   * Register plugin theme
   */
  registerTheme(pluginName, theme) {
    if (!this.pluginThemes.has(pluginName)) {
      this.pluginThemes.set(pluginName, []);
    }
    this.pluginThemes.get(pluginName).push(theme);
    this.pluginThemes.get(pluginName).sort((a, b) => (b.priority || 0) - (a.priority || 0));
    if (this.themeRegistry) {
      this.themeRegistry.registerTheme(pluginName, {
        name: theme.name,
        version: "1.0.0",
        description: theme.description || `${pluginName} theme`,
        variables: theme.variables,
        stylesheets: theme.stylesheets,
        assets: theme.assets,
        priority: theme.priority
      });
    }
  }
  /**
   * Get plugin themes
   */
  getThemes(pluginName) {
    return this.pluginThemes.get(pluginName) || [];
  }
  /**
   * Get all plugin themes
   */
  getAllThemes() {
    return new Map(this.pluginThemes);
  }
  /**
   * Get theme by name
   */
  getThemeByName(pluginName, themeName) {
    const themes = this.pluginThemes.get(pluginName);
    return themes?.find((t) => t.name === themeName) || null;
  }
  /**
   * Switch to plugin theme
   */
  switchToPluginTheme(pluginName, themeName) {
    if (!this.themeRegistry) {
      throw new Error("Theme registry not initialized");
    }
    const theme = this.getThemeByName(pluginName, themeName);
    if (!theme) {
      throw new Error(`Plugin theme not found: ${pluginName}:${themeName}`);
    }
    this.themeRegistry.switchToPluginTheme(pluginName, themeName);
  }
  /**
   * Add theme asset
   */
  addThemeAsset(pluginName, themeName, assetName, data, mimeType) {
    if (!this.themeRegistry) {
      throw new Error("Theme registry not initialized");
    }
    this.themeRegistry.addThemeAsset(pluginName, themeName, assetName, data, mimeType);
  }
  /**
   * Get theme asset
   */
  getThemeAsset(pluginName, themeName, assetName) {
    if (!this.themeRegistry) {
      return null;
    }
    const asset = this.themeRegistry.getThemeAsset(pluginName, themeName, assetName);
    return asset?.data || null;
  }
  /**
   * Set theme registry
   */
  setThemeRegistry(registry) {
    this.themeRegistry = registry;
  }
  /**
   * Register plugin partial template
   */
  registerPartial(pluginName, partialName, template) {
    const fullName = `${pluginName}:${partialName}`;
    this.templateEngine.registerPartial(fullName, template);
  }
  /**
   * List all registered plugins with templates
   */
  listPlugins() {
    return Array.from(this.pluginTemplates.keys());
  }
  /**
   * Unregister plugin templates
   */
  unregisterPlugin(pluginName) {
    this.pluginTemplates.delete(pluginName);
    this.pluginThemes.delete(pluginName);
    for (const [templateName, override] of this.templateOverrides) {
      if (override.startsWith(`${pluginName}:`)) {
        this.templateOverrides.delete(templateName);
      }
    }
  }
  /**
   * Get template engine
   */
  getTemplateEngine() {
    return this.templateEngine;
  }
};
var globalPluginTemplateSystem = null;
function getPluginTemplateSystem(templateEngine, themeRegistry) {
  if (!globalPluginTemplateSystem) {
    const engine = templateEngine || (init_semantic_template_engine(), chunkG7VZBCD6_cjs.__toCommonJS(semantic_template_engine_exports)).getTemplateEngine();
    const registry = themeRegistry || (init_plugin_theme_registry(), chunkG7VZBCD6_cjs.__toCommonJS(plugin_theme_registry_exports)).getPluginThemeRegistry();
    globalPluginTemplateSystem = new PluginTemplateSystem(engine, registry);
  }
  return globalPluginTemplateSystem;
}
function initializePluginTemplateSystem() {
  getPluginTemplateSystem();
}

// src/templates/index.ts
chunkAPBYI7AY_cjs.init_logo_template();

exports.PluginTemplateSystem = PluginTemplateSystem;
exports.SemanticTemplates = SemanticTemplates;
exports.TemplateMonitoring = TemplateMonitoring;
exports.TemplateValidator = TemplateValidator;
exports.ThemeCustomizer = ThemeCustomizer;
exports.ThemeLoader = ThemeLoader;
exports.ThemeRegistry = ThemeRegistry;
exports.ThemeSystem = ThemeSystem;
exports.createThemeCustomizer = createThemeCustomizer;
exports.createThemeLoader = createThemeLoader;
exports.createThemeRegistry = createThemeRegistry;
exports.escapeHtml = escapeHtml;
exports.getPluginTemplateSystem = getPluginTemplateSystem;
exports.getPluginThemeRegistry = getPluginThemeRegistry;
exports.getTemplateEngine = getTemplateEngine;
exports.getThemeManager = getThemeManager;
exports.getThemeSystem = getThemeSystem;
exports.init_plugin_theme_registry = init_plugin_theme_registry;
exports.init_semantic_template_engine = init_semantic_template_engine;
exports.init_theme_manager = init_theme_manager;
exports.initializePluginTemplateSystem = initializePluginTemplateSystem;
exports.initializePluginThemeRegistry = initializePluginThemeRegistry;
exports.initializeTemplateEngine = initializeTemplateEngine;
exports.initializeTemplateMonitoring = initializeTemplateMonitoring;
exports.initializeThemeSystem = initializeThemeSystem;
exports.initializeThemeSystem2 = initializeThemeSystem2;
exports.renderFilterBar = renderFilterBar;
exports.renderSafeAdminLayout = renderSafeAdminLayout;
exports.renderSafeAdminLayoutCatalyst = renderSafeAdminLayoutCatalyst;
exports.renderSafeComponent = renderSafeComponent;
exports.renderSafePageContent = renderSafePageContent;
exports.resetThemeSystem = resetThemeSystem;
exports.setupGlobalTemplateErrorHandling = setupGlobalTemplateErrorHandling;
exports.toSemanticTemplate = toSemanticTemplate;
exports.validateSemanticTemplate = validateSemanticTemplate;
exports.withErrorBoundary = withErrorBoundary;
//# sourceMappingURL=chunk-GYEXFEFU.cjs.map
//# sourceMappingURL=chunk-GYEXFEFU.cjs.map