/**
 * 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";
import { ensureSeekoraStyles } from "../styles/inject";
export const Stats = ({ results: resultsProp, renderStats, className, style, theme: customTheme, showProcessingTime = false, showQuery = false, separator = " • ", variant = "inline", showResultCount = true, formatNumber, emptyLabel = "No results", resultsLabel = "Results", }) => {
    const { theme } = useSearchContext();
    const { results: stateResults } = useSearchState();
    const statsTheme = customTheme || {};
    // Inject canonical stylesheet once
    useEffect(() => {
        ensureSeekoraStyles();
    }, []);
    // Use results from prop if provided, otherwise from state manager
    const results = resultsProp || stateResults;
    // Extract stats from results
    const res = results;
    // Post-processed shape: res.totalResults (preferred)
    // Raw envelope fallback: res.data.total_results
    const totalResults = res?.totalResults || res?.data?.total_results || 0;
    const processingTime = res?.data?.processingTimeMS ??
        res?.["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]);
    // ─── Custom render ────────────────────────────────────────
    if (renderStats) {
        return (React.createElement("div", { className: clsx("seekora-stats", statsTheme.container, className), "data-variant": variant, 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: clsx("seekora-stats__text", statsTheme.text) },
                    React.createElement("span", { ref: countRef, className: clsx("seekora-stats__count", animating && "seekora-stats__count--animating") }, fmt(totalResults)),
                    ` result${totalResults !== 1 ? "s" : ""}`));
            }
            else {
                parts.push(React.createElement("span", { key: "count", className: clsx("seekora-stats__text", statsTheme.text) }, emptyLabel));
            }
        }
        if (showProcessingTime && processingTime !== undefined) {
            parts.push(React.createElement("span", { key: "time", className: clsx("seekora-stats__text", statsTheme.text) },
                fmt(processingTime),
                "ms"));
        }
        if (showQuery && query) {
            parts.push(React.createElement("span", { key: "query", className: clsx("seekora-stats__text", statsTheme.text) },
                "for \"",
                query,
                "\""));
        }
        return (React.createElement("div", { className: clsx("seekora-stats", statsTheme.container, className), "data-variant": "inline", style: style, "aria-live": "polite", "aria-atomic": "true" }, parts.map((part, index) => (React.createElement("span", { key: index },
            index > 0 && (React.createElement("span", { className: clsx("seekora-stats__separator", statsTheme.separator) }, separator)),
            part)))));
    }
    // ─── Badge variant ────────────────────────────────────────
    if (variant === "badge") {
        const badges = [];
        if (showResultCount) {
            badges.push(React.createElement("span", { key: "count", className: clsx("seekora-stats__badge", statsTheme.badge) },
                React.createElement("span", { className: clsx("seekora-stats__badge-label", statsTheme.badgeLabel) }, resultsLabel),
                React.createElement("span", { className: clsx("seekora-stats__badge-value", statsTheme.badgeValue, animating && "seekora-stats__count--animating") }, totalResults > 0 ? fmt(totalResults) : "0")));
        }
        if (showQuery && query) {
            badges.push(React.createElement("span", { key: "query", className: clsx("seekora-stats__badge", statsTheme.badge) },
                React.createElement("span", { className: clsx("seekora-stats__badge-label", statsTheme.badgeLabel) }, "Query"),
                React.createElement("span", { className: clsx("seekora-stats__badge-value", statsTheme.badgeValue) }, query)));
        }
        if (showProcessingTime && processingTime !== undefined) {
            badges.push(React.createElement("span", { key: "time", className: clsx("seekora-stats__badge", statsTheme.badge) },
                React.createElement("span", { className: clsx("seekora-stats__badge-label", statsTheme.badgeLabel) }, "Time"),
                React.createElement("span", { className: clsx("seekora-stats__badge-value", statsTheme.badgeValue) },
                    fmt(processingTime),
                    "ms")));
        }
        return (React.createElement("div", { className: clsx("seekora-stats", statsTheme.container, className), "data-variant": "badge", style: style, "aria-live": "polite", "aria-atomic": "true" }, badges));
    }
    // ─── Detailed variant ─────────────────────────────────────
    if (variant === "detailed") {
        const rows = [];
        if (showResultCount) {
            rows.push({
                label: resultsLabel,
                value: (React.createElement("span", { className: clsx("seekora-stats__count", animating && "seekora-stats__count--animating") }, 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", statsTheme.detailed, statsTheme.container, className), "data-variant": "detailed", style: style, "aria-live": "polite", "aria-atomic": "true" }, rows.map((row, index) => (React.createElement("div", { key: index, className: clsx("seekora-stats__row", statsTheme.detailedRow) },
            React.createElement("span", { className: clsx("seekora-stats__label", statsTheme.detailedLabel) },
                row.label,
                ":"),
            React.createElement("span", { className: clsx("seekora-stats__value", statsTheme.detailedValue) }, row.value))))));
    }
    // Fallback (should not be reached)
    return null;
};
