/**
 * Text Overflow Prevention Utilities
 * Comprehensive system to prevent text overflow in UI components
 */

export interface TruncateOptions {
  maxLength: number;
  suffix?: string;
  preserveWords?: boolean;
}

export interface ResponsiveTruncateOptions {
  mobile: number;
  tablet: number;
  desktop: number;
  suffix?: string;
  preserveWords?: boolean;
}

/**
 * Truncate text to a specific length with ellipsis
 */
export const truncateText = (
  text: string | null | undefined,
  options: TruncateOptions
): string => {
  if (!text) return '';

  const { maxLength, suffix = '...', preserveWords = false } = options;

  if (text.length <= maxLength) return text;

  let truncated = text.slice(0, maxLength - suffix.length);

  if (preserveWords) {
    const lastSpaceIndex = truncated.lastIndexOf(' ');
    if (lastSpaceIndex > 0) {
      truncated = truncated.slice(0, lastSpaceIndex);
    }
  }

  return truncated + suffix;
};

/**
 * Get responsive truncate length based on screen size
 */
export const getResponsiveTruncateLength = (
  options: ResponsiveTruncateOptions,
  screenSize: 'mobile' | 'tablet' | 'desktop' = 'mobile'
): number => {
  return options[screenSize];
};

/**
 * Truncate text responsively based on screen size
 */
export const truncateResponsive = (
  text: string | null | undefined,
  options: ResponsiveTruncateOptions,
  screenSize: 'mobile' | 'tablet' | 'desktop' = 'mobile'
): string => {
  const maxLength = getResponsiveTruncateLength(options, screenSize);
  return truncateText(text, {
    maxLength,
    suffix: options.suffix,
    preserveWords: options.preserveWords
  });
};

/**
 * Truncate array of strings (for metadata, tags, etc.)
 */
export const truncateArray = (
  items: string[],
  maxItems: number,
  maxItemLength?: number
): string[] => {
  let result = items.slice(0, maxItems);

  if (maxItemLength) {
    result = result.map(item =>
      truncateText(item, { maxLength: maxItemLength, preserveWords: true })
    );
  }

  if (items.length > maxItems) {
    result.push(`+${items.length - maxItems} más`);
  }

  return result;
};

/**
 * Smart truncation for different content types
 */
export class TextOverflowPrevention {
  // StatusCard specific truncation
  static statusCard = {
    title: (text: string) => truncateText(text, { maxLength: 35, preserveWords: true }),
    subtitle: (text: string) => truncateText(text, { maxLength: 50, preserveWords: true }),
    primaryValueLabel: (text: string) => truncateText(text, { maxLength: 12 }),
    secondaryLabel: (text: string) => truncateText(text, { maxLength: 15 }),
    secondaryValue: (text: string) => truncateText(text, { maxLength: 25, preserveWords: true }),
    metadataItem: (text: string) => truncateText(text, { maxLength: 60, preserveWords: true }),
    actionLabel: (text: string) => truncateText(text, { maxLength: 12 }),
    progressLabel: (text: string) => truncateText(text, { maxLength: 30, preserveWords: true }),
  };

  // Mobile specific truncation (more aggressive)
  static mobile = {
    title: (text: string) => truncateText(text, { maxLength: 25, preserveWords: true }),
    subtitle: (text: string) => truncateText(text, { maxLength: 35, preserveWords: true }),
    primaryValueLabel: (text: string) => truncateText(text, { maxLength: 8 }),
    secondaryLabel: (text: string) => truncateText(text, { maxLength: 10 }),
    secondaryValue: (text: string) => truncateText(text, { maxLength: 20, preserveWords: true }),
    metadataItem: (text: string) => truncateText(text, { maxLength: 45, preserveWords: true }),
    actionLabel: (text: string) => truncateText(text, { maxLength: 8 }),
    progressLabel: (text: string) => truncateText(text, { maxLength: 25, preserveWords: true }),
    equipment: (items: string[]) => truncateArray(items, 2, 15).join(', '),
    staff: (items: string[]) => truncateArray(items, 2, 20).join(', '),
  };

  // Production specific truncation
  static production = {
    equipmentList: (items: string[]) => truncateArray(items, 3, 20).join(', '),
    staffList: (items: string[]) => truncateArray(items, 3, 25).join(', '),
    batchNumber: (text: string) => truncateText(text, { maxLength: 20 }),
    productName: (text: string) => truncateText(text, { maxLength: 30, preserveWords: true }),
    notes: (text: string) => truncateText(text, { maxLength: 100, preserveWords: true }),
  };
}

/**
 * CSS class utilities for overflow prevention
 */
export const overflowClasses = {
  truncate: 'truncate',
  truncateWithTooltip: 'truncate cursor-help',
  breakWords: 'break-words',
  breakAll: 'break-all',
  wrapAnywhere: 'break-words hyphens-auto',
  ellipsis: 'overflow-hidden text-ellipsis whitespace-nowrap',
  multilineEllipsis: 'overflow-hidden line-clamp-2',
  responsiveText: 'text-sm sm:text-base lg:text-lg',
  responsiveTruncate: 'truncate sm:text-clip lg:text-clip',
} as const;

/**
 * Generate responsive classes for different screen sizes
 */
export const getResponsiveClasses = (
  baseClasses: string,
  mobileClasses?: string,
  tabletClasses?: string,
  desktopClasses?: string
): string => {
  return [
    baseClasses,
    mobileClasses,
    tabletClasses && `sm:${tabletClasses}`,
    desktopClasses && `lg:${desktopClasses}`,
  ].filter(Boolean).join(' ');
};

/**
 * Hook-like function to determine screen size for truncation
 */
export const getScreenSize = (): 'mobile' | 'tablet' | 'desktop' => {
  if (typeof window === 'undefined') return 'desktop';

  const width = window.innerWidth;
  if (width < 768) return 'mobile';
  if (width < 1024) return 'tablet';
  return 'desktop';
};

/**
 * Safe text rendering with overflow prevention
 */
export const safeText = (
  text: string | null | undefined,
  fallback: string = '',
  maxLength?: number
): string => {
  if (!text) return fallback;
  if (!maxLength) return text;
  return truncateText(text, { maxLength, preserveWords: true });
};

export default TextOverflowPrevention;