import {
  OS_MACOS,
  OS_IOS,
  OS_IPADOS,
  OS_WINDOWS,
  OS_ANDROID_MOBILE,
  OS_ANDROID_TABLET,
} from '../preview/constants';

/**
 * Converts OS name to CSS class name format
 * @param {string} os - Operating system name (e.g., 'macOS', 'Android (Mobile)')
 * @returns {string} CSS class name (e.g., 'macos', 'android-mobile')
 */
export const getOSClassName = (os) => {
  if (os == null) return '';
  const osMap = {
    [OS_MACOS]: 'macos',
    [OS_IOS]: 'ios',
    [OS_IPADOS]: 'ipados',
    [OS_WINDOWS]: 'windows',
    [OS_ANDROID_MOBILE]: 'android-mobile',
    [OS_ANDROID_TABLET]: 'android-tablet',
  };
  return osMap[os] || String(os).toLowerCase().replace(/\s+/g, '-').replace(/[()]/g, '');
};

/**
 * Converts Browser name to CSS class name format
 * @param {string} browser - Browser name (e.g., 'Chrome', 'Firefox')
 * @returns {string} CSS class name (e.g., 'chrome', 'firefox')
 */
export const getBrowserClassName = (browser) => {
  if (typeof browser === 'string') {
    return browser.toLowerCase();
  }
  return '';
};

/**
 * Gets the combined platform + browser class name for notification-container
 * @param {string} os - Operating system name
 * @param {string} browser - Browser name
 * @returns {string} Combined class name (e.g., 'macos-chrome', 'windows-firefox')
 */
export const getNotificationContainerClassName = (os, browser) => {
  const osClass = os ? getOSClassName(os) : '';
  const browserClass = browser ? getBrowserClassName(browser) : '';
  
  // If both are missing, return empty string
  if (!osClass && !browserClass) {
    return '';
  }
  
  // Join non-empty parts with a single hyphen
  return [osClass, browserClass].filter(Boolean).join('-');
};

/**
 * Preview-only: strip protocol, drop www. only, remove child paths and trailing slashes
 * @param {string} rawUrl - Raw URL to format
 * @returns {string} Formatted URL for preview display
 */
export const formatUrlForPreview = (rawUrl) => {
  // Handle null/undefined
  if (rawUrl == null) return rawUrl;
  
  // Ensure rawUrl is a string before calling string methods
  if (typeof rawUrl !== 'string') return rawUrl;
  
  const withoutProtocol = rawUrl.replace(/^https?:\/\//i, '');
  const withoutWww = withoutProtocol.startsWith('www.') ? withoutProtocol.slice(4) : withoutProtocol;
  // Remove child paths (everything after the first slash)
  const domainOnly = withoutWww.split('/')[0];
  return domainOnly.replace(/\/+$/, '');
};

/**
 * Transforms form buttons to preview format
 * @param {Array} formButtons - Array of button objects from form
 * @returns {Array} Transformed buttons with id and label
 */
export const transformButtonsForPreview = (formButtons = []) => {
  return formButtons.map((button, index) => ({
    id: String(index + 1),
    label: button?.text || '',
  }));
};

