/**
 * Simple Performance Optimizations for HTML Editor
 *
 * Practical optimizations that improve performance without complexity:
 * - Memoization
 * - Debouncing improvements
 * - Memory cleanup
 * - Bundle size optimizations
 */

import React, { useCallback, useMemo, useRef, useEffect } from 'react';

/**
 * Enhanced debounce with content-size awareness
 * Automatically adjusts delays based on content size
 */
export const useSmartDebounce = (callback, baseDelay = 300) => {
  const timeoutRef = useRef(null);

  // Cleanup timeout on unmount to prevent callbacks after component unmount
  useEffect(() => {
    return () => {
      if (timeoutRef.current) {
        clearTimeout(timeoutRef.current);
      }
    };
  }, []);

  return useCallback((value, contentSize = 0) => {
    if (timeoutRef.current) {
      clearTimeout(timeoutRef.current);
    }

    // Adjust delay based on content size, using baseDelay as starting point
    let delay = baseDelay;
    if (contentSize > PERFORMANCE_THRESHOLDS.LARGE_CONTENT_DEBOUNCE) {
      delay = baseDelay * 2;        // Large content: double the base delay
    } else if (contentSize > PERFORMANCE_THRESHOLDS.MEDIUM_CONTENT_DEBOUNCE) {
      delay = Math.round(baseDelay * 1.33); // Medium content: increase base delay by 33%
    } else if (contentSize < PERFORMANCE_THRESHOLDS.SMALL_CONTENT_DEBOUNCE) {
      delay = Math.max(Math.round(baseDelay * (2/3)), 100); // Small content: reduce to 2/3 of base delay, min 100ms
    }
    // For content between SMALL_CONTENT_DEBOUNCE and MEDIUM_CONTENT_DEBOUNCE, use baseDelay as-is

    timeoutRef.current = setTimeout(() => {
      callback(value);
    }, delay);
  }, [callback, baseDelay]);
};

/**
 * Memory-optimized component wrapper
 * Prevents unnecessary re-renders
 */
export const withPerformanceOptimization = (Component) => {
  return React.memo(Component, (prevProps, nextProps) => {
    // Skip re-render if content hasn't actually changed
    if (prevProps.content === nextProps.content &&
        prevProps.variant === nextProps.variant &&
        prevProps.readOnly === nextProps.readOnly) {
      return true;
    }
    return false;
  });
};

/**
 * Cleanup utility for preventing memory leaks
 * Uses ref-based stabilization so callers don't need to memoize the cleanup function
 */
export const useCleanup = (cleanupFn) => {
  const cleanupRef = useRef(cleanupFn);

  // Update ref on every render to capture latest cleanup function
  cleanupRef.current = cleanupFn;

  useEffect(() => {
    // Return a stable cleanup wrapper that reads the latest ref value
    return () => {
      if (cleanupRef.current && typeof cleanupRef.current === 'function') {
        cleanupRef.current();
      }
    };
  }, []); // Empty dependency array - effect only runs once
};

/**
 * Content size analyzer for performance decisions
 */
export const analyzeContentSize = (content) => {
  const size = typeof content === 'string' ? content.length : 0;

  return {
    size,
    isSmall: size < PERFORMANCE_THRESHOLDS.SMALL_CONTENT_ANALYSIS,    // < 10KB
    isMedium: size < PERFORMANCE_THRESHOLDS.LARGE_CONTENT_ANALYSIS,   // < 50KB
    isLarge: size >= PERFORMANCE_THRESHOLDS.LARGE_CONTENT_ANALYSIS,   // >= 50KB
    shouldOptimize: size > PERFORMANCE_THRESHOLDS.SMALL_CONTENT_ANALYSIS,
    recommendedDebounce: size > PERFORMANCE_THRESHOLDS.LARGE_CONTENT_ANALYSIS ?
      PERFORMANCE_THRESHOLDS.DEBOUNCE_SLOW :
      size > PERFORMANCE_THRESHOLDS.SMALL_CONTENT_ANALYSIS ?
        400 :
        PERFORMANCE_THRESHOLDS.DEBOUNCE_FAST
  };
};

/**
 * Simple virtualization for very large content
 * Only renders visible portions
 */
export const useVirtualization = (content, threshold = 100000) => {
  return useMemo(() => {
    // Handle non-string content gracefully
    if (!content || typeof content !== 'string' || content.length < threshold) {
      return { content, isVirtualized: false };
    }

    // For very large content, show first 50KB with indicator
    const truncated = content.substring(0, 50000);
    return {
      content: truncated + '\n\n<!-- Content truncated for performance -->',
      isVirtualized: true,
      originalSize: content.length
    };
  }, [content, threshold]);
};

/**
 * Performance constants
 */
export const PERFORMANCE_THRESHOLDS = {
  // Content size thresholds for debouncing (useSmartDebounce)
  SMALL_CONTENT_DEBOUNCE: 1000,    // 1KB - threshold for fast debouncing
  MEDIUM_CONTENT_DEBOUNCE: 10000,  // 10KB - threshold for medium debouncing
  LARGE_CONTENT_DEBOUNCE: 50000,   // 50KB - threshold for slow debouncing

  // Content size thresholds for analysis (analyzeContentSize)
  SMALL_CONTENT_ANALYSIS: 10000,   // 10KB - for general content analysis
  LARGE_CONTENT_ANALYSIS: 50000,   // 50KB - for general content analysis
  HUGE_CONTENT: 100000,            // 100KB - for virtualization

  DEBOUNCE_FAST: 200,
  DEBOUNCE_NORMAL: 300,
  DEBOUNCE_SLOW: 600
};
