/**
 * useEditorContent - Custom hook for managing unified editor content state
 *
 * Handles unified HTML content with embedded CSS and JavaScript
 * Simplified from separate language management to single editor approach
 */

import { useState, useCallback, useRef, useEffect, useMemo } from 'react';
import { PERFORMANCE } from '../constants';
import { useSmartDebounce, analyzeContentSize, useCleanup } from '../utils/simplePerformance';

/**
 * Custom hook for unified editor content management
 *
 * @param {string} initialContent - Initial unified HTML content
 * @param {Object} options - Configuration options
 * @returns {Object} Content state and methods
 */
const DEFAULT_CONTENT = `<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>HTML Editor Preview</title>
    <style>
        /* Your CSS styles here */
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f5f5f5;
        }

        .container {
            max-width: 800px;
            margin: 0 auto;
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>Welcome to HTML Editor</h1>
        <p>Start editing your HTML, CSS, and JavaScript code above to see the live preview here.</p>
        <button id="demoButton">Click me!</button>
    </div>

    <script>
        // Your JavaScript code here
        document.getElementById('demoButton').addEventListener('click', function() {
            alert('Hello from the HTML Editor!');
        });
    </script>
</body>
</html>`;

export const useEditorContent = (
  initialContent = null,
  options = {}
) => {
  const {
    autoSave = true,
    autoSaveInterval = PERFORMANCE.AUTO_SAVE_INTERVAL,
    onSave = null,
    onChange = null
  } = options;

  // Unified content state
  // Use DEFAULT_CONTENT only if initialContent is null or undefined (not empty string)
  // This allows explicitly passing empty string for empty content
  const initialContentValue = initialContent == null ? DEFAULT_CONTENT : initialContent;
  const [content, setContent] = useState(initialContentValue);
  const [isDirty, setIsDirty] = useState(false);
  const [lastSaved, setLastSaved] = useState(null);
  const [isAutoSaveEnabled, setIsAutoSaveEnabled] = useState(autoSave);

  // Refs for performance optimization
  const onChangeDebounceRef = useRef(null);
  const validationDebounceRef = useRef(null);
  const autoSaveRef = useRef(null);
  const validationCallbackRef = useRef(null);
  const lastContentRef = useRef(initialContentValue);

  // Smart debouncing hooks
  const debouncedOnChange = useSmartDebounce(onChange || (() => {}), PERFORMANCE.PREVIEW_UPDATE_DEBOUNCE);
  const debouncedValidation = useSmartDebounce((content) => {
    if (validationCallbackRef.current) {
      validationCallbackRef.current(content);
    }
  }, PERFORMANCE.VALIDATION_DEBOUNCE);

  // Update unified content
  const updateContent = useCallback((value, immediate = false) => {
    setContent(prevContent => {
      // Skip update if content hasn't actually changed
      if (prevContent === value) {
        return prevContent;
      }

      // Analyze content for performance optimization
      const analysis = analyzeContentSize(value);

      // Use smart debouncing for callbacks
      if (onChange) {
        if (immediate) {
          onChange(value);
        } else {
          debouncedOnChange(value, analysis.size);
        }
      }

      // Use smart debouncing for validation
      if (validationCallbackRef.current) {
        if (immediate) {
          validationCallbackRef.current(value);
        } else {
          debouncedValidation(value, analysis.size);
        }
      }

      // Update refs
      lastContentRef.current = value;

      return value;
    });

    setIsDirty(true);
  }, [onChange, debouncedOnChange, debouncedValidation]);

  // Get current unified content
  const currentContent = useMemo(() => {
    return content || '';
  }, [content]);

  // Check if content exists
  const hasContent = useCallback(() => {
    return content && typeof content === 'string' && content.trim().length > 0;
  }, [content]);

  // Get content size for performance monitoring
  const getContentSize = useCallback(() => {
    return (content && typeof content === 'string') ? content.length : 0;
  }, [content]);

  // Performance analysis
  const contentAnalysis = useMemo(() => {
    return analyzeContentSize(content);
  }, [content]);

  // Check if content is large (for performance warnings)
  const isLargeContent = useMemo(() => {
    return contentAnalysis.isLarge;
  }, [contentAnalysis.isLarge]);

  // Mark content as saved
  const markAsSaved = useCallback(() => {
    setIsDirty(false);
    setLastSaved(new Date());
  }, []);

  // Reset all content
  const resetContent = useCallback(() => {
    const contentToUse = initialContent || DEFAULT_CONTENT;
    setContent(contentToUse);
    setIsDirty(false);
    setLastSaved(null);
    lastContentRef.current = contentToUse;
  }, [initialContent]);

  // Save content (calls onSave callback if provided)
  const saveContent = useCallback(async () => {
    if (onSave && isDirty) {
      try {
        await onSave(content);
        markAsSaved();
        return true;
      } catch (error) {
        console.error('Failed to save content:', error);
        return false;
      }
    }
    return false;
  }, [content, isDirty, onSave, markAsSaved]);

  // Register validation callback
  const registerValidationCallback = useCallback((callback) => {
    validationCallbackRef.current = callback;
  }, []);

  // Unregister validation callback
  const unregisterValidationCallback = useCallback(() => {
    validationCallbackRef.current = null;
  }, []);

  // Toggle auto-save
  const toggleAutoSave = useCallback(() => {
    setIsAutoSaveEnabled(prev => !prev);
  }, []);

  // Force validation
  const validateContent = useCallback(() => {
    if (validationCallbackRef.current) {
      validationCallbackRef.current(content);
    }
  }, [content]);

  // Auto-save effect
  useEffect(() => {
    if (isAutoSaveEnabled && isDirty && autoSaveInterval > 0) {
      autoSaveRef.current = setTimeout(() => {
        saveContent();
      }, autoSaveInterval);

      return () => {
        if (autoSaveRef.current) {
          clearTimeout(autoSaveRef.current);
        }
      };
    }
  }, [isDirty, isAutoSaveEnabled, autoSaveInterval, saveContent]);

  // Cleanup effect with performance optimization
  useCleanup(() => {
    if (onChangeDebounceRef.current) {
      clearTimeout(onChangeDebounceRef.current);
      onChangeDebounceRef.current = null;
    }
    if (validationDebounceRef.current) {
      clearTimeout(validationDebounceRef.current);
      validationDebounceRef.current = null;
    }
    if (autoSaveRef.current) {
      clearTimeout(autoSaveRef.current);
      autoSaveRef.current = null;
    }
  });

  // Return state and methods
  return {
    // Content state
    content: currentContent,
    isDirty,
    lastSaved,
    isAutoSaveEnabled,
    isLargeContent,

    // Content methods
    updateContent,
    hasContent,
    getContentSize,
    resetContent,
    saveContent,
    markAsSaved,

    // Auto-save methods
    toggleAutoSave,

    // Validation methods
    registerValidationCallback,
    unregisterValidationCallback,
    validateContent,

    // Computed properties
    canSave: isDirty && onSave !== null,
    isEmpty: !hasContent(),
    characterCount: getContentSize(),

    // Performance indicators
    shouldShowPerformanceWarning: isLargeContent,
    contentAnalysis
  };
};

export default useEditorContent;