import { jsxs, jsx, Fragment } from 'react/jsx-runtime';
import React__default from 'react';
import { cn } from '../../../utils/cn.js';
import { useChartScales } from '../hooks/useChartScales.js';
import { ChartContainer, useChartContext } from '../shared/ChartContainer/ChartContainer.js';
import { BarRenderer } from '../shared/BarRenderer/BarRenderer.js';
import { LineRenderer } from '../shared/LineRenderer/LineRenderer.js';
import { COMBO_CHART_DEFAULTS } from './ComboChart.types.js';
import { ExclamationTriangleIcon } from '@heroicons/react/20/solid';

/**
 * Internal component that uses context to render bars and lines
 */
const ComboChartRenderers = ({ barKeys, lineKeys, stacked, barRadius, dotRadius, gap, categoryGap, strokeWidth, curved, curveType, showDots, }) => {
    const context = useChartContext();
    const dataKeys = Object.keys(context.config);
    const seriesColors = [
        "var(--color-primary)",
        "var(--color-warning)",
        "var(--color-success)",
        "var(--color-danger)",
    ];
    // Filter configs for bars and lines, and assign colors
    const barConfig = {};
    barKeys.forEach((key) => {
        var _a;
        const keyIndex = dataKeys.indexOf(key);
        barConfig[key] = {
            ...context.config[key],
            color: ((_a = context.config[key]) === null || _a === void 0 ? void 0 : _a.color) ||
                seriesColors[keyIndex % seriesColors.length],
        };
    });
    const lineConfig = {};
    lineKeys.forEach((key) => {
        var _a;
        const keyIndex = dataKeys.indexOf(key);
        lineConfig[key] = {
            ...context.config[key],
            color: ((_a = context.config[key]) === null || _a === void 0 ? void 0 : _a.color) ||
                seriesColors[keyIndex % seriesColors.length],
        };
    });
    // Create custom tooltip handler that includes ALL series (bars + lines)
    const handleComboMouseEnter = React__default.useCallback((e, content, coordinates) => {
        // Rebuild content to include all series from the full config
        const dataItem = context.data.find((d) => d.name === content.category);
        if (dataItem) {
            const allSeries = dataKeys.map((key, idx) => {
                var _a, _b;
                const value = dataItem[key];
                const isNull = value === null || value === undefined || (typeof value === 'number' && !isFinite(value));
                return {
                    key,
                    label: ((_a = context.config[key]) === null || _a === void 0 ? void 0 : _a.label) || key,
                    value: isNull ? 0 : value,
                    color: ((_b = context.config[key]) === null || _b === void 0 ? void 0 : _b.color) || seriesColors[idx % seriesColors.length],
                };
            }).filter(series => {
                // Only show series that have valid non-zero values
                const rawVal = dataItem[series.key];
                return rawVal != null && typeof rawVal === 'number' && isFinite(rawVal) && rawVal !== 0;
            });
            const enhancedContent = {
                category: content.category,
                series: allSeries,
                total: stacked && allSeries.length > 0
                    ? allSeries.reduce((acc, s) => acc + (typeof s.value === 'number' ? s.value : 0), 0)
                    : undefined,
            };
            context.handleMouseEnter(e, enhancedContent, coordinates);
        }
        else {
            // Fallback to original content if we can't find the data item
            context.handleMouseEnter(e, content, coordinates);
        }
    }, [context, dataKeys, seriesColors, stacked]);
    return (jsxs(Fragment, { children: [barKeys.length > 0 && (jsx(BarRenderer, { data: context.data, config: barConfig, scales: context.scales, dimensions: context.dimensions, margin: context.margin, stacked: stacked, radius: barRadius, gap: gap, categoryGap: categoryGap, showAnimation: true, hoveredCategory: context.hoveredCategory, onHoverCategory: context.setHoveredCategory, onMouseEnter: handleComboMouseEnter, onMouseMove: context.handleMouseMove, onMouseLeave: context.handleMouseLeave, focusedElementIndex: context.focusedElementIndex, isKeyboardMode: context.isKeyboardMode })), lineKeys.length > 0 && (jsx(LineRenderer, { data: context.data, config: lineConfig, scales: context.scales, dimensions: context.dimensions, margin: context.margin, strokeWidth: strokeWidth, curved: curved, curveType: curveType, showDots: showDots, radius: dotRadius, hoveredPoint: context.hoveredPoint, onHoverPoint: context.setHoveredPoint, onMouseEnter: handleComboMouseEnter, onMouseMove: context.handleMouseMove, onMouseLeave: context.handleMouseLeave, focusedElementIndex: context.focusedElementIndex, isKeyboardMode: context.isKeyboardMode }))] }));
};
/**
 * ComboChart Component
 *
 * Combines bar and line series in a single chart.
 * Now uses composed BarRenderer and LineRenderer instead of duplicating code.
 */
const ComboChart = ({ data, config, 
// Standardized display props with defaults
showGrid = COMBO_CHART_DEFAULTS.showGrid, showXAxis = COMBO_CHART_DEFAULTS.showXAxis, showYAxis = COMBO_CHART_DEFAULTS.showYAxis, minValue: propMinValue, maxValue: propMaxValue, 
// Visual props (inherited from StandardVisualProps)
barRadius, dotRadius, radius, // @deprecated - kept for backward compatibility
strokeWidth = COMBO_CHART_DEFAULTS.strokeWidth, gap = COMBO_CHART_DEFAULTS.gap, categoryGap = COMBO_CHART_DEFAULTS.categoryGap, stacked = COMBO_CHART_DEFAULTS.stacked, 
// Line-specific props
curved = COMBO_CHART_DEFAULTS.curved, curveType = COMBO_CHART_DEFAULTS.curveType, showDots = COMBO_CHART_DEFAULTS.showDots, 
// Dual axis (not yet implemented)
showDualAxis = COMBO_CHART_DEFAULTS.showDualAxis, 
// Base props
className, title, description, enableKeyboardNavigation = COMBO_CHART_DEFAULTS.enableKeyboardNavigation, showValidationWarnings = process.env.NODE_ENV === "development", children, ...props }) => {
    var _a, _b;
    // Resolve radius props with backward compatibility
    const resolvedBarRadius = (_a = barRadius !== null && barRadius !== void 0 ? barRadius : radius) !== null && _a !== void 0 ? _a : COMBO_CHART_DEFAULTS.barRadius;
    const resolvedDotRadius = (_b = dotRadius !== null && dotRadius !== void 0 ? dotRadius : radius) !== null && _b !== void 0 ? _b : COMBO_CHART_DEFAULTS.dotRadius;
    // Development warning for deprecated radius prop
    if (process.env.NODE_ENV !== 'production' && radius !== undefined) {
        console.warn('[ComboChart]: The `radius` prop is deprecated and will be removed in a future version. ' +
            'Use `barRadius` for bar corners and `dotRadius` for line markers instead.');
    }
    // Get all data keys from config
    const dataKeys = Object.keys(config || {});
    // Separate bar and line series
    const barSeries = dataKeys.filter((key) => {
        const seriesConfig = config[key];
        return !(seriesConfig === null || seriesConfig === void 0 ? void 0 : seriesConfig.type) || seriesConfig.type === "bar";
    });
    const lineSeries = dataKeys.filter((key) => {
        const seriesConfig = config[key];
        return (seriesConfig === null || seriesConfig === void 0 ? void 0 : seriesConfig.type) === "line";
    });
    // Use unified chart scales hook
    const { scales, sanitizedData, isValid, hasWarnings} = useChartScales({
        data,
        config,
        chartType: "combo",
        stacked,
        minValue: propMinValue,
        maxValue: propMaxValue,
        includeZero: true,
        innerWidth: 600, // Will be overridden by ChartContainer
        categoryGap,
    });
    // Early return for invalid data with error message
    if (!isValid) {
        return (jsxs("div", { className: cn("chart-container flex flex-col items-center justify-center p-6 border border-border rounded-lg text-2xl", className), role: "alert", "aria-live": "polite", ...props, children: [jsxs("div", { className: "flex flex-col items-center gap-4 mb-1", children: [jsx(ExclamationTriangleIcon, { className: "size-6 text-[var(--color-danger)]" }), jsx("div", { className: "text-base font-semibold text-[var(--color-text-secondary)]", children: "Invalid Chart Data" })] }), jsx("p", { className: "text-base text-[var(--color-text-secondary)]/70 mb-2", children: "Unable to render chart due to data validation errors" })] }));
    }
    // Early return for empty data
    if (!sanitizedData || sanitizedData.length === 0) {
        return (jsx("div", { className: cn("chart-container flex items-center justify-center text-[var(--color-text-muted)]", className), role: "img", "aria-label": "Empty combo chart", ...props, children: jsx("span", { children: "No data available" }) }));
    }
    barSeries.forEach((key) => {
        config[key];
    });
    lineSeries.forEach((key) => {
        config[key];
    });
    return (jsxs(ChartContainer, { data: sanitizedData, config: config, scales: scales, showGrid: showGrid, showXAxis: showXAxis, showYAxis: showYAxis, categoryGap: categoryGap, className: className, title: title, description: description, enableKeyboardNavigation: enableKeyboardNavigation, chartType: "combo", ...props, children: [jsx(ComboChartRenderers, { barKeys: barSeries, lineKeys: lineSeries, stacked: stacked, barRadius: resolvedBarRadius, dotRadius: resolvedDotRadius, gap: gap, categoryGap: categoryGap, strokeWidth: strokeWidth, curved: curved, curveType: curveType, showDots: showDots }), showValidationWarnings && hasWarnings && (jsx("foreignObject", { x: "0", y: "0", width: "100%", height: "50", children: jsxs("div", { className: "p-2 bg-[var(--color-warning-50)] border border-[var(--color-warning-200)] rounded text-sm text-[var(--color-warning)] shadow-sm", children: [jsx("strong", { children: "Chart Warnings:" }), " Some data validation warnings occurred."] }) })), children] }));
};

export { ComboChart };
