const validationDebugger = {
  logEvent: (type, message, data) => {
    if (typeof console !== "undefined") {
      console.log(`[ValidationDebugger] ${type}: ${message}`, data);
    }
  }
};
class PerformanceOptimizer {
  static instance;
  config;
  metrics = /* @__PURE__ */ new Map();
  operationQueue = [];
  frameCounter = 0;
  lastBatchTime = 0;
  throttleTimers = /* @__PURE__ */ new Map();
  defaultConfig = {
    enabled: true,
    targetOverhead: 5,
    // 5% overhead target
    batchSize: 10,
    cacheStrategy: "moderate",
    asyncValidation: true,
    throttleMs: 16,
    // ~60fps
    skipFrames: 0
  };
  constructor(config = {}) {
    this.config = { ...this.defaultConfig, ...config };
  }
  static getInstance(config) {
    if (!this.instance) {
      this.instance = new PerformanceOptimizer(config);
    }
    return this.instance;
  }
  configure(config) {
    this.config = { ...this.config, ...config };
  }
  /**
   * Optimize a validation operation with smart batching and caching
   */
  optimizeValidation(key, operation, _skipCache = false) {
    if (!this.config.enabled) {
      return operation();
    }
    if (this.shouldSkipFrame()) {
      return operation();
    }
    if (this.isThrottled(key)) {
      return operation();
    }
    const startTime = performance.now();
    try {
      const result = operation();
      this.recordMetrics(key, performance.now() - startTime, true);
      return result;
    } catch (error) {
      this.recordMetrics(key, performance.now() - startTime, false);
      throw error;
    }
  }
  /**
   * Batch validation operations for better performance
   */
  batchValidations(operations) {
    if (!this.config.enabled) {
      operations.forEach((op) => op());
      return;
    }
    this.operationQueue.push(...operations);
    const now = Date.now();
    if (this.operationQueue.length >= this.config.batchSize || now - this.lastBatchTime > this.config.throttleMs) {
      this.processBatch();
      this.lastBatchTime = now;
    }
  }
  /**
   * Process queued validation operations
   */
  processBatch() {
    const batch = this.operationQueue.splice(0, this.config.batchSize);
    if (this.config.asyncValidation) {
      setTimeout(() => {
        batch.forEach((op) => {
          try {
            op();
          } catch (error) {
            console.warn("Batch validation error:", error);
          }
        });
      }, 0);
    } else {
      batch.forEach((op) => {
        try {
          op();
        } catch (error) {
          console.warn("Batch validation error:", error);
        }
      });
    }
  }
  /**
   * Check if validation should be skipped this frame
   */
  shouldSkipFrame() {
    if (this.config.skipFrames === 0) return false;
    this.frameCounter++;
    return this.frameCounter % (this.config.skipFrames + 1) !== 0;
  }
  /**
   * Check if operation is currently throttled
   */
  isThrottled(key) {
    const lastTime = this.throttleTimers.get(key);
    const now = Date.now();
    if (!lastTime || now - lastTime > this.config.throttleMs) {
      this.throttleTimers.set(key, now);
      return false;
    }
    return true;
  }
  /**
   * Record performance metrics
   */
  recordMetrics(key, duration, _success) {
    const existing = this.metrics.get(key) || {
      operationCount: 0,
      totalTime: 0,
      averageTime: 0,
      maxTime: 0,
      cacheHitRate: 0,
      skipRate: 0
    };
    existing.operationCount++;
    existing.totalTime += duration;
    existing.averageTime = existing.totalTime / existing.operationCount;
    existing.maxTime = Math.max(existing.maxTime, duration);
    this.metrics.set(key, existing);
  }
  /**
   * Get performance metrics for a specific operation
   */
  getMetrics(key) {
    return this.metrics.get(key);
  }
  /**
   * Get all performance metrics
   */
  getAllMetrics() {
    return new Map(this.metrics);
  }
  /**
   * Reset all metrics
   */
  resetMetrics() {
    this.metrics.clear();
    this.throttleTimers.clear();
    this.frameCounter = 0;
  }
  /**
   * Auto-optimize based on current performance
   */
  autoOptimize(currentOverhead) {
    if (currentOverhead > this.config.targetOverhead * 1.5) {
      this.configure({
        batchSize: Math.max(this.config.batchSize * 2, 50),
        cacheStrategy: "aggressive",
        skipFrames: Math.min(this.config.skipFrames + 1, 3)
      });
    } else if (currentOverhead < this.config.targetOverhead * 0.5) {
      this.configure({
        batchSize: Math.max(Math.floor(this.config.batchSize / 2), 5),
        cacheStrategy: "moderate",
        skipFrames: Math.max(this.config.skipFrames - 1, 0)
      });
    }
  }
  /**
   * Measure validation overhead
   */
  measureOverhead(validationFn, iterations = 100) {
    const baselineStart = performance.now();
    const baselineTime = performance.now() - baselineStart;
    const validationStart = performance.now();
    for (let i = 0; i < iterations; i++) {
      validationFn();
    }
    const validationTime = performance.now() - validationStart;
    const overhead = validationTime - baselineTime;
    const overheadPercentage = overhead / validationTime * 100;
    return Math.max(overheadPercentage, 0);
  }
  /**
   * Monitor and report performance continuously
   */
  startPerformanceMonitoring(intervalMs = 5e3) {
    const interval = setInterval(() => {
      const overhead = this.measureOverhead(() => {
        this.optimizeValidation("monitor-test", () => {
          return Math.random() > 0.5;
        });
      });
      if (overhead > this.config.targetOverhead) {
        this.autoOptimize(overhead);
        validationDebugger.logEvent(
          "performance-warning",
          `Validation overhead: ${overhead.toFixed(1)}% (target: ${this.config.targetOverhead}%)`,
          { overhead, target: this.config.targetOverhead, actual: overhead }
        );
      }
    }, intervalMs);
    return () => clearInterval(interval);
  }
}
const performanceOptimizer = PerformanceOptimizer.getInstance();
const PerformanceOptimizationUtils = {
  configure: (config) => performanceOptimizer.configure(config),
  getMetrics: (key) => key ? performanceOptimizer.getMetrics(key) : performanceOptimizer.getAllMetrics(),
  resetMetrics: () => performanceOptimizer.resetMetrics(),
  measureOverhead: (validationFn, iterations) => performanceOptimizer.measureOverhead(validationFn, iterations),
  startMonitoring: (intervalMs) => performanceOptimizer.startPerformanceMonitoring(intervalMs),
  getStats: () => ({
    enabled: performanceOptimizer["config"].enabled,
    targetOverhead: performanceOptimizer["config"].targetOverhead,
    batchSize: performanceOptimizer["config"].batchSize,
    cacheStrategy: performanceOptimizer["config"].cacheStrategy,
    metricsCount: performanceOptimizer.getAllMetrics().size
  })
};
class ProductionMonitor {
  static instance;
  bypassCount = 0;
  performanceGain = 0;
  validationTimes = [];
  slowValidations = [];
  static getInstance() {
    if (!this.instance) {
      this.instance = new ProductionMonitor();
    }
    return this.instance;
  }
  /**
   * Record a validation bypass for performance tracking
   */
  recordBypass(timesSaved) {
    this.bypassCount++;
    this.performanceGain += timesSaved;
  }
  /**
   * Record validation performance
   */
  recordValidationTime(componentType, duration) {
    this.validationTimes.push(duration);
    if (duration > 5) {
      this.slowValidations.push({ component: componentType, time: duration });
      console.warn(
        `⚠️ Validation overhead: ${duration.toFixed(2)}ms for ${componentType}`
      );
    }
    if (this.validationTimes.length > 100) {
      this.validationTimes = this.validationTimes.slice(-50);
    }
    if (this.slowValidations.length > 20) {
      this.slowValidations = this.slowValidations.slice(-10);
    }
  }
  /**
   * Get performance statistics
   */
  getStats() {
    const averageOverhead = this.validationTimes.length > 0 ? this.validationTimes.reduce((sum, time) => sum + time, 0) / this.validationTimes.length : 0;
    return {
      bypassCount: this.bypassCount,
      performanceGain: this.performanceGain,
      averageOverhead,
      slowValidations: [...this.slowValidations]
    };
  }
  /**
   * Reset monitoring statistics
   */
  reset() {
    this.bypassCount = 0;
    this.performanceGain = 0;
    this.validationTimes = [];
    this.slowValidations = [];
  }
  /**
   * Generate optimization recommendations
   */
  getRecommendations() {
    const recommendations = [];
    const stats = this.getStats();
    if (stats.averageOverhead > 3) {
      recommendations.push(
        "Consider reducing validation complexity - average overhead is high"
      );
    }
    if (stats.slowValidations.length > 5) {
      recommendations.push(
        "Multiple slow validation operations detected - review component validators"
      );
    }
    if (stats.bypassCount === 0 && process.env.NODE_ENV === "production") {
      recommendations.push(
        "Validation bypass not working - check production build configuration"
      );
    }
    return recommendations;
  }
}
class BundleAnalysis {
  /**
   * Estimate validation code size in bundle
   */
  static getValidationCodeSize() {
    if (process.env.NODE_ENV === "production") {
      return 0;
    }
    return 15e3;
  }
  /**
   * Generate optimization report
   */
  static getOptimizationReport() {
    const monitor = ProductionMonitor.getInstance();
    const stats = monitor.getStats();
    const codeSize = this.getValidationCodeSize();
    return {
      validationCodeSize: codeSize,
      performanceGain: stats.performanceGain,
      optimization: codeSize === 0 ? "Fully optimized (tree-shaken)" : "Development mode",
      recommendations: monitor.getRecommendations()
    };
  }
}
function devAssert(condition, message, context) {
  if (typeof window !== "undefined" && window.__TACHUI_DEV_MODE__) {
    if (!condition) {
      console.error("TachUI Dev Assertion Failed:", message, context);
      if (context) {
        console.trace("Assertion context:", context);
      }
      throw new Error(`TachUI Dev Assertion: ${message}`);
    }
  }
}
function devWarn(condition, message, context) {
  if (typeof window !== "undefined" && window.__TACHUI_DEV_MODE__) {
    if (!condition) {
      console.warn(`TachUI Dev Warning: ${message}`, context);
      if (context) {
        console.trace("Warning context:", context);
      }
    }
  }
}
function withPerformanceMonitoring(fn, name, options = {}) {
  const { threshold = 10, logSlow = true, trackStats = true } = options;
  return function monitoredFunction(...args) {
    const start = performance.now();
    const result = fn(...args);
    const end = performance.now();
    const duration = end - start;
    if (trackStats) {
      ProductionMonitor.getInstance().recordValidationTime(name, duration);
    }
    if (logSlow && duration > threshold) {
      console.info(`⏱️ ${name}: ${duration.toFixed(2)}ms`);
    }
    return result;
  };
}
function withMonitoredValidation(originalConstructor, componentType, validator) {
  return function monitoredComponent(...args) {
    const startTime = performance.now();
    if (validator) {
      try {
        validator(args);
      } catch (error) {
        console.error(`Validation failed for ${componentType}:`, error);
        throw error;
      }
    }
    const result = originalConstructor.apply(this, args);
    const endTime = performance.now();
    const duration = endTime - startTime;
    ProductionMonitor.getInstance().recordValidationTime(
      componentType,
      duration
    );
    return result;
  };
}
const DevConstants = {
  __DEVELOPMENT_ONLY__: process.env.NODE_ENV !== "production",
  __TACHUI_VERSION__: "0.1.0",
  // Define globals for bundlers to replace
  defineGlobals: {
    __TACHUI_PRODUCTION_MODE__: process.env.NODE_ENV === "production",
    __TACHUI_DEBUG_INFO__: process.env.NODE_ENV !== "production"
  }
};
const ProductionOptimizationUtils = {
  /**
   * Get detailed performance statistics
   */
  getDetailedStats: () => {
    const monitor = ProductionMonitor.getInstance();
    return {
      ...monitor.getStats(),
      recommendations: monitor.getRecommendations(),
      bundleReport: BundleAnalysis.getOptimizationReport()
    };
  },
  /**
   * Reset monitoring data
   */
  resetStats: () => ProductionMonitor.getInstance().reset(),
  /**
   * Get bundle optimization report
   */
  getBundleReport: BundleAnalysis.getOptimizationReport,
  /**
   * Test production optimization with detailed reporting
   */
  test() {
    console.group("🚀 Production Optimization Analysis");
    const stats = ProductionMonitor.getInstance().getStats();
    const report = BundleAnalysis.getOptimizationReport();
    console.info("📊 Performance Statistics:");
    console.info("  • Validation bypasses:", stats.bypassCount);
    console.info(
      "  • Performance gain:",
      `${stats.performanceGain.toFixed(2)}ms`
    );
    console.info(
      "  • Average overhead:",
      `${stats.averageOverhead.toFixed(2)}ms`
    );
    console.info("  • Slow validations:", stats.slowValidations.length);
    console.info("📦 Bundle Optimization:");
    console.info("  • Bundle status:", report.optimization);
    console.info(
      "  • Validation code size:",
      report.validationCodeSize === 0 ? "Tree-shaken ✅" : `${report.validationCodeSize} bytes`
    );
    if (report.recommendations.length > 0) {
      console.info("💡 Optimization Recommendations:");
      report.recommendations.forEach((rec) => console.info(`   • ${rec}`));
    } else {
      console.info(
        "✅ No optimization recommendations - system is running efficiently"
      );
    }
    if (stats.slowValidations.length > 0) {
      console.info("⚠️ Slow Validations:");
      stats.slowValidations.forEach(
        (slow) => console.info(`   • ${slow.component}: ${slow.time.toFixed(2)}ms`)
      );
    }
    console.groupEnd();
  },
  /**
   * Start continuous monitoring
   */
  startMonitoring(intervalMs = 3e4) {
    const monitor = ProductionMonitor.getInstance();
    const interval = setInterval(() => {
      const stats = monitor.getStats();
      if (stats.slowValidations.length > 0) {
        console.warn(
          "⚠️ TachUI Performance Alert: Slow validation operations detected"
        );
      }
    }, intervalMs);
    console.info("🔍 TachUI production monitoring started");
    return () => {
      clearInterval(interval);
      console.info("🔍 TachUI production monitoring stopped");
    };
  }
};
const PerformanceProfiler = {
  initialize: (config) => {
    console.log("PerformanceProfiler initialized with config:", config);
  }
};
const RenderProfiler = {
  wrap: (component, _config) => component
};
const MemoryProfiler = {
  startMonitoring: (config) => {
    console.log("MemoryProfiler started with config:", config);
  }
};
const BundleAnalyzer = {
  analyze: () => {
    console.log("Bundle analysis started");
  }
};
export {
  BundleAnalysis,
  BundleAnalyzer,
  DevConstants,
  MemoryProfiler,
  PerformanceOptimizationUtils,
  PerformanceOptimizer,
  PerformanceProfiler,
  ProductionMonitor,
  ProductionOptimizationUtils,
  RenderProfiler,
  devAssert,
  devWarn,
  performanceOptimizer,
  withMonitoredValidation,
  withPerformanceMonitoring
};
