"use strict";
/**
 * @file usePredictiveLoading.ts
 * Hook for predictive resource loading based on user behavior
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.usePredictiveLoading = usePredictiveLoading;
const react_1 = require("react");
/**
 * Hook for predictive resource loading
 */
function usePredictiveLoading(config) {
    const { target, enabled = true, threshold = 0.7, preloadDelay = 300, } = config;
    const [state, setState] = (0, react_1.useState)({
        isPredicting: false,
        confidence: 0,
        preloaded: false,
        resources: [],
    });
    const hoverStartRef = (0, react_1.useRef)(0);
    const preloadTimeoutRef = (0, react_1.useRef)();
    const interactionHistoryRef = (0, react_1.useRef)([]);
    // Preload resources
    const preload = (0, react_1.useCallback)(() => {
        if (!enabled || !target || state.preloaded)
            return;
        const resources = [];
        // Preload link
        if (target.startsWith('http') || target.startsWith('/')) {
            const link = document.createElement('link');
            link.rel = 'prefetch';
            link.href = target;
            link.as = 'document';
            document.head.appendChild(link);
            resources.push(target);
            // Also preload as DNS
            const dnsLink = document.createElement('link');
            dnsLink.rel = 'dns-prefetch';
            const url = new URL(target, window.location.origin);
            dnsLink.href = url.origin;
            document.head.appendChild(dnsLink);
        }
        // Preload related resources based on target
        const relatedResources = predictRelatedResources(target);
        relatedResources.forEach(resource => {
            const link = document.createElement('link');
            link.rel = 'prefetch';
            link.href = resource;
            document.head.appendChild(link);
            resources.push(resource);
        });
        setState(prev => ({
            ...prev,
            preloaded: true,
            resources,
        }));
        // Report to AI service
        if (window.Drupal?.llmAI) {
            window.Drupal.llmAI.recordInteraction({
                component: 'predictive-loading',
                action: 'preload',
                target,
                resources,
                confidence: state.confidence,
            });
        }
    }, [enabled, target, state.preloaded, state.confidence]);
    // Predict user intent based on interaction
    const predictIntent = (0, react_1.useCallback)((interactionType) => {
        if (!enabled)
            return;
        const now = Date.now();
        interactionHistoryRef.current.push({ type: interactionType, timestamp: now });
        // Keep only recent interactions
        interactionHistoryRef.current = interactionHistoryRef.current.filter(interaction => now - interaction.timestamp < 5000);
        // Calculate confidence based on interaction patterns
        const confidence = calculateConfidence(interactionHistoryRef.current, interactionType);
        setState(prev => ({
            ...prev,
            confidence,
            isPredicting: confidence > threshold,
        }));
        // Start preload if confidence is high
        if (confidence > threshold && interactionType === 'hover') {
            if (preloadTimeoutRef.current) {
                clearTimeout(preloadTimeoutRef.current);
            }
            preloadTimeoutRef.current = setTimeout(() => {
                preload();
            }, preloadDelay);
        }
    }, [enabled, threshold, preloadDelay, preload]);
    // Calculate confidence score
    const calculateConfidence = (history, currentType) => {
        let score = 0;
        // Base score for interaction type
        const baseScores = {
            hover: 0.3,
            focus: 0.4,
            mousemove: 0.1,
            touchstart: 0.5,
        };
        score += baseScores[currentType] || 0;
        // Increase score for repeated interactions
        const sameTypeCount = history.filter(h => h.type === currentType).length;
        score += Math.min(0.3, sameTypeCount * 0.1);
        // Increase score for hover duration
        if (currentType === 'hover' && hoverStartRef.current > 0) {
            const hoverDuration = Date.now() - hoverStartRef.current;
            score += Math.min(0.3, hoverDuration / 3000); // Max 0.3 after 3 seconds
        }
        // Machine learning pattern detection
        if (history.length >= 3) {
            const pattern = detectPattern(history);
            if (pattern === 'intent-to-click') {
                score += 0.2;
            }
        }
        return Math.min(1, score);
    };
    // Detect interaction patterns
    const detectPattern = (history) => {
        const types = history.map(h => h.type).join(',');
        // Common patterns indicating intent to click
        const clickPatterns = [
            'hover,mousemove,hover',
            'focus,hover',
            'touchstart,touchstart',
        ];
        for (const pattern of clickPatterns) {
            if (types.includes(pattern)) {
                return 'intent-to-click';
            }
        }
        return null;
    };
    // Predict related resources
    const predictRelatedResources = (targetUrl) => {
        const resources = [];
        // Common assets that might be needed
        const url = new URL(targetUrl, window.location.origin);
        const basePath = url.pathname.split('/').slice(0, -1).join('/');
        // Predict common resources
        resources.push(`${basePath}/styles.css`);
        resources.push(`${basePath}/bundle.js`);
        // Predict API endpoints
        if (targetUrl.includes('/node/') || targetUrl.includes('/api/')) {
            resources.push(`${url.origin}/jsonapi${url.pathname}`);
        }
        return resources.filter(r => r !== targetUrl);
    };
    // Handle hover start
    const onHoverStart = (0, react_1.useCallback)(() => {
        hoverStartRef.current = Date.now();
        predictIntent('hover');
    }, [predictIntent]);
    // Handle hover end
    const onHoverEnd = (0, react_1.useCallback)(() => {
        hoverStartRef.current = 0;
        if (preloadTimeoutRef.current) {
            clearTimeout(preloadTimeoutRef.current);
        }
        setState(prev => ({
            ...prev,
            isPredicting: false,
        }));
    }, []);
    // Cleanup
    (0, react_1.useEffect)(() => {
        return () => {
            if (preloadTimeoutRef.current) {
                clearTimeout(preloadTimeoutRef.current);
            }
        };
    }, []);
    return {
        preload,
        predictIntent,
        onHoverStart,
        onHoverEnd,
        isPredicting: state.isPredicting,
        confidence: state.confidence,
        preloaded: state.preloaded,
        preloadedResources: state.resources,
    };
}
//# sourceMappingURL=usePredictiveLoading.js.map