import React, { useEffect, useRef, useState } from "react";
import { Button } from "../../button/index.js";
import { Box } from "../../primitives/box/index.js";
import { VStack } from "../../primitives/stack/index.js";
import { Heading } from "../../typography/index.js";
function DataTableProfiler({ children }) {
    const lastProfilerStateRef = useRef({});
    return (React.createElement("div", null,
        React.createElement(ProfilerDisplay, { getLatestData: () => lastProfilerStateRef.current }),
        React.createElement(React.Profiler, { id: "DataTable", onRender: (_, phase, actualDuration) => {
                var _a;
                lastProfilerStateRef.current = Object.assign(Object.assign({}, lastProfilerStateRef.current), { [phase]: {
                        actualDuration: rollingLatestValues(((_a = lastProfilerStateRef.current[phase]) === null || _a === void 0 ? void 0 : _a.actualDuration) || [], { duration: actualDuration.toFixed(2), timestamp: Date.now() }, 10),
                    } });
            } },
            React.createElement("div", { id: "dataTable-profiler-content" }, children))));
}
function rollingLatestValues(arr, newValue, maxLength) {
    let newArr = [newValue, ...arr];
    if (newArr.length > maxLength) {
        newArr = newArr.slice(0, -1);
    }
    return newArr;
}
const getOpacity = (timestamp) => {
    const age = Date.now() - timestamp;
    const maxAge = 10000;
    return Math.max(0.4, 1 - age / maxAge);
};
function ProfilerDisplay({ getLatestData, }) {
    const [open, setOpen] = useState(false);
    const [domStats, setDomStats] = useState(null);
    const [, setTick] = useState(0);
    const lastProfilerState = getLatestData();
    useEffect(() => {
        if (!open)
            return;
        const interval = setInterval(() => {
            const dataTableElement = document.getElementById("dataTable-profiler-content");
            if (dataTableElement) {
                const walker = document.createTreeWalker(dataTableElement, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT, null);
                let elements = 0;
                let nodes = 0;
                while (walker.nextNode()) {
                    nodes++;
                    if (walker.currentNode.nodeType === Node.ELEMENT_NODE) {
                        elements++;
                    }
                }
                setDomStats({ elements, nodes });
            }
            setTick((t) => t + 1);
        }, 500);
        return () => clearInterval(interval);
    }, [open]);
    return (React.createElement(VStack, { asChild: true },
        React.createElement(Box, { position: "fixed", top: "space-4", right: "space-4", padding: "space-6", background: "raised", borderRadius: "8", borderWidth: "1", borderColor: "neutral-subtleA", style: { zIndex: 1000 } },
            React.createElement(Button, { "data-color": "neutral", variant: "tertiary", size: "small", onClick: () => setOpen(!open) }, open ? "Hide Profiler" : "Show Profiler"),
            open && (React.createElement(React.Fragment, null,
                !domStats && React.createElement("div", null, "Loading stats..."),
                domStats && (React.createElement("div", null,
                    React.createElement(Heading, { level: "2", size: "xsmall" }, "DOM Stats:"),
                    React.createElement("ul", { style: { margin: 0, paddingLeft: "1rem" } },
                        React.createElement("li", { style: { listStyle: "none" } }, `${domStats.elements} elements`),
                        React.createElement("li", { style: { listStyle: "none" } }, `${domStats.nodes} nodes`)))),
                lastProfilerState.mount && (React.createElement("div", null,
                    React.createElement(Heading, { level: "2", size: "xsmall" }, "Mount:"),
                    React.createElement("ul", { style: { margin: 0, paddingLeft: "1rem" } }, lastProfilerState.mount.actualDuration.map((entry, index) => (React.createElement("li", { style: {
                            listStyle: "none",
                            opacity: getOpacity(entry.timestamp),
                            transition: "opacity 0.5s",
                        }, key: index }, `${entry.duration} ms`)))))),
                lastProfilerState.update && (React.createElement("div", null,
                    React.createElement(Heading, { level: "2", size: "xsmall" }, "Update:"),
                    React.createElement("ul", { style: { margin: 0, paddingLeft: "1rem" } }, lastProfilerState.update.actualDuration.map((entry, index) => (React.createElement("li", { style: {
                            listStyle: "none",
                            opacity: getOpacity(entry.timestamp),
                            transition: "opacity 0.5s",
                        }, key: index }, `${entry.duration} ms`)))))),
                lastProfilerState["nested-update"] && (React.createElement("div", null,
                    React.createElement(Heading, { level: "2", size: "xsmall" }, "Nested-update"),
                    React.createElement("ul", { style: { margin: 0, paddingLeft: "1rem" } }, lastProfilerState["nested-update"].actualDuration.map((entry, index) => (React.createElement("li", { style: {
                            listStyle: "none",
                            opacity: getOpacity(entry.timestamp),
                            transition: "opacity 0.5s",
                        }, key: index }, `${entry.duration} ms`)))))))))));
}
export { DataTableProfiler };
//# sourceMappingURL=DataTableProfiler.js.map