"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = InformationWidget;
const tslib_1 = require("tslib");
const jsx_runtime_1 = require("react/jsx-runtime");
const lucide_react_native_1 = require("lucide-react-native");
const react_1 = tslib_1.__importStar(require("react"));
const react_native_1 = require("react-native");
const react_native_svg_1 = tslib_1.__importStar(require("react-native-svg"));
const hooks_1 = require("../../hooks");
const livestream_store_1 = require("../../livestream-store");
const zero = tslib_1.__importStar(require("../../ui"));
const ui_1 = require("../ui");
const BITRATE_HISTORY_LENGTH = 30;
const { bg, r, borders, px, py, text, layout, gap, flex, p } = zero;
function InformationWidget({ embedMode = false, wideMode, // Optional override
showChart = true, }) {
    const [bitrateHistory, setBitrateHistory] = (0, react_1.useState)(Array.from({ length: BITRATE_HISTORY_LENGTH }, () => 0));
    const [showViewers, setShowViewers] = (0, hooks_1.useAQState)("showViewers", true);
    const [componentWidth, setComponentWidth] = (0, react_1.useState)(220);
    const [componentHeight, setComponentHeight] = (0, react_1.useState)(400);
    const [streamStartTime, setStreamStartTime] = (0, react_1.useState)(null);
    const [layoutMeasured, setLayoutMeasured] = (0, react_1.useState)(false);
    const isWideMode = wideMode !== undefined ? wideMode : layoutMeasured && componentWidth > 400;
    const isCompactHeight = layoutMeasured && componentHeight < 350;
    const seg = (0, livestream_store_1.useSegment)();
    const livestream = (0, livestream_store_1.useLivestream)();
    const viewers = (0, livestream_store_1.useViewers)();
    const getBitrate = (0, react_1.useCallback)(() => {
        if (!seg?.size || !seg?.duration)
            return 0;
        const kbps = (seg.size * 8) / ((seg.duration || 1000000000) / 1000000000) / 1000;
        return kbps;
    }, [seg?.size, seg?.duration]);
    const getMediaInfo = (0, react_1.useMemo)(() => {
        const videoTrack = seg?.video?.[0];
        const audioTrack = seg?.audio?.[0];
        return {
            resolution: videoTrack?.width && videoTrack?.height
                ? `${videoTrack.width}x${videoTrack.height}`
                : "Unknown",
            fps: videoTrack?.framerate
                ? `${(videoTrack.framerate.num / videoTrack.framerate.den).toFixed(2)} FPS`
                : "Unknown",
            videoCodec: videoTrack?.codec
                ? videoTrack.codec.toUpperCase()
                : "Unknown",
        };
    }, [seg?.video, seg?.audio]);
    const currentBitrate = getBitrate();
    (0, react_1.useEffect)(() => {
        setBitrateHistory((prev) => [...prev.slice(1), currentBitrate]);
    }, [currentBitrate]);
    (0, react_1.useEffect)(() => {
        if (seg?.startTime && !streamStartTime) {
            setStreamStartTime(new Date(seg.startTime));
        }
    }, [seg?.startTime, streamStartTime]);
    const getBitrateStatus = () => {
        if (currentBitrate > 2000)
            return "good";
        if (currentBitrate > 1000)
            return "warning";
        if (currentBitrate > 0)
            return "error";
        return "neutral";
    };
    const getConnectionStatus = () => {
        if (!seg)
            return "error";
        if (currentBitrate > 1500)
            return "good";
        if (currentBitrate > 500)
            return "warning";
        return "error";
    };
    const avgBitrate = bitrateHistory.length > 0
        ? bitrateHistory.reduce((a, b) => a + b, 0) / bitrateHistory.length
        : 0;
    const peakBitrate = Math.max(...bitrateHistory, 0);
    const uptimeMinutes = streamStartTime
        ? Math.floor((Date.now() - streamStartTime.getTime()) / 60000)
        : 0;
    const estimatedLatency = seg?.duration
        ? Math.floor((seg.duration / 1000000000) * 2)
        : 0;
    const displayBitrate = `${(currentBitrate / 1000).toFixed(2)} Mbps`;
    const displayResolution = getMediaInfo.resolution;
    const displayFps = getMediaInfo.fps;
    const streamTitle = livestream?.record?.title || "Untitled Stream";
    const viewerCount = viewers ?? 0;
    const handleLayout = (0, react_1.useCallback)((event) => {
        const { width, height } = event.nativeEvent.layout;
        console.log("InformationWidget onLayout - size:", `${width}x${height}`);
        if (width > 0 && height > 0) {
            setComponentWidth(width);
            setComponentHeight(height);
            setLayoutMeasured(true);
        }
    }, []);
    return ((0, jsx_runtime_1.jsxs)(react_native_1.View, { onLayout: handleLayout, style: [
            embedMode
                ? { backgroundColor: "rgba(23, 23, 23, 0.9)" }
                : bg.neutral[900],
            embedMode ? undefined : borders.width.thin,
            embedMode ? undefined : borders.color.neutral[700],
            r.lg,
            px[4],
            py[4],
            gap.all[6],
            flex.values[1],
            {
                minWidth: isWideMode ? 500 : 220,
                width: "100%",
            },
        ], children: [(0, jsx_runtime_1.jsxs)(react_native_1.View, { style: [
                    layout.flex.row,
                    layout.flex.spaceBetween,
                    layout.flex.alignCenter,
                ], children: [(0, jsx_runtime_1.jsxs)(react_native_1.View, { style: [layout.flex.row, layout.flex.alignCenter, gap.all[1]], children: [(0, jsx_runtime_1.jsx)(react_native_1.Text, { style: [text.white, { fontSize: 18, fontWeight: "700" }], numberOfLines: 1, children: "Stream Health" }), (0, jsx_runtime_1.jsx)(react_native_1.View, { style: [
                                    {
                                        width: 8,
                                        height: 8,
                                        borderRadius: 4,
                                        backgroundColor: !livestream
                                            ? "#3b82f6"
                                            : getConnectionStatus() === "good"
                                                ? "#22c55e"
                                                : getConnectionStatus() === "warning"
                                                    ? "#f59e0b"
                                                    : "#ef4444",
                                    },
                                ] }), !livestream && ((0, jsx_runtime_1.jsx)(react_native_1.Text, { style: [text.blue[400], { fontSize: 13, fontWeight: "600" }], children: "(not live)" }))] }), (0, jsx_runtime_1.jsx)(react_native_1.TouchableOpacity, { onPress: () => setShowViewers(!showViewers), style: [
                            layout.flex.column,
                            layout.flex.alignCenter,
                            gap.all[1],
                            { minWidth: 120 },
                        ], children: (0, jsx_runtime_1.jsxs)(react_native_1.View, { style: [layout.flex.row, layout.flex.alignCenter, gap.all[2]], children: [showViewers ? ((0, jsx_runtime_1.jsx)(lucide_react_native_1.Eye, { size: 14, color: "#9ca3af" })) : ((0, jsx_runtime_1.jsx)(lucide_react_native_1.EyeClosed, { size: 14, color: "#9ca3af" })), (0, jsx_runtime_1.jsxs)(react_native_1.Text, { style: [
                                        text.white,
                                        { fontSize: 16, fontWeight: "600", textAlign: "center" },
                                    ], children: [showViewers ? `${viewerCount}` : "...", " viewer", showViewers && viewerCount !== 1 ? "s" : ""] })] }) })] }), isWideMode ? ((0, jsx_runtime_1.jsxs)(react_native_1.View, { style: [gap.all[3]], children: [(0, jsx_runtime_1.jsxs)(react_native_1.View, { style: [layout.flex.row, gap.all[2]], children: [(0, jsx_runtime_1.jsx)(ui_1.InfoBox, { icon: lucide_react_native_1.Car, label: "Bitrate", value: displayBitrate, status: getBitrateStatus() }), (0, jsx_runtime_1.jsx)(ui_1.InfoBox, { icon: lucide_react_native_1.Monitor, label: "Resolution", value: displayResolution }), (0, jsx_runtime_1.jsx)(ui_1.InfoBox, { icon: lucide_react_native_1.Video, label: "FPS", value: displayFps })] }), showChart && ((0, jsx_runtime_1.jsxs)(react_native_1.View, { style: [gap.all[2]], children: [!isCompactHeight && ((0, jsx_runtime_1.jsxs)(react_native_1.View, { style: [
                                    layout.flex.row,
                                    layout.flex.spaceBetween,
                                    layout.flex.alignCenter,
                                ], children: [(0, jsx_runtime_1.jsx)(react_native_1.Text, { style: [
                                            text.gray[200],
                                            { fontSize: 14, fontWeight: "600" },
                                        ], children: "Live Performance" }), (0, jsx_runtime_1.jsxs)(react_native_1.View, { style: [layout.flex.row, gap.all[4]], children: [(0, jsx_runtime_1.jsxs)(react_native_1.View, { style: [layout.flex.alignCenter], children: [(0, jsx_runtime_1.jsx)(react_native_1.Text, { style: [
                                                            text.gray[400],
                                                            { fontSize: 11, fontWeight: "500" },
                                                        ], children: "AVG" }), (0, jsx_runtime_1.jsx)(react_native_1.Text, { style: [
                                                            text.white,
                                                            { fontSize: 13, fontWeight: "600" },
                                                        ], children: avgBitrate > 0
                                                            ? `${(avgBitrate / 1000).toFixed(1)}M`
                                                            : "0M" })] }), (0, jsx_runtime_1.jsxs)(react_native_1.View, { style: [layout.flex.alignCenter], children: [(0, jsx_runtime_1.jsx)(react_native_1.Text, { style: [
                                                            text.gray[400],
                                                            { fontSize: 11, fontWeight: "500" },
                                                        ], children: "PEAK" }), (0, jsx_runtime_1.jsx)(react_native_1.Text, { style: [
                                                            text.white,
                                                            { fontSize: 13, fontWeight: "600" },
                                                        ], children: peakBitrate > 0
                                                            ? `${(peakBitrate / 1000).toFixed(1)}M`
                                                            : "0M" })] }), (0, jsx_runtime_1.jsxs)(react_native_1.View, { style: [layout.flex.alignCenter], children: [(0, jsx_runtime_1.jsx)(react_native_1.Text, { style: [
                                                            text.gray[400],
                                                            { fontSize: 11, fontWeight: "500" },
                                                        ], children: "CAPTURED" }), (0, jsx_runtime_1.jsx)(react_native_1.Text, { style: [
                                                            text.white,
                                                            { fontSize: 13, fontWeight: "600" },
                                                        ], children: uptimeMinutes > 60
                                                            ? `${Math.floor(uptimeMinutes / 60)}h ${uptimeMinutes % 60}m`
                                                            : `${uptimeMinutes}m` })] })] })] })), (0, jsx_runtime_1.jsx)(BitrateChart, { data: bitrateHistory, width: componentWidth - 40, height: 120, color: livestream ? "#22c55e" : "#3b82f6" })] }))] })) : ((0, jsx_runtime_1.jsxs)(react_native_1.View, { style: [gap.all[3]], children: [!isCompactHeight && ((0, jsx_runtime_1.jsxs)(react_native_1.TouchableOpacity, { onPress: () => setShowViewers(!showViewers), style: [
                            layout.flex.row,
                            layout.flex.spaceBetween,
                            layout.flex.alignCenter,
                            py[2],
                        ], children: [(0, jsx_runtime_1.jsxs)(react_native_1.View, { style: [layout.flex.row, layout.flex.alignCenter, gap.all[3]], children: [(0, jsx_runtime_1.jsx)(lucide_react_native_1.Eye, { size: 16, color: "#9ca3af" }), (0, jsx_runtime_1.jsx)(react_native_1.Text, { style: [text.gray[300], { fontSize: 13, fontWeight: "500" }], children: "Viewers" })] }), (0, jsx_runtime_1.jsxs)(react_native_1.View, { style: [layout.flex.row, layout.flex.alignCenter, gap.all[2]], children: [(0, jsx_runtime_1.jsx)(react_native_1.Text, { style: [
                                            showViewers ? text.green[400] : text.white,
                                            { fontSize: 13, fontWeight: "600" },
                                        ], children: showViewers ? `${viewerCount} watching` : "•••" }), showViewers ? ((0, jsx_runtime_1.jsx)(lucide_react_native_1.ChevronUp, { size: 14, color: "#9ca3af" })) : ((0, jsx_runtime_1.jsx)(lucide_react_native_1.ChevronDown, { size: 14, color: "#9ca3af" }))] })] })), showChart && ((0, jsx_runtime_1.jsxs)(react_native_1.View, { style: [gap.all[2]], children: [!isCompactHeight && ((0, jsx_runtime_1.jsxs)(react_native_1.View, { style: [
                                    layout.flex.row,
                                    layout.flex.spaceBetween,
                                    layout.flex.alignCenter,
                                ], children: [(0, jsx_runtime_1.jsx)(react_native_1.Text, { style: [
                                            text.gray[200],
                                            { fontSize: 14, fontWeight: "600" },
                                        ], children: "Performance" }), (0, jsx_runtime_1.jsx)(react_native_1.Text, { style: [
                                            text.gray[400],
                                            { fontSize: 11, fontWeight: "500" },
                                        ], children: avgBitrate > 0
                                            ? `AVG ${(avgBitrate / 1000).toFixed(1)}M`
                                            : "No data" })] })), (0, jsx_runtime_1.jsx)(BitrateChart, { data: bitrateHistory, width: componentWidth - 40, height: isCompactHeight ? 80 : 120, color: livestream ? "#22c55e" : "#3b82f6" })] })), (0, jsx_runtime_1.jsxs)(react_native_1.View, { style: [gap.all[1]], children: [(0, jsx_runtime_1.jsx)(ui_1.InfoRow, { icon: lucide_react_native_1.Signal, label: "Connection", value: getConnectionStatus() === "good"
                                    ? "Excellent"
                                    : getConnectionStatus() === "warning"
                                        ? "Good"
                                        : "Poor", status: getConnectionStatus() }), (0, jsx_runtime_1.jsxs)(react_native_1.View, { style: [gap.all[1], layout.flex.row], children: [(0, jsx_runtime_1.jsx)(ui_1.InfoBox, { icon: lucide_react_native_1.Zap, label: "Bitrate", value: displayBitrate, status: getBitrateStatus() }), (0, jsx_runtime_1.jsx)(ui_1.InfoBox, { icon: lucide_react_native_1.Video, label: "FPS", value: displayFps })] })] })] }))] }));
}
function BitrateChart({ data, width, height, color = "#22c55e", }) {
    const maxDataValue = Math.max(...data, 1);
    const minDataValue = Math.min(...data);
    const getSmartRange = (max) => {
        if (max <= 1000)
            return { min: 0, max: 1000, step: 500 };
        if (max <= 2000)
            return { min: 1000, max: 2000, step: 1000 };
        if (max <= 7000)
            return { min: 4000, max: 7000, step: 1500 };
        if (max <= 10000)
            return { min: 4000, max: 10000, step: 5000 };
        const roundedMax = Math.ceil(max / 5000) * 5000;
        return { min: 0, max: roundedMax, step: roundedMax / 2 };
    };
    const { min: minValue, max: maxValue, step } = getSmartRange(maxDataValue);
    const range = maxValue - minValue;
    const chartWidth = width - 40;
    const chartStartX = 40;
    const verticalPadding = 10;
    const chartHeight = height - verticalPadding * 2;
    const points = data
        .map((value, index) => {
        const x = chartStartX + (index / (data.length - 1)) * chartWidth;
        // Clamp value to chart range and plot against the smart scale
        const clampedValue = Math.max(minValue, Math.min(maxValue, value));
        const y = verticalPadding +
            chartHeight -
            ((clampedValue - minValue) / range) * chartHeight;
        return `${x},${y}`;
    })
        .join(" ");
    const pathData = `M ${points.replace(/ /g, " L ")}`;
    const ticks = [
        { value: minValue, y: height - verticalPadding },
        { value: minValue + step, y: height / 2 },
        { value: maxValue, y: verticalPadding },
    ];
    return ((0, jsx_runtime_1.jsx)(react_native_1.View, { style: { height, width, marginVertical: 8 }, children: (0, jsx_runtime_1.jsxs)(react_native_svg_1.default, { width: width, height: height, children: [ticks.map((tick, index) => ((0, jsx_runtime_1.jsxs)(react_1.default.Fragment, { children: [(0, jsx_runtime_1.jsx)(react_native_svg_1.Line, { x1: chartStartX, y1: tick.y, x2: width, y2: tick.y, stroke: "rgba(255,255,255,0.1)", strokeWidth: "1" }), (0, jsx_runtime_1.jsx)(react_native_svg_1.Text, { x: "35", y: tick.y + 4, fontSize: 10, fontFamily: "sans-serif", fill: "#9ca3af", textAnchor: "end", children: (tick.value / 1000).toLocaleString() })] }, index))), (0, jsx_runtime_1.jsx)(react_native_svg_1.Text, { x: 12, y: height / 2, transform: `rotate(-90, 12, ${height / 2})`, fontSize: 10, fontFamily: "sans-serif", fill: "#9ca3af", textAnchor: "middle", children: "mbits/s" }), (0, jsx_runtime_1.jsx)(react_native_svg_1.Path, { d: pathData, stroke: color, strokeWidth: "2", fill: "none", strokeLinecap: "round", strokeLinejoin: "round" })] }) }));
}
//# sourceMappingURL=information-widget.js.map