import { useState, useRef, useCallback, useMemo } from 'react';

function useChartAccessibility({ chartType, data, config, title, description, enableKeyboardNavigation = true, }) {
    const [focusedElementIndex, setFocusedElementIndex] = useState(-1);
    const [isKeyboardMode, setIsKeyboardMode] = useState(false);
    const descriptionId = useRef(`chart-description-${Math.random().toString(36).substr(2, 9)}`);
    // Generate chart summary for screen readers
    const generateChartSummary = useCallback(() => {
        var _a;
        const dataKeys = Object.keys(config);
        const dataCount = data.length;
        let summary = '';
        // Chart type and basic info
        switch (chartType) {
            case 'bar':
                summary = `Bar chart with ${dataCount} categories`;
                break;
            case 'line':
                summary = `Line chart with ${dataCount} data points`;
                break;
            case 'area':
                summary = `Area chart with ${dataCount} data points`;
                break;
            case 'heatmap':
                summary = `Heatmap with ${dataCount} data cells`;
                break;
        }
        // Add series information
        if (dataKeys.length > 1) {
            summary += ` showing ${dataKeys.length} data series: ${dataKeys.map(key => { var _a; return ((_a = config[key]) === null || _a === void 0 ? void 0 : _a.label) || key; }).join(', ')}`;
        }
        else if (dataKeys.length === 1) {
            const seriesLabel = ((_a = config[dataKeys[0]]) === null || _a === void 0 ? void 0 : _a.label) || dataKeys[0];
            summary += ` showing ${seriesLabel}`;
        }
        // Add data range information for numeric charts
        if (chartType !== 'heatmap' && data.length > 0) {
            const values = data.flatMap(item => dataKeys.map(key => typeof item[key] === 'number' ? item[key] : 0)).filter(val => val !== 0);
            if (values.length > 0) {
                const min = Math.min(...values);
                const max = Math.max(...values);
                summary += `. Values range from ${min} to ${max}`;
            }
        }
        return summary;
    }, [chartType, data, config]);
    // Generate ARIA label
    const generateAriaLabel = useCallback(() => {
        if (title) {
            return `${title}. ${generateChartSummary()}`;
        }
        return generateChartSummary();
    }, [title, generateChartSummary]);
    // Handle keyboard navigation
    const handleKeyDown = useCallback((event) => {
        if (!enableKeyboardNavigation)
            return;
        // Enable keyboard mode on first keyboard interaction
        if (!isKeyboardMode) {
            setIsKeyboardMode(true);
        }
        const maxIndex = data.length - 1;
        switch (event.key) {
            case 'ArrowRight':
            case 'ArrowDown':
                event.preventDefault();
                setFocusedElementIndex(prev => prev >= maxIndex ? 0 : prev + 1);
                break;
            case 'ArrowLeft':
            case 'ArrowUp':
                event.preventDefault();
                setFocusedElementIndex(prev => prev <= 0 ? maxIndex : prev - 1);
                break;
            case 'Home':
                event.preventDefault();
                setFocusedElementIndex(0);
                break;
            case 'End':
                event.preventDefault();
                setFocusedElementIndex(maxIndex);
                break;
            case 'Escape':
                event.preventDefault();
                setFocusedElementIndex(-1);
                setIsKeyboardMode(false);
                break;
        }
    }, [enableKeyboardNavigation, isKeyboardMode, data.length]);
    // Reset keyboard mode on mouse interaction
    const handleMouseInteraction = useCallback(() => {
        if (isKeyboardMode) {
            setIsKeyboardMode(false);
            setFocusedElementIndex(-1);
        }
    }, [isKeyboardMode]);
    // Chart container accessibility props
    const ariaLabel = generateAriaLabel();
    const chartAccessibilityProps = useMemo(() => ({
        role: 'img',
        'aria-label': ariaLabel,
        'aria-describedby': description ? descriptionId.current : undefined,
        tabIndex: enableKeyboardNavigation ? 0 : -1,
        onKeyDown: handleKeyDown,
    }), [ariaLabel, description, enableKeyboardNavigation, handleKeyDown]);
    // Description element props
    const descriptionProps = useMemo(() => description ? {
        id: descriptionId.current,
        className: 'sr-only',
        children: description,
    } : null, [description]);
    return {
        chartAccessibilityProps,
        descriptionProps,
        focusedElementIndex,
        isKeyboardMode,
        handleMouseInteraction,
        generateChartSummary,
    };
}

export { useChartAccessibility };
