/**
 * Frontend Error Handler
 * Centralized error handling and logging
 */

(function () {
  "use strict";

  class ErrorHandler {
    constructor() {
      this.errors = [];
      this.maxErrors = 100;
      this.productionMode = window.location.hostname !== "localhost";
    }

    log(context, error, level = "error") {
      const errorEntry = {
        timestamp: new Date().toISOString(),
        context,
        message: error?.message || error,
        level,
        stack: error?.stack,
      };

      this.errors.push(errorEntry);
      if (this.errors.length > this.maxErrors) {
        this.errors.shift();
      }

      // Only log to console in development
      if (!this.productionMode && level === "error") {
        console.error(`[${context}]`, error);
      } else if (!this.productionMode && level === "warn") {
        console.warn(`[${context}]`, error);
      }
    }

    getErrors() {
      return [...this.errors];
    }

    clearErrors() {
      this.errors = [];
    }
  }

  // Global error handler
  window.ErrorHandler = window.ErrorHandler || new ErrorHandler();

  // Global error event handler
  window.addEventListener("error", (event) => {
    window.ErrorHandler.log(
      "GlobalError",
      event.error || event.message,
      "error"
    );
  });

  // Unhandled promise rejection handler
  window.addEventListener("unhandledrejection", (event) => {
    window.ErrorHandler.log("UnhandledRejection", event.reason, "error");
  });
})();
