class DebugManager {
  config = {
    enabled: false,
    showLabels: false,
    showBounds: false,
    logComponentTree: false
  };
  componentTree = [];
  /**
   * Enable debug mode with optional configuration
   */
  enable(options = {}) {
    this.config = {
      enabled: true,
      showLabels: true,
      showBounds: true,
      logComponentTree: true,
      ...options
    };
    if (this.config.enabled) {
      this.injectDebugStyles();
    }
  }
  /**
   * Disable debug mode
   */
  disable() {
    this.config.enabled = false;
    this.removeDebugStyles();
  }
  /**
   * Check if debug mode is enabled
   */
  isEnabled() {
    return this.config.enabled;
  }
  /**
   * Get current debug configuration
   */
  getConfig() {
    return { ...this.config };
  }
  /**
   * Add debug attributes to DOM element
   */
  addDebugAttributes(element, componentType, debugLabel) {
    if (!this.config.enabled) return;
    element.setAttribute("data-tachui-component", componentType);
    if (debugLabel) {
      element.setAttribute("data-tachui-label", debugLabel);
    }
    if (this.config.showLabels || this.config.showBounds) {
      element.classList.add("tachui-debug");
    }
    if (this.config.showLabels && debugLabel) {
      element.classList.add("tachui-debug-labeled");
    }
    if (this.config.showBounds) {
      element.classList.add("tachui-debug-bounds");
    }
  }
  /**
   * Log component to tree (for hierarchical debugging)
   */
  logComponent(type, label, depth = 0) {
    if (!this.config.enabled || !this.config.logComponentTree) return;
    this.componentTree.push({
      label: label || `<${type}>`,
      type,
      depth
    });
  }
  /**
   * Print component tree to console
   */
  printComponentTree() {
    if (!this.config.enabled || !this.config.logComponentTree) return;
    console.group("🌳 TachUI Component Tree:");
    this.componentTree.forEach(({ label, type, depth }) => {
      const indent = "  ".repeat(depth);
      const icon = this.getComponentIcon(type);
      console.log(`${indent}${icon} ${type}: "${label}"`);
    });
    console.groupEnd();
    this.componentTree = [];
  }
  /**
   * Get icon for component type
   */
  getComponentIcon(type) {
    const icons = {
      VStack: "📚",
      HStack: "➡️",
      ZStack: "📑",
      Button: "🔘",
      Text: "📝",
      Image: "🖼️",
      ScrollView: "📜",
      List: "📋",
      Form: "📋",
      Section: "📁",
      default: "🧩"
    };
    return icons[type] || icons.default;
  }
  /**
   * Inject debug CSS styles
   */
  injectDebugStyles() {
    if (document.getElementById("tachui-debug-styles")) return;
    const styles = `
      /* TachUI Debug Styles */
      .tachui-debug {
        position: relative;
      }

      .tachui-debug-bounds {
        outline: 1px dashed rgba(255, 0, 0, 0.3) !important;
        outline-offset: -1px;
      }

      .tachui-debug-labeled::before {
        content: attr(data-tachui-label);
        position: absolute;
        top: -1px;
        left: -1px;
        background: rgba(255, 0, 0, 0.9);
        color: white;
        font-family: 'Monaco', 'Menlo', 'Consolas', monospace;
        font-size: 10px;
        font-weight: bold;
        line-height: 1;
        padding: 2px 4px;
        border-radius: 2px;
        z-index: 9999;
        pointer-events: none;
        white-space: nowrap;
        max-width: 200px;
        overflow: hidden;
        text-overflow: ellipsis;
      }

      .tachui-debug-labeled:hover::before {
        background: rgba(255, 0, 0, 1);
        max-width: none;
        white-space: normal;
      }

      /* Component type indicators */
      [data-tachui-component="VStack"] {
        border-left: 2px solid rgba(0, 255, 0, 0.5) !important;
      }

      [data-tachui-component="HStack"] {
        border-top: 2px solid rgba(0, 0, 255, 0.5) !important;
      }

      [data-tachui-component="Button"] {
        box-shadow: inset 0 0 0 1px rgba(255, 165, 0, 0.5) !important;
      }
    `;
    const styleElement = document.createElement("style");
    styleElement.id = "tachui-debug-styles";
    styleElement.textContent = styles;
    document.head.appendChild(styleElement);
  }
  /**
   * Remove debug CSS styles
   */
  removeDebugStyles() {
    const styleElement = document.getElementById("tachui-debug-styles");
    if (styleElement) {
      styleElement.remove();
    }
    document.querySelectorAll(".tachui-debug").forEach((el) => {
      el.classList.remove(
        "tachui-debug",
        "tachui-debug-labeled",
        "tachui-debug-bounds"
      );
    });
  }
}
const debugManager = new DebugManager();
const enableDebug = (options) => debugManager.enable(options);
const disableDebug = () => debugManager.disable();
const isDebugEnabled = () => debugManager.isEnabled();
if (typeof window !== "undefined") {
  const urlParams = new URLSearchParams(window.location.search);
  const debugParam = urlParams.get("debug");
  if (debugParam === "true" || debugParam === "1") {
    debugManager.enable({
      enabled: true,
      showLabels: true,
      showBounds: true,
      logComponentTree: true
    });
    console.log("🔧 TachUI Debug Mode: Enabled via URL parameter (?debug=true)");
  } else if (debugParam === "labels") {
    debugManager.enable({
      enabled: true,
      showLabels: true,
      showBounds: false,
      logComponentTree: false
    });
    console.log("🔧 TachUI Debug Mode: Labels only (?debug=labels)");
  } else if (debugParam === "bounds") {
    debugManager.enable({
      enabled: true,
      showLabels: false,
      showBounds: true,
      logComponentTree: false
    });
    console.log("🔧 TachUI Debug Mode: Bounds only (?debug=bounds)");
  }
}
class DeveloperErrorFactory {
  /**
   * Create modifier validation error
   */
  static modifierValidationError(modifier, issue, component) {
    const componentName = component?.type || "Unknown";
    const error = new Error(
      `Invalid modifier usage: ${modifier} - ${issue}`
    );
    error.code = "MODIFIER_VALIDATION_ERROR";
    error.category = "modifier";
    error.severity = "error";
    error.component = componentName;
    error.suggestion = DeveloperErrorFactory.getModifierSuggestion(
      modifier,
      issue
    );
    error.documentation = `https://docs.tachui.dev/modifiers/${modifier.toLowerCase()}`;
    error.examples = DeveloperErrorFactory.getModifierExamples(modifier);
    return error;
  }
  /**
   * Create component validation error
   */
  static componentValidationError(componentType, prop, expectedType, actualValue) {
    const actualType = Array.isArray(actualValue) ? `array[${actualValue.length}]` : typeof actualValue;
    const error = new Error(
      `Component validation failed: ${componentType}.${prop} expected ${expectedType}, got ${actualType}`
    );
    error.code = "COMPONENT_VALIDATION_ERROR";
    error.category = "component";
    error.severity = "error";
    error.component = componentType;
    error.suggestion = `Ensure ${prop} is of type ${expectedType}. ${DeveloperErrorFactory.getTypeConversionSuggestion(expectedType, actualValue)}`;
    error.documentation = `https://docs.tachui.dev/components/${componentType.toLowerCase()}`;
    error.examples = DeveloperErrorFactory.getComponentExamples(
      componentType,
      prop
    );
    return error;
  }
  /**
   * Create reactive system error
   */
  static reactiveSystemError(operation, issue, context) {
    const error = new Error(
      `Reactive system error: ${operation} - ${issue}`
    );
    error.code = "REACTIVE_SYSTEM_ERROR";
    error.category = "reactive";
    error.severity = "error";
    error.suggestion = DeveloperErrorFactory.getReactiveSuggestion(
      operation,
      issue
    );
    error.documentation = "https://docs.tachui.dev/reactive/signals";
    error.examples = DeveloperErrorFactory.getReactiveExamples(operation);
    if (context) {
      error.message += ` (Context: ${context})`;
    }
    return error;
  }
  /**
   * Create runtime error
   */
  static runtimeError(operation, issue, component) {
    const error = new Error(
      `Runtime error: ${operation} - ${issue}`
    );
    error.code = "RUNTIME_ERROR";
    error.category = "runtime";
    error.severity = "fatal";
    error.component = component;
    error.suggestion = DeveloperErrorFactory.getRuntimeSuggestion(
      operation,
      issue
    );
    error.documentation = "https://docs.tachui.dev/runtime/renderer";
    return error;
  }
  /**
   * Get modifier-specific suggestion
   */
  static getModifierSuggestion(modifier, issue) {
    const suggestions = {
      padding: {
        "conflicting properties": "Use either .padding(number) for all sides, or .padding({ horizontal, vertical }) for symmetric padding, or individual directional functions like .paddingTop()",
        "invalid value": "Padding values must be numbers (pixels) or valid CSS length strings",
        "negative padding": "Negative padding values are not recommended and may cause layout issues"
      },
      frame: {
        "missing dimensions": "Frame modifier requires at least width or height: .frame(width, height) or .frame({ width: 100 })",
        "invalid dimensions": "Frame dimensions must be positive numbers or valid CSS length values"
      },
      backgroundColor: {
        "invalid color": "Use valid color formats: hex (#ff0000), rgb (rgb(255,0,0)), or named colors (red)",
        "asset not found": "Color asset not found. Check your asset definitions or use getColor() to verify"
      },
      onTap: {
        "not a function": "onTap requires a function: .onTap(() => { /* your code */ })",
        "missing parameter": "onTap handler will receive a MouseEvent: .onTap((event) => { /* handle event */ })"
      }
    };
    const modifierSuggestions = suggestions[modifier];
    return modifierSuggestions?.[issue] || `Check the ${modifier} modifier documentation for proper usage`;
  }
  /**
   * Get modifier examples
   */
  static getModifierExamples(modifier) {
    const examples = {
      padding: [
        ".padding(16)",
        ".padding({ horizontal: 20, vertical: 12 })",
        ".paddingTop(8).paddingHorizontal(16)",
        ".paddingLeading(20) // SwiftUI-style"
      ],
      frame: [
        ".frame(100, 200)",
        ".frame({ width: 100, height: 200 })",
        ".frame({ minWidth: 50, maxWidth: 200 })"
      ],
      backgroundColor: [
        '.backgroundColor("#ff0000")',
        '.backgroundColor("rgb(255, 0, 0)")',
        ".backgroundColor(Colors.primary) // Asset"
      ],
      onTap: [
        '.onTap(() => console.log("Tapped!"))',
        ".onTap((event) => handleTap(event))"
      ]
    };
    return examples[modifier] || [];
  }
  /**
   * Get component examples
   */
  static getComponentExamples(componentType, prop) {
    const examples = {
      Text: {
        children: ['Text("Hello World")', "Text(() => dynamicText())"],
        style: [
          'Text("Hello").fontSize(16)',
          'Text("Hello").foregroundColor("red")'
        ]
      },
      Button: {
        children: [
          'Button({ children: "Click me" })',
          "Button({ children: () => buttonText() })"
        ],
        onPress: ["Button({ onPress: () => handlePress() })"]
      },
      VStack: {
        children: [
          'VStack([Text("Item 1"), Text("Item 2")])',
          "VStack({ children: childComponents })"
        ],
        spacing: [
          "VStack({ spacing: 16 })",
          "VStack({ spacing: 8, children: items })"
        ]
      }
    };
    const componentExamples = examples[componentType];
    return componentExamples?.[prop] || [
      `${componentType}({ ${prop}: /* your value */ })`
    ];
  }
  /**
   * Get type conversion suggestion
   */
  static getTypeConversionSuggestion(expectedType, actualValue) {
    if (expectedType.includes("string") && typeof actualValue === "number") {
      return `Convert number to string: "${actualValue}"`;
    }
    if (expectedType.includes("number") && typeof actualValue === "string") {
      const parsed = parseFloat(actualValue);
      if (!Number.isNaN(parsed)) {
        return `Convert string to number: ${parsed}`;
      }
    }
    if (expectedType.includes("array") && !Array.isArray(actualValue)) {
      return `Wrap value in array: [${JSON.stringify(actualValue)}]`;
    }
    if (expectedType.includes("function") && typeof actualValue !== "function") {
      return "Provide a function: () => { /* your code */ }";
    }
    return `Expected ${expectedType}, ensure the value matches this type`;
  }
  /**
   * Get reactive system suggestion
   */
  static getReactiveSuggestion(operation, issue) {
    const suggestions = {
      createSignal: {
        "invalid initial value": "Signal initial value should match the expected type",
        "mutation attempt": "Signals are immutable. Use the setter function: const [value, setValue] = createSignal(0); setValue(newValue)"
      },
      createEffect: {
        "missing dependencies": "Effect will only run when accessed signals change. Ensure all dependencies are accessed within the effect",
        "infinite loop": "Effect creates infinite loop. Avoid setting signals that the effect depends on"
      },
      createComputed: {
        "side effects": "Computed values should be pure. Avoid side effects like console.log or API calls",
        "circular dependency": "Computed value depends on itself, creating circular dependency"
      }
    };
    const operationSuggestions = suggestions[operation];
    return operationSuggestions?.[issue] || `Check reactive system documentation for ${operation} usage`;
  }
  /**
   * Get reactive examples
   */
  static getReactiveExamples(operation) {
    const examples = {
      createSignal: [
        "const [count, setCount] = createSignal(0)",
        'const [text, setText] = createSignal("Hello")',
        "const [user, setUser] = createSignal<User | null>(null)"
      ],
      createEffect: [
        'createEffect(() => { console.log("Count:", count()) })',
        'createEffect(() => { localStorage.setItem("count", count().toString()) })'
      ],
      createComputed: [
        "const doubled = createComputed(() => count() * 2)",
        "const fullName = createComputed(() => `${firstName()} ${lastName()}`)"
      ]
    };
    return examples[operation] || [];
  }
  /**
   * Get runtime suggestion
   */
  static getRuntimeSuggestion(operation, issue) {
    const suggestions = {
      render: "Ensure all components return valid virtual DOM nodes",
      mount: "Check that the mount target element exists in the DOM",
      update: "Verify component state and props are valid before updating"
    };
    return suggestions[operation] || `Runtime issue in ${operation}: ${issue}`;
  }
}
class DeveloperWarnings {
  static warningsSeen = /* @__PURE__ */ new Set();
  /**
   * Warn about deprecated API usage
   */
  static deprecation(oldAPI, newAPI, component, willBeRemovedIn) {
    const key = `deprecation:${oldAPI}:${component || "global"}`;
    if (DeveloperWarnings.warningsSeen.has(key)) return;
    DeveloperWarnings.warningsSeen.add(key);
    const componentContext = component ? ` in ${component}` : "";
    const removalVersion = willBeRemovedIn ? ` (will be removed in ${willBeRemovedIn})` : "";
    console.warn(
      `🟡 TachUI Deprecation Warning${componentContext}: "${oldAPI}" is deprecated. Use "${newAPI}" instead${removalVersion}.
See: https://docs.tachui.dev/migration/deprecations`
    );
  }
  /**
   * Warn about performance issues
   */
  static performance(issue, suggestion, component) {
    const key = `performance:${issue}:${component || "global"}`;
    if (DeveloperWarnings.warningsSeen.has(key)) return;
    DeveloperWarnings.warningsSeen.add(key);
    const componentContext = component ? ` in ${component}` : "";
    console.warn(
      `⚡ TachUI Performance Warning${componentContext}: ${issue}
💡 Suggestion: ${suggestion}
See: https://docs.tachui.dev/performance/optimization`
    );
  }
  /**
   * Warn about accessibility issues
   */
  static accessibility(issue, suggestion, component) {
    const key = `a11y:${issue}:${component || "global"}`;
    if (DeveloperWarnings.warningsSeen.has(key)) return;
    DeveloperWarnings.warningsSeen.add(key);
    const componentContext = component ? ` in ${component}` : "";
    console.warn(
      `♿ TachUI Accessibility Warning${componentContext}: ${issue}
💡 Suggestion: ${suggestion}
See: https://docs.tachui.dev/accessibility/guidelines`
    );
  }
  /**
   * Clear warning cache (for testing)
   */
  static clearWarnings() {
    DeveloperWarnings.warningsSeen.clear();
  }
  /**
   * Get count of unique warnings shown
   */
  static getWarningCount() {
    return DeveloperWarnings.warningsSeen.size;
  }
}
class TypeValidation {
  /**
   * Validate component props with enhanced error messages
   */
  static validateComponentProps(componentType, props, schema) {
    for (const [prop, config] of Object.entries(schema)) {
      const value = props[prop];
      if (config.required && (value === void 0 || value === null)) {
        throw DeveloperErrorFactory.componentValidationError(
          componentType,
          prop,
          `${config.type} (required)`,
          value
        );
      }
      if (value === void 0 && !config.required) continue;
      if (!TypeValidation.validateType(value, config.type)) {
        throw DeveloperErrorFactory.componentValidationError(
          componentType,
          prop,
          config.type,
          value
        );
      }
      if (config.validator && !config.validator(value)) {
        const error = DeveloperErrorFactory.componentValidationError(
          componentType,
          prop,
          config.type,
          value
        );
        if (config.message) {
          error.suggestion = config.message;
        }
        throw error;
      }
    }
  }
  /**
   * Validate type
   */
  static validateType(value, type) {
    switch (type) {
      case "string":
        return typeof value === "string";
      case "number":
        return typeof value === "number" && !Number.isNaN(value);
      case "boolean":
        return typeof value === "boolean";
      case "function":
        return typeof value === "function";
      case "array":
        return Array.isArray(value);
      case "object":
        return typeof value === "object" && value !== null && !Array.isArray(value);
      case "ComponentInstance":
        return value && typeof value === "object" && "type" in value;
      case "Signal":
        return typeof value === "function" && "peek" in value;
      default:
        if (type.includes("|")) {
          return type.split("|").some((t) => TypeValidation.validateType(value, t.trim()));
        }
        return true;
    }
  }
  /**
   * Validate modifier combination
   */
  static validateModifierCombination(modifiers) {
    const conflicts = [
      {
        types: ["padding", "padding"],
        message: "Multiple padding modifiers detected. Combine into single .padding() call or use specific directional functions"
      },
      {
        types: ["size", "size"],
        message: "Multiple size modifiers detected. Combine into single .size() call"
      }
    ];
    for (const conflict of conflicts) {
      const matchingModifiers = modifiers.filter(
        (m) => conflict.types.includes(m.type)
      );
      if (matchingModifiers.length > 1) {
        DeveloperWarnings.performance(
          "Redundant modifiers detected",
          conflict.message
        );
      }
    }
  }
}
class DeveloperExperienceUtils {
  /**
   * Format error message for better developer experience
   */
  static formatError(error) {
    return {
      code: error.code,
      message: error.message,
      suggestion: error.suggestion,
      severity: error.severity,
      component: error.component,
      documentation: error.documentation,
      examples: error.examples
    };
  }
  /**
   * Get statistics about developer experience features
   */
  static getStatistics() {
    return {
      errorCount: 0,
      warningCount: 0,
      suggestionCount: 0
    };
  }
  /**
   * Get suggestions for a diagnostic
   */
  static getSuggestions(_code, _data) {
    return [];
  }
  /**
   * Test developer experience features
   */
  static async test() {
    console.log("🛠️ Developer Experience Utils test completed");
  }
}
const devMode = {
  /**
   * Enable enhanced error reporting in development
   */
  enableEnhancedErrors() {
    const originalError = console.error;
    console.error = (...args) => {
      const firstArg = args[0];
      if (firstArg && typeof firstArg === "object" && "code" in firstArg) {
        const error = firstArg;
        console.group(
          `🚨 TachUI ${error.severity.toUpperCase()}: ${error.code}`
        );
        console.error(error.message);
        if (error.component) console.log(`📦 Component: ${error.component}`);
        console.log(`💡 Suggestion: ${error.suggestion}`);
        if (error.documentation) console.log(`📖 Docs: ${error.documentation}`);
        if (error.examples?.length) {
          console.group("💻 Examples:");
          error.examples.forEach((example) => console.log(`  ${example}`));
          console.groupEnd();
        }
        console.groupEnd();
      } else {
        originalError(...args);
      }
    };
  },
  /**
   * Log component tree for debugging
   */
  logComponentTree(root, depth = 0) {
    const indent = "  ".repeat(depth);
    const modifierCount = root.modifiers?.length || 0;
    const modifierInfo = modifierCount > 0 ? ` (${modifierCount} modifiers)` : "";
    console.log(`${indent}${root.type}${modifierInfo}`);
    if ("children" in root.props && Array.isArray(root.props.children)) {
      root.props.children.forEach((child) => {
        if (child && typeof child === "object" && "type" in child) {
          this.logComponentTree(child, depth + 1);
        }
      });
    }
  }
};
class DevelopmentWarnings {
  static warningsShown = /* @__PURE__ */ new Set();
  /**
   * Warn about element tag overrides in development
   */
  static warnElementOverride(componentType, originalTag, overrideTag) {
    if (process.env.NODE_ENV === "production") return;
    const warningKey = `${componentType}-${originalTag}-${overrideTag}`;
    if (this.warningsShown.has(warningKey)) return;
    this.warningsShown.add(warningKey);
    console.warn(
      `[tachUI] ${componentType} (${originalTag}) overridden to <${overrideTag}>. Ensure this maintains expected behavior and accessibility.`
    );
  }
  /**
   * Error for invalid HTML tags
   */
  static errorInvalidTag(tag, componentType) {
    if (process.env.NODE_ENV === "production") return;
    console.error(
      `[tachUI] Invalid HTML tag '${tag}' specified for ${componentType}. Using tag as-is - ensure this is intentional.`
    );
  }
  /**
   * Info message for semantic role application
   */
  static infoSemanticRole(tag, role) {
    if (process.env.NODE_ENV !== "development") return;
    console.info(`[tachUI] Applied semantic role '${role}' to <${tag}> element`);
  }
  /**
   * Warn about potentially problematic tag combinations
   */
  static warnProblematicCombination(componentType, tag, issue, severity = "warning") {
    if (process.env.NODE_ENV === "production") return;
    const warningKey = `${componentType}-${tag}-${issue}`;
    if (this.warningsShown.has(warningKey)) return;
    this.warningsShown.add(warningKey);
    const logFunction = severity === "warning" ? console.warn : console.info;
    logFunction(`[tachUI] ${componentType}: ${issue}`);
  }
  /**
   * Warn about accessibility concerns
   */
  static warnAccessibility(componentType, tag, accessibilityIssue) {
    if (process.env.NODE_ENV === "production") return;
    const warningKey = `a11y-${componentType}-${tag}-${accessibilityIssue}`;
    if (this.warningsShown.has(warningKey)) return;
    this.warningsShown.add(warningKey);
    console.warn(
      `[tachUI A11y] ${componentType} with <${tag}>: ${accessibilityIssue}. Consider using appropriate ARIA attributes or different semantic structure.`
    );
  }
  /**
   * Clear all shown warnings (useful for testing)
   */
  static clearWarnings() {
    this.warningsShown.clear();
  }
  /**
   * Check if a warning has been shown
   */
  static hasWarningBeenShown(warningKey) {
    return this.warningsShown.has(warningKey);
  }
  /**
   * Get count of unique warnings shown
   */
  static getWarningCount() {
    return this.warningsShown.size;
  }
}
const performanceMonitor = {
  getSnapshot: () => ({
    memory: 0,
    timing: {},
    validationOverhead: 0,
    cacheEfficiency: 0.85
  })
};
class ValidationDebugger {
  static instance;
  sessions = /* @__PURE__ */ new Map();
  currentSession = null;
  eventListeners = /* @__PURE__ */ new Map();
  componentRegistry = /* @__PURE__ */ new Map();
  static getInstance() {
    if (!this.instance) {
      this.instance = new ValidationDebugger();
    }
    return this.instance;
  }
  /**
   * Start a debugging session
   */
  startSession(sessionId) {
    const id = sessionId || `debug-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
    const session = {
      id,
      startTime: Date.now(),
      validationEvents: [],
      components: [],
      errors: [],
      performance: performanceMonitor.getSnapshot()
    };
    this.sessions.set(id, session);
    this.currentSession = session;
    this.logEvent("validation-start", `Debug session ${id} started`);
    if (process.env.NODE_ENV !== "production") {
      console.info(`🔍 TachUI Debug Session Started: ${id}`);
    }
    return id;
  }
  /**
   * End the current debugging session
   */
  endSession() {
    if (!this.currentSession) {
      console.warn("No active debug session to end");
      return null;
    }
    this.currentSession.endTime = Date.now();
    this.logEvent(
      "validation-end",
      `Debug session ${this.currentSession.id} ended`
    );
    const session = this.currentSession;
    this.currentSession = null;
    if (process.env.NODE_ENV !== "production") {
      console.info(`🔍 TachUI Debug Session Ended: ${session.id}`);
      this.printSessionSummary(session);
    }
    return session;
  }
  /**
   * Log a debug event
   */
  logEvent(type, message, data) {
    if (!this.currentSession) return;
    const event = {
      id: `event-${Date.now()}-${Math.random().toString(36).substr(2, 6)}`,
      type,
      timestamp: Date.now(),
      message,
      data,
      stackTrace: process.env.NODE_ENV !== "production" ? new Error().stack : void 0
    };
    this.currentSession.validationEvents.push(event);
    const listeners = this.eventListeners.get(type) || [];
    listeners.forEach((listener) => {
      try {
        listener(event);
      } catch (error) {
        console.error("Debug event listener error:", error);
      }
    });
  }
  /**
   * Register component for debugging
   */
  registerComponent(_component, type, props) {
    const componentId = `${type}-${Date.now()}-${Math.random().toString(36).substr(2, 6)}`;
    const debugInfo = {
      type,
      id: componentId,
      props,
      lifecycle: {
        created: Date.now()
      },
      validation: {
        passed: true,
        errors: [],
        warnings: [],
        lastCheck: Date.now()
      },
      performance: {
        updateTimes: [],
        validationTime: 0
      }
    };
    this.componentRegistry.set(componentId, debugInfo);
    if (this.currentSession) {
      this.currentSession.components.push(debugInfo);
      this.logEvent("component-mount", `Component ${type} registered`, {
        componentId,
        props
      });
    }
    return componentId;
  }
  /**
   * Update component debug info
   */
  updateComponent(componentId, phase, data) {
    const debugInfo = this.componentRegistry.get(componentId);
    if (!debugInfo) return;
    const timestamp = Date.now();
    switch (phase) {
      case "mount":
        debugInfo.lifecycle.mounted = timestamp;
        if (data?.performance) {
          debugInfo.performance.mountTime = data.performance.duration;
        }
        this.logEvent(
          "component-mount",
          `Component ${debugInfo.type} mounted`,
          { componentId, data }
        );
        break;
      case "update":
        debugInfo.lifecycle.lastUpdate = timestamp;
        if (data?.performance) {
          debugInfo.performance.updateTimes.push(data.performance.duration);
        }
        if (data?.props) {
          debugInfo.props = { ...data.props };
        }
        this.logEvent(
          "component-update",
          `Component ${debugInfo.type} updated`,
          { componentId, data }
        );
        break;
      case "unmount":
        debugInfo.lifecycle.unmounted = timestamp;
        this.logEvent(
          "component-unmount",
          `Component ${debugInfo.type} unmounted`,
          { componentId }
        );
        break;
    }
  }
  /**
   * Record validation error for debugging
   */
  recordValidationError(error, componentId) {
    if (this.currentSession) {
      this.currentSession.errors.push(error);
      this.logEvent("validation-error", `Validation error: ${error.message}`, {
        error,
        componentId
      });
    }
    if (componentId) {
      const debugInfo = this.componentRegistry.get(componentId);
      if (debugInfo) {
        debugInfo.validation.passed = false;
        debugInfo.validation.errors.push(error.message);
      }
    }
  }
  /**
   * Record validation recovery for debugging
   */
  recordValidationRecovery(originalError, recoveryStrategy, componentId) {
    this.logEvent(
      "validation-recovery",
      `Recovered from validation error using ${recoveryStrategy}`,
      { originalError, recoveryStrategy, componentId }
    );
    if (componentId) {
      const debugInfo = this.componentRegistry.get(componentId);
      if (debugInfo) {
        debugInfo.validation.warnings.push(`Recovered from: ${originalError}`);
      }
    }
  }
  /**
   * Add event listener for debug events
   */
  addEventListener(type, listener) {
    if (!this.eventListeners.has(type)) {
      this.eventListeners.set(type, []);
    }
    this.eventListeners.get(type).push(listener);
  }
  /**
   * Remove event listener
   */
  removeEventListener(type, listener) {
    const listeners = this.eventListeners.get(type);
    if (listeners) {
      const index = listeners.indexOf(listener);
      if (index > -1) {
        listeners.splice(index, 1);
      }
    }
  }
  /**
   * Get debug session by ID
   */
  getSession(sessionId) {
    return this.sessions.get(sessionId);
  }
  /**
   * Get current active session
   */
  getCurrentSession() {
    return this.currentSession;
  }
  /**
   * Get all debug sessions
   */
  getAllSessions() {
    return Array.from(this.sessions.values());
  }
  /**
   * Search debug events by criteria
   */
  searchEvents(criteria) {
    if (!this.currentSession) return [];
    return this.currentSession.validationEvents.filter((event) => {
      if (criteria.type && event.type !== criteria.type) return false;
      if (criteria.componentType && event.componentType !== criteria.componentType)
        return false;
      if (criteria.timeRange) {
        if (event.timestamp < criteria.timeRange.start || event.timestamp > criteria.timeRange.end)
          return false;
      }
      if (criteria.messageContains && !event.message.includes(criteria.messageContains))
        return false;
      return true;
    });
  }
  /**
   * Analyze component performance
   */
  analyzeComponent(componentId) {
    const debugInfo = this.componentRegistry.get(componentId);
    if (!debugInfo) return null;
    if (debugInfo.performance.updateTimes.length > 0) {
      const average = debugInfo.performance.updateTimes.reduce((sum, time) => sum + time, 0) / debugInfo.performance.updateTimes.length;
      console.info(
        `📊 Component ${debugInfo.type} average update time: ${average.toFixed(2)}ms`
      );
    }
    const age = Date.now() - debugInfo.lifecycle.created;
    console.info(`📊 Component ${debugInfo.type} age: ${age}ms`);
    return debugInfo;
  }
  /**
   * Generate performance report
   */
  generatePerformanceReport() {
    if (!this.currentSession) return "No active debug session";
    const components = this.currentSession.components;
    const totalValidationTime = components.reduce(
      (sum, comp) => sum + comp.performance.validationTime,
      0
    );
    const averageValidationTime = components.length > 0 ? totalValidationTime / components.length : 0;
    const report = [
      "🔍 TachUI Validation Performance Report",
      `Session ID: ${this.currentSession.id}`,
      `Duration: ${this.currentSession.endTime ? this.currentSession.endTime - this.currentSession.startTime : "Ongoing"}ms`,
      `Components: ${components.length}`,
      `Validation Events: ${this.currentSession.validationEvents.length}`,
      `Errors: ${this.currentSession.errors.length}`,
      `Average Validation Time: ${averageValidationTime.toFixed(2)}ms`,
      "",
      "Component Performance:",
      ...components.map((comp) => {
        const updateCount = comp.performance.updateTimes.length;
        const avgUpdateTime = updateCount > 0 ? comp.performance.updateTimes.reduce(
          (sum, time) => sum + time,
          0
        ) / updateCount : 0;
        return `  ${comp.type} (${comp.id}): ${comp.performance.validationTime}ms validation, ${avgUpdateTime.toFixed(2)}ms avg update, ${updateCount} updates`;
      })
    ].join("\n");
    return report;
  }
  /**
   * Clear all debug data
   */
  clearDebugData() {
    this.sessions.clear();
    this.currentSession = null;
    this.componentRegistry.clear();
    this.eventListeners.clear();
    console.info("🔍 Debug data cleared");
  }
  /**
   * Export debug data for external analysis
   */
  exportDebugData() {
    const data = {
      sessions: Array.from(this.sessions.entries()),
      currentSession: this.currentSession,
      components: Array.from(this.componentRegistry.entries()),
      timestamp: Date.now()
    };
    return JSON.stringify(data, null, 2);
  }
  /**
   * Import debug data from external source
   */
  importDebugData(jsonData) {
    try {
      const data = JSON.parse(jsonData);
      if (data.sessions) {
        this.sessions = new Map(data.sessions);
      }
      if (data.components) {
        this.componentRegistry = new Map(data.components);
      }
      if (data.currentSession) {
        this.currentSession = data.currentSession;
      }
      console.info("🔍 Debug data imported successfully");
    } catch (error) {
      console.error("Failed to import debug data:", error);
    }
  }
  /**
   * Print session summary to console
   */
  printSessionSummary(session) {
    const duration = session.endTime ? session.endTime - session.startTime : 0;
    const errorCount = session.errors.length;
    const componentCount = session.components.length;
    const eventCount = session.validationEvents.length;
    console.group(`📊 Debug Session Summary: ${session.id}`);
    console.info(`Duration: ${duration}ms`);
    console.info(`Components: ${componentCount}`);
    console.info(`Events: ${eventCount}`);
    console.info(`Errors: ${errorCount}`);
    if (errorCount > 0) {
      console.warn(
        "Errors encountered:",
        session.errors.map((e) => e.message)
      );
    }
    const performanceEvents = session.validationEvents.filter(
      (e) => e.type === "performance-warning"
    );
    if (performanceEvents.length > 0) {
      console.warn(`Performance warnings: ${performanceEvents.length}`);
    }
    console.groupEnd();
  }
}
const validationDebugger = ValidationDebugger.getInstance();
const ValidationDebugUtils = {
  /**
   * Start debugging session
   */
  startSession: (sessionId) => validationDebugger.startSession(sessionId),
  /**
   * End debugging session
   */
  endSession: () => validationDebugger.endSession(),
  /**
   * Log debug event
   */
  logEvent: (type, message, data) => validationDebugger.logEvent(type, message, data),
  /**
   * Register component for debugging
   */
  registerComponent: (component, type, props) => validationDebugger.registerComponent(component, type, props),
  /**
   * Record validation error
   */
  recordError: (error, componentId) => validationDebugger.recordValidationError(error, componentId),
  /**
   * Record validation recovery
   */
  recordRecovery: (originalError, strategy, componentId) => validationDebugger.recordValidationRecovery(
    originalError,
    strategy,
    componentId
  ),
  /**
   * Get performance report
   */
  getPerformanceReport: () => validationDebugger.generatePerformanceReport(),
  /**
   * Search events
   */
  searchEvents: (criteria) => validationDebugger.searchEvents(criteria),
  /**
   * Export debug data
   */
  export: () => validationDebugger.exportDebugData(),
  /**
   * Import debug data
   */
  import: (data) => validationDebugger.importDebugData(data),
  /**
   * Clear all debug data
   */
  clear: () => validationDebugger.clearDebugData(),
  /**
   * Test debugging system
   */
  test: () => {
    console.group("🔍 Validation Debug System Test");
    try {
      const sessionId = validationDebugger.startSession("test-session");
      console.info("✅ Debug session started:", sessionId);
      const componentId = validationDebugger.registerComponent(
        {},
        "TestComponent",
        { prop: "value" }
      );
      console.info("✅ Test component registered:", componentId);
      validationDebugger.logEvent("validation-start", "Test validation started");
      validationDebugger.logEvent("cache-hit", "Test cache hit", {
        key: "test-key"
      });
      validationDebugger.logEvent("validation-end", "Test validation completed");
      validationDebugger.updateComponent(componentId, "mount", {
        performance: { duration: 5 }
      });
      validationDebugger.updateComponent(componentId, "update", {
        props: { updated: true }
      });
      validationDebugger.recordValidationError(
        new Error("Test error"),
        componentId
      );
      validationDebugger.recordValidationRecovery(
        "Test error",
        "fallback",
        componentId
      );
      const _report = validationDebugger.generatePerformanceReport();
      console.info("✅ Performance report generated");
      const errorEvents = validationDebugger.searchEvents({
        type: "validation-error"
      });
      console.info("✅ Event search:", errorEvents.length, "error events found");
      const session = validationDebugger.endSession();
      console.info("✅ Debug session ended:", session?.id);
      console.info("✅ Validation debugging system is working correctly");
    } catch (error) {
      console.error("❌ Validation debugging test failed:", error);
    }
    console.groupEnd();
  }
};
export {
  DeveloperErrorFactory,
  DeveloperExperienceUtils,
  DeveloperWarnings,
  DevelopmentWarnings,
  TypeValidation,
  ValidationDebugUtils,
  ValidationDebugger,
  debugManager,
  devMode,
  disableDebug,
  enableDebug,
  isDebugEnabled,
  validationDebugger
};
