import { useMemo } from 'react';
import { useChartValidation } from './useChartValidation.js';

/**
 * Unified hook for chart scale calculations
 * Handles both bar and line charts with consistent logic
 */
function useChartScales(options) {
    const { data, config, chartType = 'bar', stacked = false, minValue: propMinValue, maxValue: propMaxValue, includeZero = true, innerWidth = 600, categoryGap = 8, } = options;
    // Use validation hook for data sanitization and safe calculations
    const { validation, sanitizedData, isValid, hasWarnings, safeScale, safeMath, } = useChartValidation(data, config, {
        autoSanitize: true,
        logWarnings: true,
    });
    // Get all data keys from config
    const dataKeys = Object.keys(config || {});
    // Calculate Y-axis scale
    const yScale = useMemo(() => {
        // Start with base scale calculation
        let scaleRange = safeScale.calculateRange({
            minValue: propMinValue,
            maxValue: propMaxValue,
            includeZero,
        });
        // For stacked bar charts, recalculate max as sum of all values per category
        if (chartType === 'bar' && stacked && propMaxValue === undefined && sanitizedData.length > 0) {
            const maxStackedTotal = sanitizedData.reduce((maxTotal, item) => {
                const currentTotal = dataKeys.reduce((sum, key) => {
                    const value = item[key];
                    return sum + (typeof value === "number" && isFinite(value) ? value : 0);
                }, 0);
                return Math.max(maxTotal, currentTotal);
            }, 0);
            scaleRange = safeScale.calculateRange({
                minValue: propMinValue,
                maxValue: maxStackedTotal,
                includeZero,
            });
        }
        // For combo charts with stacked bars, also handle stacking
        if (chartType === 'combo' && propMaxValue === undefined && sanitizedData.length > 0) {
            // Separate bar and line series
            const barKeys = dataKeys.filter((key) => {
                const seriesConfig = config[key];
                return !(seriesConfig === null || seriesConfig === void 0 ? void 0 : seriesConfig.type) || seriesConfig.type === 'bar';
            });
            const lineKeys = dataKeys.filter((key) => {
                const seriesConfig = config[key];
                return (seriesConfig === null || seriesConfig === void 0 ? void 0 : seriesConfig.type) === 'line';
            });
            // Calculate max for bars (stacked if needed)
            const maxBarValue = stacked && barKeys.length > 0
                ? sanitizedData.reduce((maxTotal, item) => {
                    const barTotal = barKeys.reduce((sum, key) => {
                        const value = item[key];
                        return sum + (typeof value === "number" && isFinite(value) ? value : 0);
                    }, 0);
                    return Math.max(maxTotal, barTotal);
                }, 0)
                : sanitizedData.reduce((max, item) => {
                    const barMax = Math.max(...barKeys.map(key => {
                        const value = item[key];
                        return typeof value === "number" && isFinite(value) ? value : 0;
                    }));
                    return Math.max(max, barMax);
                }, 0);
            // Calculate max for lines
            const maxLineValue = lineKeys.length > 0
                ? sanitizedData.reduce((max, item) => {
                    const lineMax = Math.max(...lineKeys.map(key => {
                        const value = item[key];
                        return typeof value === "number" && isFinite(value) ? value : 0;
                    }));
                    return Math.max(max, lineMax);
                }, 0)
                : 0;
            // Use the maximum of both
            const combinedMax = Math.max(maxBarValue, maxLineValue);
            scaleRange = safeScale.calculateRange({
                minValue: propMinValue,
                maxValue: combinedMax,
                includeZero,
            });
        }
        return scaleRange;
    }, [
        sanitizedData,
        dataKeys,
        config,
        chartType,
        stacked,
        propMinValue,
        propMaxValue,
        includeZero,
        safeScale,
    ]);
    // Calculate X-axis scale
    const xScale = useMemo(() => {
        const dataLength = sanitizedData.length;
        if (dataLength === 0) {
            return {
                categoryWidth: 0,
                totalWidth: 0,
                pointPosition: () => 0,
            };
        }
        // For bar charts
        if (chartType === 'bar' || chartType === 'combo') {
            const totalCategoryGap = Math.max(0, (dataLength - 1) * categoryGap);
            const availableWidth = Math.max(0, innerWidth - totalCategoryGap);
            const categoryWidth = safeMath.divide(availableWidth, dataLength, 0);
            return {
                categoryWidth,
                totalWidth: availableWidth + totalCategoryGap,
                pointPosition: (index) => index * (categoryWidth + categoryGap),
            };
        }
        // For line charts - points spread evenly across width
        if (chartType === 'line') {
            const categoryWidth = dataLength === 1 ? innerWidth : innerWidth / (dataLength - 1);
            return {
                categoryWidth,
                totalWidth: innerWidth,
                pointPosition: (index) => {
                    if (dataLength === 1)
                        return innerWidth / 2;
                    return (index / (dataLength - 1)) * innerWidth;
                },
            };
        }
        // Default fallback
        return {
            categoryWidth: innerWidth / Math.max(1, dataLength),
            totalWidth: innerWidth,
            pointPosition: (index) => (index / Math.max(1, dataLength)) * innerWidth,
        };
    }, [sanitizedData.length, chartType, categoryGap, innerWidth, safeMath]);
    return {
        scales: {
            y: yScale,
            x: xScale,
        },
        sanitizedData,
        isValid,
        hasWarnings,
        safeMath,
        safeScale,
    };
}

export { useChartScales };
