"use strict";
/**
 * @file useAiOptimization.ts
 * Hook for AI-powered component optimization
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.useAiOptimization = useAiOptimization;
const react_1 = require("react");
/**
 * Hook for AI-powered component optimization
 */
function useAiOptimization(config) {
    const { component, enabled = true, optimizationLevel = 'medium' } = config;
    const [optimizedProps, setOptimizedProps] = (0, react_1.useState)({});
    const [performanceScore, setPerformanceScore] = (0, react_1.useState)(100);
    const interactionsRef = (0, react_1.useRef)([]);
    const optimizationRef = (0, react_1.useRef)();
    // Record component interaction
    const recordInteraction = (0, react_1.useCallback)((data) => {
        if (!enabled)
            return;
        interactionsRef.current.push(data);
        // Keep only last 100 interactions
        if (interactionsRef.current.length > 100) {
            interactionsRef.current = interactionsRef.current.slice(-100);
        }
        // Trigger optimization analysis
        if (optimizationRef.current) {
            clearTimeout(optimizationRef.current);
        }
        optimizationRef.current = setTimeout(() => {
            analyzeAndOptimize();
        }, 1000);
    }, [enabled]);
    // Analyze interactions and optimize
    const analyzeAndOptimize = (0, react_1.useCallback)(() => {
        const interactions = interactionsRef.current;
        if (interactions.length < 5)
            return; // Need minimum data
        // Calculate interaction patterns
        const recentInteractions = interactions.slice(-20);
        const avgTimeBetween = calculateAverageTimeBetween(recentInteractions);
        const interactionRate = recentInteractions.length / 20;
        // Determine optimizations
        const optimizations = {
            'data-ai-optimized': 'true',
        };
        // High-frequency component - optimize rendering
        if (avgTimeBetween < 2000 && interactionRate > 0.5) {
            optimizations.style = {
                willChange: 'transform, opacity',
                contain: 'layout style',
            };
            if (optimizationLevel === 'high') {
                optimizations.style.transform = 'translateZ(0)'; // GPU acceleration
            }
        }
        // Low-frequency component - optimize for memory
        if (avgTimeBetween > 10000 && interactionRate < 0.1) {
            optimizations.style = {
                willChange: 'auto',
                contain: 'none',
            };
        }
        setOptimizedProps(optimizations);
        // Update performance score
        const score = calculatePerformanceScore(interactions);
        setPerformanceScore(score);
        // Send to AI service if available
        if (window.Drupal?.llmAI) {
            window.Drupal.llmAI.reportOptimization({
                component,
                optimizations,
                performanceScore: score,
                interactionCount: interactions.length,
            });
        }
    }, [component, optimizationLevel]);
    // Calculate average time between interactions
    const calculateAverageTimeBetween = (interactions) => {
        if (interactions.length < 2)
            return Infinity;
        let totalTime = 0;
        for (let i = 1; i < interactions.length; i++) {
            totalTime += interactions[i].timestamp - interactions[i - 1].timestamp;
        }
        return totalTime / (interactions.length - 1);
    };
    // Calculate performance score
    const calculatePerformanceScore = (interactions) => {
        // Simple scoring based on interaction patterns
        const recentCount = interactions.slice(-10).length;
        const totalCount = interactions.length;
        let score = 100;
        // Penalize if too many rapid interactions (possible performance issue)
        const rapidInteractions = interactions.filter((interaction, index) => {
            if (index === 0)
                return false;
            return interaction.timestamp - interactions[index - 1].timestamp < 100;
        }).length;
        if (rapidInteractions > totalCount * 0.2) {
            score -= 20;
        }
        return Math.max(0, Math.min(100, score));
    };
    // Monitor component performance
    (0, react_1.useEffect)(() => {
        if (!enabled || typeof window === 'undefined')
            return;
        // Use Performance Observer if available
        if ('PerformanceObserver' in window) {
            const observer = new PerformanceObserver((list) => {
                list.getEntries().forEach((entry) => {
                    if (entry.name.includes(component)) {
                        // Analyze performance metrics
                        if (entry.duration > 100) {
                            console.warn(`[AI Optimization] Slow ${component} render:`, entry.duration);
                        }
                    }
                });
            });
            try {
                observer.observe({ entryTypes: ['measure', 'navigation'] });
                return () => observer.disconnect();
            }
            catch (e) {
                // Observer not supported for this entry type
            }
        }
    }, [enabled, component]);
    // Cleanup
    (0, react_1.useEffect)(() => {
        return () => {
            if (optimizationRef.current) {
                clearTimeout(optimizationRef.current);
            }
        };
    }, []);
    return {
        optimizedProps,
        performanceScore,
        recordInteraction,
        isOptimizing: enabled,
    };
}
//# sourceMappingURL=useAiOptimization.js.map