/**
 * Standalone loglevel stand-in for the playground.
 * Avoids Vite CJS interop fights with the real package; matrix-js-sdk only needs
 * getLogger / levels / methodFactory / setLevel / rebuild.
 */

const levels = {
  TRACE: 0,
  DEBUG: 1,
  INFO: 2,
  WARN: 3,
  ERROR: 4,
  SILENT: 5,
};

const loggers = new Map();

function defaultMethodFactory(methodName) {
  return (...args) => {
    const supported =
      methodName === 'error' ||
      methodName === 'warn' ||
      methodName === 'trace' ||
      methodName === 'info' ||
      methodName === 'debug';
    if (supported) console[methodName](...args);
    else console.log(...args);
  };
}

function createLogger(name) {
  const logger = {
    name,
    prefix: undefined,
    methodFactory: defaultMethodFactory,
    getChild: undefined,
    setLevel(_level, _persist) {},
    getLevel() {
      return levels.WARN;
    },
    setDefaultLevel() {},
    enableAll() {},
    disableAll() {},
    rebuild() {
      for (const methodName of ['trace', 'debug', 'info', 'warn', 'error']) {
        logger[methodName] = logger.methodFactory(methodName, levels.DEBUG, name);
      }
    },
  };
  logger.rebuild();
  // matrix-js-sdk expects console-like `.log` (e.g. logger.log.bind(logger)).
  logger.log = logger.info;
  return logger;
}

const loglevel = createLogger('root');
loglevel.levels = levels;
loglevel.getLogger = (name) => {
  const key = String(name ?? 'default');
  if (!loggers.has(key)) loggers.set(key, createLogger(key));
  return loggers.get(key);
};
loglevel.methodFactory = defaultMethodFactory;

export default loglevel;
