/**
 * Stats Component
 *
 * Displays search statistics (total results, processing time, etc.)
 * Supports inline, badge, and detailed display variants.
 */
import React, { useEffect, useRef, useState } from 'react';
import { useSearchContext } from './SearchProvider';
import { useSearchState } from '../hooks/useSearchState';
import { clsx } from 'clsx';
/** CSS class name used for the animated count fade transition */
const ANIMATE_CLASS = 'seekora-stats-animate';
/** Inline <style> for the count-change animation and CSS custom properties */
const statsStyleId = 'seekora-stats-styles';
function ensureStatsStyles() {
    if (typeof document === 'undefined')
        return;
    if (document.getElementById(statsStyleId))
        return;
    const style = document.createElement('style');
    style.id = statsStyleId;
    style.textContent = `
    .seekora-stats-root {
      --seekora-stats-color: inherit;
      --seekora-stats-bg: transparent;
      --seekora-stats-font-size: inherit;
      --seekora-stats-badge-bg: inherit;
      --seekora-stats-badge-color: inherit;
    }
    .${ANIMATE_CLASS} {
      opacity: 0;
      transition: opacity 250ms ease-in-out;
    }
  `;
    document.head.appendChild(style);
}
export const Stats = ({ results: resultsProp, renderStats, className, style, theme: customTheme, showProcessingTime = false, showQuery = false, separator = ' \u2022 ', variant = 'inline', showResultCount = true, formatNumber, }) => {
    const { theme } = useSearchContext();
    const { results: stateResults } = useSearchState();
    const statsTheme = customTheme || {};
    // Use results from prop if provided, otherwise from state manager
    const results = resultsProp || stateResults;
    // Inject keyframe / transition styles once
    useEffect(() => {
        ensureStatsStyles();
    }, []);
    // Extract stats from results
    const res = results;
    const totalResults = res?.totalResults
        || res?.data?.total_results
        || res?.data?.data?.total_results
        || 0;
    const processingTime = res?.processingTimeMS
        || res?.data?.processingTimeMS
        || res?.data?.data?.processingTimeMS;
    const query = (res?.query ?? '');
    // Number formatter
    const fmt = formatNumber || ((n) => n.toLocaleString());
    // Animated count change — toggle a CSS class briefly on totalResults change
    const countRef = useRef(null);
    const prevTotalRef = useRef(totalResults);
    const [animating, setAnimating] = useState(false);
    useEffect(() => {
        if (prevTotalRef.current !== totalResults) {
            prevTotalRef.current = totalResults;
            setAnimating(true);
            // After a frame, remove the class so the transition plays (opacity 0 -> 1)
            const raf = requestAnimationFrame(() => {
                setAnimating(false);
            });
            return () => cancelAnimationFrame(raf);
        }
    }, [totalResults]);
    // Helper: border radius value from theme
    const borderRadiusSmall = typeof theme.borderRadius === 'string'
        ? theme.borderRadius
        : theme.borderRadius.small;
    // ─── Custom render ────────────────────────────────────────
    if (renderStats) {
        return (React.createElement("div", { className: clsx('seekora-stats-root', statsTheme.container, className), style: style }, renderStats({
            totalResults,
            processingTime,
            query,
        })));
    }
    // ─── Inline variant (original behaviour) ──────────────────
    if (variant === 'inline') {
        const parts = [];
        if (showResultCount) {
            if (totalResults > 0) {
                parts.push(React.createElement("span", { key: "count", className: statsTheme.text },
                    React.createElement("span", { ref: countRef, className: clsx(animating && ANIMATE_CLASS), style: { transition: 'opacity 250ms ease-in-out' } }, fmt(totalResults)),
                    ` result${totalResults !== 1 ? 's' : ''}`));
            }
            else {
                parts.push(React.createElement("span", { key: "count", className: statsTheme.text }, "No results"));
            }
        }
        if (showProcessingTime && processingTime !== undefined) {
            parts.push(React.createElement("span", { key: "time", className: statsTheme.text },
                fmt(processingTime),
                "ms"));
        }
        if (showQuery && query) {
            parts.push(React.createElement("span", { key: "query", className: statsTheme.text },
                "for \"",
                query,
                "\""));
        }
        return (React.createElement("div", { className: clsx('seekora-stats-root', statsTheme.container, className), style: {
                fontSize: 'var(--seekora-stats-font-size,' + theme.typography.fontSize.medium + ')',
                color: 'var(--seekora-stats-color,' + theme.colors.text + ')',
                backgroundColor: 'var(--seekora-stats-bg, transparent)',
                ...style,
            } }, parts.map((part, index) => (React.createElement("span", { key: index },
            index > 0 && (React.createElement("span", { className: statsTheme.separator, style: { margin: `0 ${theme.spacing.small}` } }, separator)),
            part)))));
    }
    // ─── Badge variant ────────────────────────────────────────
    if (variant === 'badge') {
        const badges = [];
        const badgeStyle = {
            display: 'inline-flex',
            alignItems: 'center',
            gap: theme.spacing.small,
            padding: `${theme.spacing.small} ${theme.spacing.medium}`,
            borderRadius: borderRadiusSmall,
            backgroundColor: `var(--seekora-stats-badge-bg, ${theme.colors.primary}1A)`, // 10 % opacity hex
            color: `var(--seekora-stats-badge-color, ${theme.colors.primary})`,
            fontSize: theme.typography.fontSize.small,
            fontWeight: 500,
        };
        if (showResultCount) {
            badges.push(React.createElement("span", { key: "count", className: clsx(statsTheme.badge), style: badgeStyle },
                React.createElement("span", { className: statsTheme.badgeLabel }, "Results"),
                React.createElement("span", { className: clsx(statsTheme.badgeValue, animating && ANIMATE_CLASS), style: { fontWeight: 600, transition: 'opacity 250ms ease-in-out' } }, totalResults > 0 ? fmt(totalResults) : '0')));
        }
        if (showQuery && query) {
            badges.push(React.createElement("span", { key: "query", className: clsx(statsTheme.badge), style: badgeStyle },
                React.createElement("span", { className: statsTheme.badgeLabel }, "Query"),
                React.createElement("span", { className: statsTheme.badgeValue, style: { fontWeight: 600 } }, query)));
        }
        if (showProcessingTime && processingTime !== undefined) {
            badges.push(React.createElement("span", { key: "time", className: clsx(statsTheme.badge), style: badgeStyle },
                React.createElement("span", { className: statsTheme.badgeLabel }, "Time"),
                React.createElement("span", { className: statsTheme.badgeValue, style: { fontWeight: 600 } },
                    fmt(processingTime),
                    "ms")));
        }
        return (React.createElement("div", { className: clsx('seekora-stats-root', statsTheme.container, className), style: {
                display: 'flex',
                flexWrap: 'wrap',
                gap: theme.spacing.small,
                fontSize: 'var(--seekora-stats-font-size,' + theme.typography.fontSize.small + ')',
                color: 'var(--seekora-stats-color,' + theme.colors.text + ')',
                backgroundColor: 'var(--seekora-stats-bg, transparent)',
                ...style,
            } }, badges));
    }
    // ─── Detailed variant ─────────────────────────────────────
    if (variant === 'detailed') {
        const rows = [];
        if (showResultCount) {
            rows.push({
                label: 'Total Results',
                value: (React.createElement("span", { className: clsx(animating && ANIMATE_CLASS), style: { transition: 'opacity 250ms ease-in-out' } }, fmt(totalResults))),
            });
        }
        if (showQuery && query) {
            rows.push({ label: 'Query', value: query });
        }
        if (showProcessingTime && processingTime !== undefined) {
            rows.push({ label: 'Time', value: `${fmt(processingTime)}ms` });
        }
        return (React.createElement("div", { className: clsx('seekora-stats-root', statsTheme.detailed, statsTheme.container, className), style: {
                display: 'flex',
                flexDirection: 'column',
                gap: theme.spacing.small,
                fontSize: 'var(--seekora-stats-font-size,' + theme.typography.fontSize.medium + ')',
                color: 'var(--seekora-stats-color,' + theme.colors.text + ')',
                backgroundColor: 'var(--seekora-stats-bg, transparent)',
                ...style,
            } }, rows.map((row, index) => (React.createElement("div", { key: index, className: statsTheme.detailedRow, style: {
                display: 'flex',
                alignItems: 'center',
                gap: theme.spacing.small,
            } },
            React.createElement("span", { className: statsTheme.detailedLabel, style: {
                    color: theme.colors.textSecondary,
                    fontWeight: 500,
                } },
                row.label,
                ":"),
            React.createElement("span", { className: statsTheme.detailedValue, style: {
                    color: theme.colors.text,
                    fontWeight: 600,
                } }, row.value))))));
    }
    // Fallback (should not be reached)
    return null;
};
