/**
 * logger.js
 * Centralized logging utility for DSS
 * Replaces direct console.log usage for structured, environment-aware logging
 */

// Determine if we're in development mode
const isDevelopment = () => {
  // Check various indicators of development environment
  return (
    window.location.hostname === 'localhost' ||
    window.location.hostname === '127.0.0.1' ||
    window.location.port === '3456' || // DSS development port
    window.location.search.includes('debug=true')
  );
};

// Check if debug mode is enabled
const isDebugEnabled = () => {
  return isDevelopment() || localStorage.getItem('dss_debug') === 'true';
};

/**
 * Format log message with timestamp and component context
 * @param {string} level - Log level (DEBUG, INFO, WARN, ERROR)
 * @param {string} message - Log message
 * @param {...any} args - Additional arguments
 * @returns {Array} Formatted arguments for console methods
 */
function formatLog(level, message, ...args) {
  const timestamp = new Date().toISOString().split('T')[1].slice(0, -1); // HH:MM:SS.mmm
  const prefix = `[${timestamp}] [${level}]`;

  return [prefix, message, ...args];
}

/**
 * Logger object with structured logging methods
 */
export const logger = {
  /**
   * Debug logging - only shown in development or when debug flag enabled
   * Use for detailed diagnostic information
   * @param {string} message - Log message
   * @param {...any} args - Additional data to log
   */
  debug(message, ...args) {
    if (isDebugEnabled()) {
      console.log(...formatLog('DEBUG', message, ...args));
    }
  },

  /**
   * Info logging - informational messages about normal operations
   * @param {string} message - Log message
   * @param {...any} args - Additional data to log
   */
  info(message, ...args) {
    console.info(...formatLog('INFO', message, ...args));
  },

  /**
   * Warning logging - potentially harmful situations
   * @param {string} message - Log message
   * @param {...any} args - Additional data to log
   */
  warn(message, ...args) {
    console.warn(...formatLog('WARN', message, ...args));
  },

  /**
   * Error logging - error events that might still allow the application to continue
   * @param {string} message - Log message
   * @param {...any} args - Additional data to log (typically Error objects)
   */
  error(message, ...args) {
    console.error(...formatLog('ERROR', message, ...args));
  },

  /**
   * Performance timing helper
   * Returns a function that logs elapsed time when called
   * @param {string} label - Label for the timing measurement
   * @returns {Function} Function to call when operation completes
   *
   * @example
   * const endTimer = logger.time('Data load');
   * await loadData();
   * endTimer(); // Logs: [TIME] Data load: 234ms
   */
  time(label) {
    const start = performance.now();
    return () => {
      if (isDebugEnabled()) {
        const elapsed = (performance.now() - start).toFixed(2);
        console.log(...formatLog('TIME', `${label}: ${elapsed}ms`));
      }
    };
  },

  /**
   * Enable debug mode (persists in localStorage)
   */
  enableDebug() {
    localStorage.setItem('dss_debug', 'true');
    this.info('Debug mode enabled');
  },

  /**
   * Disable debug mode
   */
  disableDebug() {
    localStorage.removeItem('dss_debug');
    this.info('Debug mode disabled');
  },

  /**
   * Check if debug mode is enabled
   * @returns {boolean}
   */
  isDebugEnabled() {
    return isDebugEnabled();
  }
};

// Export as default for convenience
export default logger;

// Make logger available globally for console debugging
if (isDevelopment()) {
  window.dssLogger = logger;
  logger.debug('[Logger] Logger utility initialized. Access via window.dssLogger');
  logger.debug('[Logger] Enable debug: logger.enableDebug() | Disable: logger.disableDebug()');
}
