'use client';
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/

const DEBUG_LOGS_LOCAL_STORAGE_KEY = "viewer-debug-logs-enabled";
const LOG_FROM_WORKER = false; // Workers don't have access to localStorage, so we need a fallback value for them. We default to false to avoid spamming logs from workers, but this can be changed by setting the value in the main thread before the worker is initialized.

// Singleton class used for logging across our apps
// Is controlled by DEBUG_LOGS_LOCAL_STORAGE_KEY key
class Logger {
  constructor() {}
  static get debugLogsEnabled() {
    if (Logger._debugLogsEnabled === null) {
      if (typeof localStorage === "undefined") {
        Logger._debugLogsEnabled = LOG_FROM_WORKER;
        return LOG_FROM_WORKER;
      }
      const storedValue = localStorage.getItem(DEBUG_LOGS_LOCAL_STORAGE_KEY);
      Logger._debugLogsEnabled = storedValue === "true";
    }
    return Logger._debugLogsEnabled;
  }
  static set debugLogsEnabled(value) {
    Logger._debugLogsEnabled = value;
    if (typeof localStorage === "undefined") {
      console.warn("cannot interact with localStorage in worker");
      return;
    }
    localStorage.setItem(DEBUG_LOGS_LOCAL_STORAGE_KEY, value ? "true" : "false");
  }

  // biome-ignore lint/suspicious/noExplicitAny: <explanation>
  log(message, ...optionalParams) {
    if (Logger.debugLogsEnabled) {
      console.log(message, ...optionalParams);
    }
  }
  info(message, ...optionalParams) {
    if (Logger.debugLogsEnabled) {
      console.log(message, ...optionalParams);
    }
  }

  // biome-ignore lint/suspicious/noExplicitAny: <explanation>
  debug(message, ...optionalParams) {
    if (Logger.debugLogsEnabled) {
      console.debug(message, ...optionalParams);
    }
  }

  // biome-ignore lint/suspicious/noExplicitAny: <explanation>
  warn(message, ...optionalParams) {
    if (Logger.debugLogsEnabled) {
      console.warn(message, ...optionalParams);
    }
  }

  // biome-ignore lint/suspicious/noExplicitAny: <explanation>
  error(message, ...optionalParams) {
    if (Logger.debugLogsEnabled) {
      console.error(message, ...optionalParams);
    }
  }
  static getLogger() {
    if (!Logger.instance) {
      Logger.instance = new Logger();
    }
    return Logger.instance;
  }
}
Logger.instance = null;
Logger._debugLogsEnabled = null;

export { Logger as L };
