/**
 * 🎨 Global Components Stylesheet System - Utility Functions
 * 
 * This file provides easy access to the global stylesheet system
 * and utility functions for all 15 refactored components.
 */

// Import the main global stylesheet
import './components-global.scss';

/**
 * Get current theme CSS variables
 * @returns {Object} Object containing current CSS variable values
 */
export const getThemeVariables = () => {
  const root = document.documentElement;
  const computedStyle = getComputedStyle(root);
  
  return {
    // Primary Colors
    primaryColor: computedStyle.getPropertyValue('--primary-color').trim(),
    primaryHover: computedStyle.getPropertyValue('--primary-hover').trim(),
    primaryLight: computedStyle.getPropertyValue('--primary-light').trim(),
    
    // Premium Colors
    premiumColor: computedStyle.getPropertyValue('--premium-color').trim(),
    premiumGradient: computedStyle.getPropertyValue('--premium-gradient').trim(),
    
    // Status Colors
    successColor: computedStyle.getPropertyValue('--success-color').trim(),
    errorColor: computedStyle.getPropertyValue('--error-color').trim(),
    warningColor: computedStyle.getPropertyValue('--warning-color').trim(),
    infoColor: computedStyle.getPropertyValue('--info-color').trim(),
    
    // Spacing
    spacingXs: computedStyle.getPropertyValue('--spacing-xs').trim(),
    spacingSm: computedStyle.getPropertyValue('--spacing-sm').trim(),
    spacingMd: computedStyle.getPropertyValue('--spacing-md').trim(),
    spacingLg: computedStyle.getPropertyValue('--spacing-lg').trim(),
    spacingXl: computedStyle.getPropertyValue('--spacing-xl').trim(),
    
    // Border Radius
    radiusSm: computedStyle.getPropertyValue('--radius-sm').trim(),
    radiusMd: computedStyle.getPropertyValue('--radius-md').trim(),
    radiusLg: computedStyle.getPropertyValue('--radius-lg').trim(),
    
    // Shadows
    shadowSm: computedStyle.getPropertyValue('--shadow-sm').trim(),
    shadowMd: computedStyle.getPropertyValue('--shadow-md').trim(),
    shadowLg: computedStyle.getPropertyValue('--shadow-lg').trim(),
  };
};

/**
 * Set a theme variable dynamically
 * @param {string} variable - CSS variable name (without --)
 * @param {string} value - New value for the variable
 */
export const setThemeVariable = (variable, value) => {
  document.documentElement.style.setProperty(`--${variable}`, value);
};

/**
 * Toggle dark mode
 * @param {boolean} isDark - Whether to enable dark mode
 */
export const toggleDarkMode = (isDark = false) => {
  const root = document.documentElement;
  
  if (isDark) {
    // Apply dark mode variables
    root.style.setProperty('--bg-white', '#1d2327');
    root.style.setProperty('--bg-light', '#2c3338');
    root.style.setProperty('--bg-lighter', '#32373c');
    root.style.setProperty('--text-primary', '#f0f0f1');
    root.style.setProperty('--text-secondary', '#c3c4c7');
    root.style.setProperty('--border-color', '#3c434a');
    root.style.setProperty('--border-light', '#50575e');
    
    // Add dark mode class to body
    document.body.classList.add('dark-mode');
  } else {
    // Reset to light mode (remove custom properties to use defaults)
    root.style.removeProperty('--bg-white');
    root.style.removeProperty('--bg-light');
    root.style.removeProperty('--bg-lighter');
    root.style.removeProperty('--text-primary');
    root.style.removeProperty('--text-secondary');
    root.style.removeProperty('--border-color');
    root.style.removeProperty('--border-light');
    
    // Remove dark mode class from body
    document.body.classList.remove('dark-mode');
  }
};

/**
 * Check if user prefers reduced motion
 * @returns {boolean} True if user prefers reduced motion
 */
export const prefersReducedMotion = () => {
  return window.matchMedia('(prefers-reduced-motion: reduce)').matches;
};

/**
 * Get current responsive breakpoint
 * @returns {string} Current breakpoint (xs, sm, md, lg, xl)
 */
export const getCurrentBreakpoint = () => {
  const width = window.innerWidth;
  
  if (width <= 480) return 'xs';
  if (width <= 768) return 'sm';
  if (width <= 992) return 'md';
  if (width <= 1200) return 'lg';
  return 'xl';
};

/**
 * Add responsive breakpoint listener
 * @param {Function} callback - Function to call when breakpoint changes
 * @returns {Function} Cleanup function to remove listeners
 */
export const addBreakpointListener = (callback) => {
  const mediaQueries = {
    xs: window.matchMedia('(max-width: 480px)'),
    sm: window.matchMedia('(max-width: 768px)'),
    md: window.matchMedia('(max-width: 992px)'),
    lg: window.matchMedia('(max-width: 1200px)'),
  };
  
  const handlers = [];
  
  Object.entries(mediaQueries).forEach(([breakpoint, mq]) => {
    const handler = (e) => callback(breakpoint, e.matches);
    mq.addListener(handler);
    handlers.push({ mq, handler });
  });
  
  // Call immediately with current state
  callback(getCurrentBreakpoint(), true);
  
  // Return cleanup function
  return () => {
    handlers.forEach(({ mq, handler }) => {
      mq.removeListener(handler);
    });
  };
};

/**
 * Apply custom theme colors
 * @param {Object} colors - Object containing color overrides
 */
export const applyCustomTheme = (colors) => {
  Object.entries(colors).forEach(([key, value]) => {
    setThemeVariable(key, value);
  });
};

/**
 * Reset theme to defaults
 */
export const resetTheme = () => {
  const root = document.documentElement;
  const customProperties = [
    '--primary-color', '--primary-hover', '--primary-light',
    '--premium-color', '--success-color', '--error-color',
    '--warning-color', '--info-color', '--bg-white', '--bg-light',
    '--bg-lighter', '--text-primary', '--text-secondary',
    '--border-color', '--border-light'
  ];
  
  customProperties.forEach(prop => {
    root.style.removeProperty(prop);
  });
  
  document.body.classList.remove('dark-mode');
};

/**
 * Get component-specific class names
 * @param {string} component - Component name
 * @returns {Object} Object containing component class names
 */
export const getComponentClasses = (component) => {
  const baseClasses = {
    container: `acb_${component}`,
    left: 'acb_left',
    right: 'acb_right',
    toggleSection: 'toogle-section',
    parentSection: 'parent-section',
    sectionChild: 'section-child',
    formInput: 'formInput',
    saveButton: 'save-webhook',
    proTag: 'PRO_TAG',
    newTag: 'NEW_TAG',
    checkbox: 'getGlobalURLCheckbox',
    statusActive: 'wpnts-log active',
    statusInactive: 'wpnts-log inactive',
  };
  
  return baseClasses;
};

/**
 * Animate element with CSS classes
 * @param {HTMLElement} element - Element to animate
 * @param {string} animation - Animation class name
 * @param {number} duration - Animation duration in ms
 */
export const animateElement = (element, animation, duration = 300) => {
  if (!element || prefersReducedMotion()) return;
  
  element.classList.add(animation);
  
  setTimeout(() => {
    element.classList.remove(animation);
  }, duration);
};

/**
 * Show toast notification (utility for components)
 * @param {string} type - Toast type (success, error, warning, info)
 * @param {string} message - Toast message
 * @param {number} duration - Duration in ms
 */
export const showToast = (type = 'info', message = '', duration = 3000) => {
  // This would integrate with your existing toast system
  console.log(`Toast [${type}]: ${message}`);
  
  // You can implement actual toast logic here
  // For now, this is a placeholder that logs to console
};

/**
 * Validate component settings
 * @param {Object} settings - Settings object to validate
 * @param {Array} requiredFields - Array of required field names
 * @returns {Object} Validation result with isValid and errors
 */
export const validateSettings = (settings, requiredFields = []) => {
  const errors = [];
  
  requiredFields.forEach(field => {
    if (!settings[field] || settings[field] === '') {
      errors.push(`${field} is required`);
    }
  });
  
  // Validate webhook URL if present
  if (settings.webhook && settings.webhook.trim() !== '') {
    const webhookPattern = /^https?:\/\/.+/;
    if (!webhookPattern.test(settings.webhook)) {
      errors.push('Webhook URL must be a valid HTTP/HTTPS URL');
    }
  }
  
  return {
    isValid: errors.length === 0,
    errors
  };
};

/**
 * Format component title for display
 * @param {string} component - Component name
 * @returns {string} Formatted title
 */
export const formatComponentTitle = (component) => {
  const titles = {
    comment: 'Comment Settings Panel',
    media: 'Media Settings Panel',
    security: 'Security Settings Panel',
    woocommerce: 'WooCommerce Settings Panel',
    author: 'Author Settings Panel',
    captcha: 'Captcha Settings Panel',
    debug_log: 'Debug Log Settings Panel',
    website_downtime_alerts: 'Downtime Alerts Panel',
    emengency_shutdown: 'Emergency Shutdown Panel',
    maintenance_mode: 'Maintenance Mode Panel',
    menu: 'Menu Settings Panel',
    pagenpost: 'Page & Post Settings Panel',
    sites: 'Site Settings Panel',
    theme: 'Theme Settings Panel',
    widgets: 'Widget Settings Panel',
  };
  
  return titles[component] || `${component} Settings Panel`;
};

// Export all utilities as default object
export default {
  getThemeVariables,
  setThemeVariable,
  toggleDarkMode,
  prefersReducedMotion,
  getCurrentBreakpoint,
  addBreakpointListener,
  applyCustomTheme,
  resetTheme,
  getComponentClasses,
  animateElement,
  showToast,
  validateSettings,
  formatComponentTitle,
};