/**
 * Debug logging utility
 * Allows conditional logging based on environment or debug flags
 */

// Check if we're in development mode or debug is explicitly enabled
const isDebugEnabled = (): boolean => {
  if (typeof window === 'undefined') {
    // Server-side: check NODE_ENV
    return process.env.NODE_ENV === 'development' || process.env.DEBUG === 'true';
  }

  // Client-side: check localStorage flag or development mode
  try {
    return (
      process.env.NODE_ENV === 'development' ||
      localStorage.getItem('debug') === 'true' ||
      window.location.search.includes('debug=true')
    );
  } catch {
    return process.env.NODE_ENV === 'development';
  }
};

/**
 * Debug logger that only outputs in development or when debug is enabled
 */
export const debug = {
  log: (...args: any[]) => {
    if (isDebugEnabled()) {
      console.log('[DEBUG]', ...args);
    }
  },

  warn: (...args: any[]) => {
    if (isDebugEnabled()) {
      console.warn('[DEBUG]', ...args);
    }
  },

  error: (...args: any[]) => {
    if (isDebugEnabled()) {
      console.error('[DEBUG]', ...args);
    }
  },

  group: (label: string) => {
    if (isDebugEnabled()) {
      console.group(`[DEBUG] ${label}`);
    }
  },

  groupEnd: () => {
    if (isDebugEnabled()) {
      console.groupEnd();
    }
  },

  time: (label: string) => {
    if (isDebugEnabled()) {
      console.time(`[DEBUG] ${label}`);
    }
  },

  timeEnd: (label: string) => {
    if (isDebugEnabled()) {
      console.timeEnd(`[DEBUG] ${label}`);
    }
  }
};

/**
 * Enable debug mode (persists in localStorage)
 */
export const enableDebug = () => {
  if (typeof window !== 'undefined') {
    localStorage.setItem('debug', 'true');
    console.log('Debug mode enabled. Reload page to see debug output.');
  }
};

/**
 * Disable debug mode
 */
export const disableDebug = () => {
  if (typeof window !== 'undefined') {
    localStorage.removeItem('debug');
    console.log('Debug mode disabled. Reload page to hide debug output.');
  }
};