const LOG_LEVELS = {
  DEBUG: 0,
  INFO: 1,
  WARN: 2,
  ERROR: 3,
};

// Default log level based on environment
const currentEnv = process.env.NODE_ENV || 'development';
const isDev = currentEnv === 'development';
const GLOBAL_LOG_LEVEL = isDev ? LOG_LEVELS.DEBUG : LOG_LEVELS.WARN;

const style = (bg, color) => `background: ${bg}; color: ${color}; padding: 2px 5px; border-radius: 4px; font-weight: bold;`;

const PREFIX = '%c[NearlExpress]';
const PREFIX_STYLE = style('#2563eb', '#ffffff');

// Capture original console methods before any global overrides occur
const originalLog = console.log;
const originalWarn = console.warn || console.log;
const originalError = console.error || console.log;

const print = (levelName, args, labelStyle) => {
  const levelValue = LOG_LEVELS[levelName];
  if (levelValue < GLOBAL_LOG_LEVEL) return;

  const [message, ...extra] = args;
  const isMessageString = typeof message === 'string';

  const formatPrefix = `${PREFIX}%c ${levelName}`;
  const styles = [PREFIX_STYLE, labelStyle];

  const consoleMethod =
    levelName === 'ERROR' ? originalError :
    levelName === 'WARN' ? originalWarn :
    originalLog;

  if (isMessageString) {
    consoleMethod(
      `${formatPrefix}%c ${message}`,
      ...styles,
      'color: inherit;',
      ...extra
    );
  } else {
    // If first argument is an object/array, preserve raw interactive log
    consoleMethod(
      `${formatPrefix}`,
      ...styles,
      message,
      ...extra
    );
  }
};

const logger = {
  debug: (...args) => print('DEBUG', args, style('#64748b', '#ffffff')),
  info: (...args) => print('INFO', args, style('#10b981', '#ffffff')),
  warn: (...args) => print('WARN', args, style('#f59e0b', '#ffffff')),
  error: (...args) => {
    print('ERROR', args, style('#ef4444', '#ffffff'));
    // Future expansion hook: e.g., Sentry.captureException(args[0]);
  },
};

export default logger;
