import { Head } from "@inertiajs/react";
import {
    Activity,
    AlertTriangle,
    History,
    BarChart3,
    BrainCircuit,
    Gauge,
    CheckCircle2,
    Clock3,
    SlidersHorizontal,
    RefreshCw,
    RotateCcw,
    ShieldAlert,
    Target,
    XCircle,
    Zap,
    TrendingUp,
    Sparkles,
} from "lucide-react";
import { useCallback, useEffect, useMemo, useState } from "react";

import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from "@/components/ui/select";
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { useI18n } from "@/lib/i18n";
import CustomerWorkspaceNav from "@/components/customer-workspace-nav";
import type { MarketType } from "@/lib/market";
import SignalEngineReplayPanel from "@/components/trading/SignalEngineReplayPanel";

type ProviderOption = { slug: string; name: string; markets: string[] };
type SymbolItem = { symbol: string; name: string };
type Props = {
    providers: ProviderOption[];
    defaultProvider: string;
    symbols: Record<string, Record<MarketType, SymbolItem[]>>;
    defaultSymbol: string;
    defaultMarket: MarketType;
    defaultInterval: string;
    canReplay: boolean;
};
type Explain = {
    decision: {
        status: string;
        execution_allowed: boolean;
        direction: string;
        candidate_direction: string;
        action: string;
        confidence: {
            confidence?: number;
            confirmation_alignment?: number;
        } | null;
        score: number | null;
        base_score: number | null;
        adaptive_adjustment: number;
    };
    policy: {
        decision_fingerprint: string | null;
        decision_trace: Array<{
            step: number;
            key: string;
            label: string;
            status: string;
            severity: string;
            stage: string;
            value: unknown;
            target: unknown;
        }>;
        hard_failures: string[];
        candidate_failures: string[];
        execution_blockers: string[];
        warnings: string[];
        thresholds: Record<string, number>;
        context_adjustment: number;
    };
    reasons: string[];
    warnings: string[];
    primary: {
        score: number | null;
        base_score: number | null;
        adaptive_score: number | null;
        rating: string | null;
        confidence: Explain["decision"]["confidence"];
        regime: Record<string, unknown>;
        metrics: Record<string, unknown>;
    };
    mtf: Record<string, unknown>;
    strategy: {
        setup: string | null;
        direction: string;
        quality: number;
        grade: string;
        preferred_strategy: string | null;
        regime: Record<string, unknown>;
        trigger: Record<string, unknown>;
    };
    trade_plan: Record<string, unknown> | null;
    market_context: Record<string, unknown>;
    note: string;
};
type Quality = {
    summary: {
        signals: number;
        matching_signals: number;
        sample_limited: boolean;
        entered: number;
        no_trades: number;
        active: number;
        completed: number;
        wins: number;
        losses: number;
        entry_rate: number | null;
        win_rate: number | null;
        average_r: number | null;
        total_r: number | null;
        profit_factor: number | null;
    };
    by_mode: Row[];
    by_direction: Row[];
    by_market: Row[];
    by_timeframe: Row[];
    by_symbol: Row[];
    confidence_calibration: Array<{
        bucket: string;
        signals: number;
        expected_confidence: number | null;
        observed_win_rate: number | null;
        gap: number | null;
    }>;
    alignment_quality: Row[];
    quality_matrix: Array<{
        confidence_bucket: string;
        alignment_bucket: string;
        signals: number;
        wins: number;
        losses: number;
        win_rate: number | null;
        average_r: number | null;
        total_r: number | null;
    }>;
    regime_quality: Row[];
    gate_outcomes: Array<{
        key: string;
        label: string;
        evaluations: number;
        passes: number;
        blocks: number;
        warnings: number;
        pass_rate: number | null;
    }>;
    coverage: {
        persisted_traces: number;
        with_confidence: number;
        with_alignment: number;
        with_regime: number;
        sample: number;
        matching: number;
        limit: number;
    };
};
type Row = {
    key: string;
    total: number;
    entered: number;
    wins: number;
    losses: number;
    no_trades: number;
    entry_rate: number | null;
    win_rate: number | null;
    average_r: number | null;
    total_r: number | null;
};

const pct = (value: number | null | undefined) =>
    value == null ? "—" : `${value.toFixed(1)}%`;
const r = (value: number | null | undefined) =>
    value == null ? "—" : `${value >= 0 ? "+" : ""}${value.toFixed(2)}R`;
const number = (value: number | null | undefined, digits = 1) =>
    value == null || !Number.isFinite(value) ? "—" : value.toFixed(digits);
const pretty = (value: string) =>
    value.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());

function Stat({
    icon,
    label,
    value,
    detail,
    highlight,
}: {
    icon: React.ReactNode;
    label: string;
    value: React.ReactNode;
    detail?: string;
    highlight?: boolean;
}) {
    return (
        <Card
            className={`relative overflow-hidden transition-all duration-300 hover:shadow-lg hover:border-primary-500/40 ${highlight ? "bg-gradient-to-br from-primary-500/10 via-card to-card border-primary-500/30 shadow-primary-500/5" : "bg-card/60 backdrop-blur-md border-border/60"}`}
        >
            <div className="absolute top-0 right-0 p-3 opacity-10 pointer-events-none transform translate-x-2 -translate-y-2">
                {icon}
            </div>
            <CardContent className="p-5">
                <div className="flex items-start justify-between gap-3">
                    <div className="space-y-1">
                        <div className="text-xs font-semibold tracking-wider uppercase text-muted-foreground/90 flex items-center gap-1.5">
                            {label}
                        </div>
                        <div className="text-2xl font-black tracking-tight text-foreground sm:text-3xl">
                            {value}
                        </div>
                        {detail ? (
                            <div className="text-xs font-medium text-muted-foreground/80 flex items-center gap-1 pt-0.5">
                                {detail}
                            </div>
                        ) : null}
                    </div>
                    <div className="rounded-2xl border border-border/80 bg-background/80 p-3 shadow-sm text-primary-500 flex items-center justify-center">
                        {icon}
                    </div>
                </div>
            </CardContent>
        </Card>
    );
}

function Table({
    rows,
    labels = ["Group", "Signals", "Entry", "Win", "Avg R"],
}: {
    rows: Row[];
    labels?: string[];
}) {
    return (
        <div className="-mx-4 max-h-[380px] overflow-y-auto overflow-x-auto px-4 scrollbar-thin scrollbar-thumb-primary-500/20">
            <table className="w-full min-w-[620px] text-xs">
                <thead className="sticky top-0 z-10 bg-muted/95 text-left text-muted-foreground backdrop-blur-md shadow-sm">
                    <tr>
                        {labels.map((label) => (
                            <th
                                key={label}
                                className="whitespace-nowrap p-3.5 font-bold uppercase tracking-wider text-[10px] first:pl-4 last:pr-4"
                            >
                                {label}
                            </th>
                        ))}
                    </tr>
                </thead>
                <tbody className="divide-y divide-border/40">
                    {rows.length === 0 ? (
                        <tr>
                            <td
                                colSpan={labels.length}
                                className="p-8 text-center text-muted-foreground font-medium"
                            >
                                <div className="flex flex-col items-center justify-center gap-2">
                                    <ShieldAlert className="size-6 text-muted-foreground/40" />
                                    <span>
                                        No persisted data for this filter.
                                    </span>
                                </div>
                            </td>
                        </tr>
                    ) : (
                        rows.map((row) => (
                            <tr
                                key={row.key}
                                className="transition-all hover:bg-primary-500/[0.03]"
                            >
                                <td className="p-3.5 font-bold text-foreground first:pl-4">
                                    {pretty(row.key)}
                                </td>
                                <td className="p-3.5 font-medium text-muted-foreground">
                                    {row.total}
                                </td>
                                <td className="p-3.5 font-medium text-muted-foreground">
                                    {pct(row.entry_rate)}
                                </td>
                                <td className="p-3.5 font-medium text-success-500 dark:text-success-400">
                                    {pct(row.win_rate)}
                                </td>
                                <td className="p-3.5 font-bold tabular-nums text-foreground last:pr-4">
                                    <span
                                        className={`px-2 py-1 rounded-md ${row.average_r && row.average_r >= 0 ? "bg-success-500/10 text-success-600 dark:text-success-400" : "bg-destructive-500/10 text-destructive-600 dark:text-destructive-400"}`}
                                    >
                                        {r(row.average_r)}
                                    </span>
                                </td>
                            </tr>
                        ))
                    )}
                </tbody>
            </table>
        </div>
    );
}

export default function SignalResearch({
    providers,
    defaultProvider,
    symbols,
    defaultSymbol,
    defaultMarket,
    defaultInterval,
    canReplay,
}: Props) {
    const { t } = useI18n();
    const [tab, setTab] = useState<"explain" | "quality" | "replay">("explain");
    const [provider, setProvider] = useState(defaultProvider);
    const [market, setMarket] = useState<MarketType>(defaultMarket);
    const [symbol, setSymbol] = useState(defaultSymbol);
    const [interval, setInterval] = useState(defaultInterval);
    const [signalMode, setSignalMode] = useState("strict");
    const [qualityMode, setQualityMode] = useState("all");
    const [direction, setDirection] = useState("all");
    const [from, setFrom] = useState("");
    const [to, setTo] = useState("");
    const [explain, setExplain] = useState<Explain | null>(null);
    const [quality, setQuality] = useState<Quality | null>(null);
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState("");

    const availableSymbols = symbols[provider]?.[market] ?? [];
    const selectedSymbol = useMemo(
        () =>
            availableSymbols.some((item) => item.symbol === symbol)
                ? symbol
                : (availableSymbols[0]?.symbol ?? symbol),
        [availableSymbols, symbol],
    );

    const loadExplain = useCallback(async () => {
        setLoading(true);
        setError("");
        try {
            const query = new URLSearchParams({
                provider,
                market,
                symbol: selectedSymbol,
                interval,
                signal_mode: signalMode,
            });
            const response = await fetch(`/signals/research/explain?${query}`, {
                headers: { Accept: "application/json" },
                credentials: "same-origin",
                cache: "no-store",
            });
            const payload = await response.json();
            if (!response.ok)
                throw new Error(
                    payload?.message ?? "Explain Signal gagal diproses.",
                );
            setExplain(payload);
        } catch (e) {
            setError(
                e instanceof Error
                    ? e.message
                    : "Explain Signal gagal diproses.",
            );
        } finally {
            setLoading(false);
        }
    }, [provider, market, selectedSymbol, interval, signalMode]);

    const loadQuality = useCallback(async () => {
        setLoading(true);
        setError("");
        try {
            const query = new URLSearchParams({
                provider,
                market,
                symbol: selectedSymbol,
                interval,
                direction,
                signal_mode: qualityMode,
                limit: "5000",
            });
            if (from) query.set("from", from);
            if (to) query.set("to", to);
            const response = await fetch(`/signals/research/quality?${query}`, {
                headers: { Accept: "application/json" },
                credentials: "same-origin",
                cache: "no-store",
            });
            const payload = await response.json();
            if (!response.ok)
                throw new Error(
                    payload?.message ??
                        "Signal Quality Analytics gagal diproses.",
                );
            setQuality(payload);
        } catch (e) {
            setError(
                e instanceof Error
                    ? e.message
                    : "Signal Quality Analytics gagal diproses.",
            );
        } finally {
            setLoading(false);
        }
    }, [
        provider,
        market,
        selectedSymbol,
        interval,
        direction,
        qualityMode,
        from,
        to,
    ]);

    useEffect(() => {
        if (tab === "explain") void loadExplain();
    }, [tab, loadExplain]);
    useEffect(() => {
        if (tab === "quality") void loadQuality();
    }, [tab, loadQuality]);

    const changeProvider = (next: string) => {
        setProvider(next);
        const nextSymbols = symbols[next]?.[market] ?? [];
        if (!nextSymbols.some((item) => item.symbol === symbol))
            setSymbol(nextSymbols[0]?.symbol ?? "");
    };
    const changeMarket = (next: MarketType) => {
        setMarket(next);
        const nextSymbols = symbols[provider]?.[next] ?? [];
        if (!nextSymbols.some((item) => item.symbol === symbol))
            setSymbol(nextSymbols[0]?.symbol ?? "");
    };

    return (
        <>
            <Head title={t("Signal Research")} />
            <div className="product-page min-h-full min-w-0 bg-background">
                <div className="mx-auto w-full min-w-0 max-w-[1600px] space-y-6">
                    <CustomerWorkspaceNav group="signals" />

                    {/* Hero Banner yang Lebih Menarik & Bernilai Jual */}
                    <Card className="relative overflow-hidden border-border/70 bg-card shadow-sm">
                        <div className="pointer-events-none absolute -right-16 -top-16 h-64 w-64 rounded-full bg-primary/5 blur-3xl"></div>
                        <CardContent className="p-6 sm:p-8 relative z-10">
                            <div className="flex flex-col gap-6 xl:flex-row xl:items-center xl:justify-between">
                                <div className="min-w-0 space-y-3">
                                    <div className="inline-flex items-center gap-2 rounded-full border border-primary/20 bg-primary/5 px-3 py-1 text-xs font-semibold uppercase tracking-[0.12em] text-primary">
                                        <Sparkles className="size-3.5" />
                                        {t("Signal analysis workspace")}
                                    </div>
                                    <h1 className="text-2xl font-bold tracking-tight text-foreground sm:text-3xl">
                                        {t("Signal Research")}
                                    </h1>
                                    <p className="max-w-3xl text-sm sm:text-base leading-relaxed text-muted-foreground">
                                        {t(
                                            "Review signal evidence, historical quality, and replay results in one focused research workspace.",
                                        )}
                                    </p>
                                    <div className="flex flex-wrap gap-2 pt-2">
                                        <Badge
                                            variant="secondary"
                                            className="bg-background/70 border-border/70 font-medium px-3 py-1 text-xs"
                                        >
                                            🚀 Provider: {provider}
                                        </Badge>
                                        <Badge
                                            variant="secondary"
                                            className="bg-background/70 border-border/70 font-medium px-3 py-1 text-xs"
                                        >
                                            ⚡ Market: {market.toUpperCase()}
                                        </Badge>
                                        <Badge
                                            variant="secondary"
                                            className="bg-background/80 border-border/80 shadow-sm font-semibold px-3 py-1 text-xs text-primary-500"
                                        >
                                            💎 Asset:{" "}
                                            {selectedSymbol || "No symbol"}
                                        </Badge>
                                        <Badge
                                            variant="secondary"
                                            className="bg-background/70 border-border/70 font-medium px-3 py-1 text-xs"
                                        >
                                            ⏱️ TF: {interval}
                                        </Badge>
                                        <Badge
                                            variant="outline"
                                            className="border-primary/30 text-primary font-medium px-3 py-1 text-xs"
                                        >
                                            🛡️ Mode: {signalMode}
                                        </Badge>
                                    </div>
                                </div>

                                <div className="w-full shrink-0 xl:w-auto">
                                    <Tabs
                                        value={tab}
                                        onValueChange={(value) =>
                                            setTab(
                                                value as
                                                    | "explain"
                                                    | "quality"
                                                    | "replay",
                                            )
                                        }
                                        className="w-full xl:w-auto"
                                    >
                                        <TabsList className="grid !h-12 w-full grid-cols-3 gap-2 rounded-2xl border border-primary-500/20 bg-background/80 p-1.5 shadow-lg backdrop-blur-md xl:min-w-[450px]">
                                            <TabsTrigger
                                                value="explain"
                                                className="flex h-full min-w-0 items-center justify-center gap-2 rounded-xl px-4 text-xs sm:text-sm font-bold transition-all data-[state=active]:bg-primary-600 data-[state=active]:text-white data-[state=active]:shadow-md text-muted-foreground"
                                            >
                                                <Gauge className="size-4 shrink-0" />
                                                <span className="truncate">
                                                    Explain
                                                </span>
                                            </TabsTrigger>
                                            <TabsTrigger
                                                value="quality"
                                                className="flex h-full min-w-0 items-center justify-center gap-2 rounded-xl px-4 text-xs sm:text-sm font-bold transition-all data-[state=active]:bg-primary-600 data-[state=active]:text-white data-[state=active]:shadow-md text-muted-foreground"
                                            >
                                                <BarChart3 className="size-4 shrink-0" />
                                                <span className="truncate">
                                                    Quality
                                                </span>
                                            </TabsTrigger>
                                            <TabsTrigger
                                                value="replay"
                                                disabled={!canReplay}
                                                className="flex h-full min-w-0 items-center justify-center gap-2 rounded-xl px-4 text-xs sm:text-sm font-bold transition-all data-[state=active]:bg-primary-600 data-[state=active]:text-white data-[state=active]:shadow-md text-muted-foreground disabled:opacity-40"
                                            >
                                                <History className="size-4 shrink-0" />
                                                <span className="truncate">
                                                    Replay
                                                </span>
                                            </TabsTrigger>
                                        </TabsList>
                                    </Tabs>
                                </div>
                            </div>
                        </CardContent>
                    </Card>

                    {/* Filter Panel yang Lebih Modern */}
                    <Card className="border-border/70 shadow-md bg-card/80 backdrop-blur-md">
                        <CardHeader className="gap-1 border-b bg-muted/30 px-5 py-4">
                            <div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
                                <div>
                                    <CardTitle className="flex items-center gap-2 text-sm font-bold tracking-tight">
                                        <SlidersHorizontal className="size-4 text-primary-500" />
                                        Advanced Research Filters
                                    </CardTitle>
                                    <p className="mt-0.5 text-xs text-muted-foreground">
                                        Sesuaikan parameter pasar secara
                                        real-time untuk pengujian sinyal presisi
                                        tinggi.
                                    </p>
                                </div>
                                {loading ? (
                                    <Badge
                                        variant="outline"
                                        className="w-fit gap-2 border-primary-500/40 bg-primary-500/10 text-primary-600 dark:text-primary-400 font-semibold"
                                    >
                                        <RefreshCw className="size-3.5 animate-spin" />
                                        Syncing Engine…
                                    </Badge>
                                ) : null}
                            </div>
                        </CardHeader>
                        <CardContent className="grid gap-4 p-5 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-5">
                            <Control label="Provider">
                                <Select
                                    value={provider}
                                    onValueChange={changeProvider}
                                >
                                    <SelectTrigger className="w-full bg-background/90 border-border/80 shadow-sm font-medium">
                                        <SelectValue />
                                    </SelectTrigger>
                                    <SelectContent>
                                        {providers.map((item) => (
                                            <SelectItem
                                                key={item.slug}
                                                value={item.slug}
                                            >
                                                {item.name}
                                            </SelectItem>
                                        ))}
                                    </SelectContent>
                                </Select>
                            </Control>
                            <Control label="Market Type">
                                <Select
                                    value={market}
                                    onValueChange={(value) =>
                                        changeMarket(value as MarketType)
                                    }
                                >
                                    <SelectTrigger className="w-full bg-background/90 border-border/80 shadow-sm font-medium">
                                        <SelectValue />
                                    </SelectTrigger>
                                    <SelectContent>
                                        <SelectItem value="spot">
                                            Spot Market
                                        </SelectItem>
                                        <SelectItem value="futures">
                                            Futures Derivatives
                                        </SelectItem>
                                    </SelectContent>
                                </Select>
                            </Control>
                            <Control label="Trading Pair / Coin">
                                <Select
                                    value={selectedSymbol}
                                    onValueChange={setSymbol}
                                >
                                    <SelectTrigger className="w-full bg-background/90 border-border/80 shadow-sm font-medium">
                                        <SelectValue />
                                    </SelectTrigger>
                                    <SelectContent className="max-h-80">
                                        {availableSymbols.map((item) => (
                                            <SelectItem
                                                key={item.symbol}
                                                value={item.symbol}
                                            >
                                                {item.symbol} · {item.name}
                                            </SelectItem>
                                        ))}
                                    </SelectContent>
                                </Select>
                            </Control>
                            <Control label="Timeframe">
                                <Select
                                    value={interval}
                                    onValueChange={setInterval}
                                >
                                    <SelectTrigger className="w-full bg-background/90 border-border/80 shadow-sm font-medium">
                                        <SelectValue />
                                    </SelectTrigger>
                                    <SelectContent>
                                        {[
                                            "1m",
                                            "5m",
                                            "15m",
                                            "30m",
                                            "1h",
                                            "4h",
                                            "1d",
                                            "1w",
                                        ].map((item) => (
                                            <SelectItem key={item} value={item}>
                                                {item}
                                            </SelectItem>
                                        ))}
                                    </SelectContent>
                                </Select>
                            </Control>
                            <Control label="Engine Signal Mode">
                                <Select
                                    value={signalMode}
                                    onValueChange={setSignalMode}
                                >
                                    <SelectTrigger className="w-full bg-background/90 border-border/80 shadow-sm font-medium text-primary-600 dark:text-primary-400 font-semibold">
                                        <SelectValue />
                                    </SelectTrigger>
                                    <SelectContent>
                                        <SelectItem value="strict">
                                            Strict (High Conviction)
                                        </SelectItem>
                                        <SelectItem value="balanced">
                                            Balanced Mode
                                        </SelectItem>
                                        <SelectItem value="flexible">
                                            Flexible Mode
                                        </SelectItem>
                                    </SelectContent>
                                </Select>
                            </Control>
                        </CardContent>
                    </Card>

                    {tab === "quality" ? (
                        <Card className="border-border/70 shadow-md bg-card/80 backdrop-blur-md">
                            <CardHeader className="gap-1 border-b bg-muted/30 px-5 py-4">
                                <div className="flex flex-col gap-1.5 sm:flex-row sm:items-center sm:justify-between">
                                    <div>
                                        <CardTitle className="text-sm font-bold tracking-tight">
                                            Quality Analytics Scope
                                        </CardTitle>
                                        <p className="mt-0.5 text-xs text-muted-foreground">
                                            Saring rentang waktu dan arah sinyal
                                            untuk analisis performa historis
                                            yang akurat.
                                        </p>
                                    </div>
                                    <Badge
                                        variant="secondary"
                                        className="bg-primary-500/10 text-primary-600 dark:text-primary-400 font-bold"
                                    >
                                        📊 {quality?.coverage.sample ?? 0}{" "}
                                        Sampled /{" "}
                                        {quality?.coverage.matching ?? 0}{" "}
                                        Matching
                                    </Badge>
                                </div>
                            </CardHeader>
                            <CardContent className="grid gap-4 p-5 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-6">
                                <Control label="Signal Mode Filter">
                                    <Select
                                        value={qualityMode}
                                        onValueChange={setQualityMode}
                                    >
                                        <SelectTrigger className="w-full bg-background/90 border-border/80 font-medium">
                                            <SelectValue />
                                        </SelectTrigger>
                                        <SelectContent>
                                            <SelectItem value="all">
                                                All Modes
                                            </SelectItem>
                                            <SelectItem value="strict">
                                                Strict
                                            </SelectItem>
                                            <SelectItem value="balanced">
                                                Balanced
                                            </SelectItem>
                                            <SelectItem value="flexible">
                                                Flexible
                                            </SelectItem>
                                        </SelectContent>
                                    </Select>
                                </Control>
                                <Control label="Position Direction">
                                    <Select
                                        value={direction}
                                        onValueChange={setDirection}
                                    >
                                        <SelectTrigger className="w-full bg-background/90 border-border/80 font-medium">
                                            <SelectValue />
                                        </SelectTrigger>
                                        <SelectContent>
                                            <SelectItem value="all">
                                                Both Directions
                                            </SelectItem>
                                            <SelectItem value="long">
                                                Long Only
                                            </SelectItem>
                                            <SelectItem value="short">
                                                Short Only
                                            </SelectItem>
                                        </SelectContent>
                                    </Select>
                                </Control>
                                <Control label="Start Date (From)">
                                    <Input
                                        type="date"
                                        value={from}
                                        onChange={(e) =>
                                            setFrom(e.target.value)
                                        }
                                        className="bg-background/90 border-border/80 font-medium"
                                    />
                                </Control>
                                <Control label="End Date (To)">
                                    <Input
                                        type="date"
                                        min={from || undefined}
                                        value={to}
                                        onChange={(e) => setTo(e.target.value)}
                                        className="bg-background/90 border-border/80 font-medium"
                                    />
                                </Control>
                                <div className="flex items-end gap-2 sm:col-span-2 xl:col-span-1">
                                    <Button
                                        variant="default"
                                        className="w-full bg-primary-600 hover:bg-primary-700 text-white font-bold shadow-sm"
                                        onClick={() => void loadQuality()}
                                        disabled={loading}
                                    >
                                        <RefreshCw
                                            className={
                                                loading
                                                    ? "size-4 animate-spin mr-1.5"
                                                    : "size-4 mr-1.5"
                                            }
                                        />
                                        Apply Filter
                                    </Button>
                                </div>
                                <Button
                                    type="button"
                                    variant="outline"
                                    className="w-full justify-center border-border/80 hover:bg-muted font-medium sm:col-span-2 lg:col-span-1 xl:col-span-1 self-end"
                                    onClick={() => {
                                        setQualityMode("all");
                                        setDirection("all");
                                        setFrom("");
                                        setTo("");
                                    }}
                                >
                                    <RotateCcw className="size-4 mr-1.5" />
                                    Reset Range
                                </Button>
                            </CardContent>
                        </Card>
                    ) : null}

                    {error ? (
                        <Card className="border-destructive/40 bg-destructive/10 shadow-md">
                            <CardContent className="flex items-start gap-3 p-5 text-sm text-destructive">
                                <AlertTriangle className="mt-0.5 size-5 shrink-0" />
                                <div className="min-w-0">
                                    <div className="font-bold text-base">
                                        Gagal Memuat Data Research
                                    </div>
                                    <div className="mt-1 break-words text-destructive/90 font-medium">
                                        {error}
                                    </div>
                                </div>
                            </CardContent>
                        </Card>
                    ) : null}

                    {loading && !explain && !quality && tab !== "replay" ? (
                        <Card className="border-border/70 shadow-md">
                            <CardContent className="flex min-h-[300px] items-center justify-center p-8 text-sm text-muted-foreground">
                                <div className="flex flex-col items-center gap-4 text-center">
                                    <div className="rounded-2xl border border-primary-500/30 bg-primary-500/10 p-4 shadow-inner">
                                        <RefreshCw className="size-6 animate-spin text-primary-500" />
                                    </div>
                                    <div>
                                        <div className="font-bold text-foreground text-base">
                                            Menganalisis Parameter Pasar…
                                        </div>
                                        <div className="mt-1 text-xs text-muted-foreground">
                                            Sistem sedang memproses kalkulasi
                                            mesin sinyal real-time.
                                        </div>
                                    </div>
                                </div>
                            </CardContent>
                        </Card>
                    ) : null}

                    {tab === "explain" && explain ? (
                        <ExplainPanel data={explain} />
                    ) : null}
                    {tab === "quality" && quality ? (
                        <QualityPanel data={quality} />
                    ) : null}
                    {tab === "replay" ? (
                        canReplay ? (
                            <SignalEngineReplayPanel
                                symbol={selectedSymbol}
                                market={market}
                                interval={interval}
                                provider={provider}
                            />
                        ) : (
                            <Card className="border-border/70 shadow-md">
                                <CardContent className="flex items-start gap-4 p-6 text-sm text-muted-foreground">
                                    <ShieldAlert className="mt-0.5 size-6 shrink-0 text-warning-500" />
                                    <div>
                                        <div className="font-bold text-foreground text-base">
                                            Historical Replay Terkunci
                                        </div>
                                        <div className="mt-1 text-xs leading-relaxed">
                                            Fitur Historical Replay memerlukan
                                            langganan paket Backtest /
                                            Enterprise entitlement aktif.
                                        </div>
                                    </div>
                                </CardContent>
                            </Card>
                        )
                    ) : null}
                </div>
            </div>
        </>
    );
}

function Control({
    label,
    children,
}: {
    label: string;
    children: React.ReactNode;
}) {
    return (
        <div className="space-y-1.5">
            <div className="text-xs font-bold uppercase tracking-wider text-muted-foreground">
                {label}
            </div>
            {children}
        </div>
    );
}

function ExplainPanel({ data }: { data: Explain }) {
    const { t } = useI18n();
    const statusBlocked = !data.decision.execution_allowed;
    return (
        <div className="space-y-6">
            <section className="grid gap-4 sm:grid-cols-2 lg:grid-cols-5">
                <Stat
                    icon={
                        statusBlocked ? (
                            <XCircle className="size-5 text-destructive-500" />
                        ) : (
                            <CheckCircle2 className="size-5 text-success-500" />
                        )
                    }
                    label="Engine Decision"
                    value={statusBlocked ? "BLOCKED" : "CONFIRMED"}
                    detail={data.decision.action}
                    highlight={!statusBlocked}
                />
                <Stat
                    icon={<Target className="size-5 text-primary-500" />}
                    label="Target Direction"
                    value={data.decision.direction.toUpperCase()}
                    detail={`Candidate: ${data.decision.candidate_direction}`}
                />
                <Stat
                    icon={<TrendingUp className="size-5 text-info-500" />}
                    label="Adaptive Score"
                    value={number(data.decision.score)}
                    detail={`Base ${number(data.decision.base_score)} · Adj ${number(data.decision.adaptive_adjustment, 2)}`}
                />
                <Stat
                    icon={<Zap className="size-5 text-warning-500" />}
                    label="Confidence Level"
                    value={number(data.decision.confidence?.confidence)}
                    detail={`MTF ${number(data.decision.confidence?.confirmation_alignment)}%`}
                />
                <Stat
                    icon={<Clock3 className="size-5 text-slate-400" />}
                    label="Engine State"
                    value={
                        data.decision.execution_allowed ? "Ready" : "Waiting"
                    }
                    detail={
                        data.policy.decision_fingerprint
                            ? `fp ${data.policy.decision_fingerprint}`
                            : "No fingerprint"
                    }
                />
            </section>

            <div className="grid gap-6 lg:grid-cols-[1.35fr_0.85fr]">
                {/* Decision Trace Card */}
                <Card className="border-border/70 shadow-md bg-card/90">
                    <CardHeader className="border-b bg-muted/30 pb-4">
                        <CardTitle className="text-sm font-bold flex items-center gap-2">
                            <Activity className="size-4 text-primary-500" />
                            Decision Trace Breakdown
                        </CardTitle>
                    </CardHeader>
                    <CardContent className="py-4 px-0">
                        <div className="max-h-[520px] space-y-3 overflow-y-auto px-5 scrollbar-thin scrollbar-thumb-primary-500/20">
                            {data.policy.decision_trace.map((gate) => (
                                <div
                                    key={`${gate.key}-${gate.step}`}
                                    className="rounded-xl border border-border/80 bg-background/60 p-4 transition-all hover:border-primary-500/40 hover:shadow-sm"
                                >
                                    <div className="flex items-start justify-between gap-3">
                                        <div>
                                            <div className="text-xs font-bold text-foreground">
                                                {gate.label}
                                            </div>
                                            <div className="mt-0.5 text-[10px] font-medium text-muted-foreground">
                                                {gate.key} · {gate.stage} ·{" "}
                                                {gate.severity}
                                            </div>
                                        </div>
                                        <Badge
                                            variant={
                                                gate.status === "pass"
                                                    ? "secondary"
                                                    : gate.status === "warn"
                                                      ? "outline"
                                                      : "destructive"
                                            }
                                            className="font-bold text-[10px] uppercase tracking-wider"
                                        >
                                            {gate.status}
                                        </Badge>
                                    </div>
                                    <div className="mt-3 grid gap-2.5 text-[11px] sm:grid-cols-2">
                                        <div className="rounded-lg border border-border/50 bg-muted/40 p-2.5">
                                            <div className="text-[10px] font-bold text-muted-foreground uppercase">
                                                Value
                                            </div>
                                            <div className="mt-1 break-words font-semibold text-foreground">
                                                {renderValue(gate.value)}
                                            </div>
                                        </div>
                                        <div className="rounded-lg border border-border/50 bg-muted/40 p-2.5">
                                            <div className="text-[10px] font-bold text-muted-foreground uppercase">
                                                Target
                                            </div>
                                            <div className="mt-1 break-words font-semibold text-foreground">
                                                {renderValue(gate.target)}
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            ))}
                        </div>
                    </CardContent>
                </Card>

                {/* Why this decision Card */}
                <Card className="border-border/70 shadow-md bg-card/90">
                    <CardHeader className="border-b bg-muted/30 pb-4">
                        <CardTitle className="text-sm font-bold flex items-center gap-2">
                            <BrainCircuit className="size-4 text-primary-500" />
                            Why this decision?
                        </CardTitle>
                    </CardHeader>
                    <CardContent className="py-4 px-0">
                        <div className="max-h-[520px] space-y-4 overflow-y-auto px-5 scrollbar-thin scrollbar-thumb-primary-500/20">
                            <ReasonBlock
                                title="Hard Blockers"
                                items={data.policy.hard_failures}
                                icon={
                                    <XCircle className="size-4 text-destructive-500" />
                                }
                            />
                            <ReasonBlock
                                title="Candidate Blockers"
                                items={data.policy.candidate_failures}
                                icon={
                                    <ShieldAlert className="size-4 text-warning-500" />
                                }
                            />
                            <ReasonBlock
                                title="Engine Warnings"
                                items={[
                                    ...data.policy.warnings,
                                    ...data.warnings,
                                ]}
                                icon={
                                    <AlertTriangle className="size-4 text-warning-500" />
                                }
                            />
                            <ReasonBlock
                                title="Execution Reasons"
                                items={data.reasons}
                                icon={
                                    <CheckCircle2 className="size-4 text-success-500" />
                                }
                            />
                        </div>
                    </CardContent>
                </Card>
            </div>

            <div className="grid gap-6 lg:grid-cols-3">
                <Card className="border-border/70 shadow-md bg-card/90">
                    <CardHeader className="border-b bg-muted/30 pb-4">
                        <CardTitle className="text-sm font-bold">
                            Score Composition
                        </CardTitle>
                    </CardHeader>
                    <CardContent className="space-y-3.5 p-5 text-xs">
                        <Metric
                            label="Base Score"
                            value={number(data.primary.base_score)}
                        />
                        <Metric
                            label="Adaptive Score"
                            value={number(data.primary.adaptive_score)}
                        />
                        <Metric
                            label="Context Adjustment"
                            value={number(data.policy.context_adjustment, 2)}
                        />
                        <Metric
                            label="Rating Grade"
                            value={data.primary.rating ?? "—"}
                        />
                    </CardContent>
                </Card>
                <Card className="border-border/70 shadow-md bg-card/90">
                    <CardHeader className="border-b bg-muted/30 pb-4">
                        <CardTitle className="text-sm font-bold">
                            Strategy Context
                        </CardTitle>
                    </CardHeader>
                    <CardContent className="space-y-3.5 p-5 text-xs">
                        <Metric
                            label="Setup Type"
                            value={data.strategy.setup ?? "—"}
                        />
                        <Metric
                            label="Direction"
                            value={data.strategy.direction}
                        />
                        <Metric
                            label="Quality Score"
                            value={number(data.strategy.quality)}
                        />
                        <Metric
                            label="Grade Tier"
                            value={data.strategy.grade}
                        />
                        <Metric
                            label="Preferred Strategy"
                            value={data.strategy.preferred_strategy ?? "—"}
                        />
                    </CardContent>
                </Card>
                <Card className="border-border/70 shadow-md bg-card/90">
                    <CardHeader className="border-b bg-muted/30 pb-4">
                        <CardTitle className="text-sm font-bold">
                            Active Trade Plan
                        </CardTitle>
                    </CardHeader>
                    <CardContent className="space-y-3.5 p-5 text-xs">
                        {data.trade_plan ? (
                            <>
                                <Metric
                                    label="Entry Price"
                                    value={renderValue(data.trade_plan.entry)}
                                />
                                <Metric
                                    label="Stop Loss (SL)"
                                    value={renderValue(data.trade_plan.sl)}
                                />
                                <Metric
                                    label="Take Profit (TP)"
                                    value={renderValue(data.trade_plan.tp)}
                                />
                                <Metric
                                    label="Risk-Reward Ratio"
                                    value={renderValue(
                                        data.trade_plan.risk_reward,
                                    )}
                                />
                            </>
                        ) : (
                            <div className="py-8 text-center text-muted-foreground font-medium">
                                No valid trade plan in this snapshot.
                            </div>
                        )}
                    </CardContent>
                </Card>
            </div>

            <Card className="border-primary-500/20 bg-primary-500/5 shadow-sm">
                <CardContent className="flex gap-3 p-4 text-xs leading-relaxed text-muted-foreground">
                    <ShieldAlert className="mt-0.5 size-4 shrink-0 text-primary-500" />
                    <span>{t(data.note)}</span>
                </CardContent>
            </Card>
        </div>
    );
}

function ReasonBlock({
    title,
    items,
    icon,
}: {
    title: string;
    items: string[];
    icon: React.ReactNode;
}) {
    return (
        <div>
            <div className="mb-2 flex items-center gap-2 text-xs font-bold text-foreground uppercase tracking-wider">
                {icon}
                {title}
            </div>
            {items.length === 0 ? (
                <div className="rounded-xl border border-border/50 bg-muted/30 p-3 text-xs text-muted-foreground font-medium">
                    None recorded.
                </div>
            ) : (
                <div className="space-y-2">
                    {items.map((item, i) => (
                        <div
                            key={`${item}-${i}`}
                            className="rounded-xl border border-border/60 bg-background/80 p-3 text-xs font-medium leading-relaxed text-foreground shadow-sm"
                        >
                            {item}
                        </div>
                    ))}
                </div>
            )}
        </div>
    );
}

function Metric({ label, value }: { label: string; value: React.ReactNode }) {
    return (
        <div className="flex items-center justify-between gap-4 border-b border-border/40 pb-3 last:border-0 last:pb-0">
            <span className="text-muted-foreground font-medium">{label}</span>
            <span className="font-bold text-foreground">{value}</span>
        </div>
    );
}

function renderValue(value: unknown): React.ReactNode {
    if (value === null || value === undefined) return "—";
    if (typeof value === "object")
        return (
            <code className="whitespace-pre-wrap break-words text-[10px] font-mono">
                {JSON.stringify(value)}
            </code>
        );
    return String(value);
}

function QualityPanel({ data }: { data: Quality }) {
    const { t } = useI18n();
    return (
        <div className="space-y-6">
            <section className="grid gap-4 sm:grid-cols-2 lg:grid-cols-5">
                <Stat
                    icon={<BarChart3 className="size-5 text-primary-500" />}
                    label="Persisted Signals"
                    value={data.summary.signals}
                    detail={
                        data.summary.sample_limited
                            ? `Showing latest ${data.coverage.limit} of ${data.summary.matching_signals}`
                            : "Within current filter"
                    }
                />
                <Stat
                    icon={<Target className="size-5 text-info-500" />}
                    label="Entry Rate"
                    value={pct(data.summary.entry_rate)}
                    detail={`${data.summary.entered} entered`}
                />
                <Stat
                    icon={<CheckCircle2 className="size-5 text-success-500" />}
                    label="Win Rate"
                    value={pct(data.summary.win_rate)}
                    detail={`${data.summary.wins}W / ${data.summary.losses}L`}
                    highlight
                />
                <Stat
                    icon={<Activity className="size-5 text-warning-500" />}
                    label="Average R Multiple"
                    value={r(data.summary.average_r)}
                    detail={`Total ${r(data.summary.total_r)}`}
                />
                <Stat
                    icon={<ShieldAlert className="size-5 text-primary-500" />}
                    label="Profit Factor"
                    value={
                        data.summary.profit_factor == null
                            ? "—"
                            : data.summary.profit_factor.toFixed(2)
                    }
                    detail={`${data.summary.no_trades} no-trade`}
                />
            </section>

            <div className="grid gap-6 lg:grid-cols-2">
                <Card className="border-border/70 shadow-md bg-card/90">
                    <CardHeader className="border-b bg-muted/30 pb-4">
                        <CardTitle className="text-sm font-bold">
                            Performance By Signal Mode
                        </CardTitle>
                    </CardHeader>
                    <CardContent className="p-0 py-4">
                        <Table rows={data.by_mode} />
                    </CardContent>
                </Card>
                <Card className="border-border/70 shadow-md bg-card/90">
                    <CardHeader className="border-b bg-muted/30 pb-4">
                        <CardTitle className="text-sm font-bold">
                            Performance By Direction
                        </CardTitle>
                    </CardHeader>
                    <CardContent className="p-0 py-4">
                        <Table rows={data.by_direction} />
                    </CardContent>
                </Card>
                <Card className="border-border/70 shadow-md bg-card/90">
                    <CardHeader className="border-b bg-muted/30 pb-4">
                        <CardTitle className="text-sm font-bold">
                            Performance By Timeframe
                        </CardTitle>
                    </CardHeader>
                    <CardContent className="p-0 py-4">
                        <Table rows={data.by_timeframe} />
                    </CardContent>
                </Card>
                <Card className="border-border/70 shadow-md bg-card/90">
                    <CardHeader className="border-b bg-muted/30 pb-4">
                        <CardTitle className="text-sm font-bold">
                            Performance By Market Regime
                        </CardTitle>
                    </CardHeader>
                    <CardContent className="p-0 py-4">
                        <Table rows={data.regime_quality} />
                    </CardContent>
                </Card>
            </div>

            <div className="grid gap-6 lg:grid-cols-[1fr_1fr]">
                {/* Confidence Calibration Card */}
                <Card className="border-border/70 shadow-md bg-card/90">
                    <CardHeader className="border-b bg-muted/30 pb-4">
                        <CardTitle className="text-sm font-bold">
                            Confidence vs Observed Outcome
                        </CardTitle>
                    </CardHeader>
                    <CardContent className="px-0 py-4">
                        <div className="-mx-4 max-h-[380px] overflow-y-auto overflow-x-auto px-4 scrollbar-thin scrollbar-thumb-primary-500/20">
                            <table className="w-full min-w-[650px] text-xs">
                                <thead className="sticky top-0 z-10 bg-muted/95 text-left text-muted-foreground backdrop-blur-md shadow-sm">
                                    <tr>
                                        <th className="p-3.5 font-bold uppercase tracking-wider text-[10px] first:pl-4">
                                            Bucket
                                        </th>
                                        <th className="p-3.5 font-bold uppercase tracking-wider text-[10px]">
                                            Signals
                                        </th>
                                        <th className="p-3.5 font-bold uppercase tracking-wider text-[10px]">
                                            Expected
                                        </th>
                                        <th className="p-3.5 font-bold uppercase tracking-wider text-[10px]">
                                            Observed Win
                                        </th>
                                        <th className="p-3.5 font-bold uppercase tracking-wider text-[10px] last:pr-4">
                                            Gap
                                        </th>
                                    </tr>
                                </thead>
                                <tbody className="divide-y divide-border/40">
                                    {data.confidence_calibration.map((row) => (
                                        <tr
                                            key={row.bucket}
                                            className="transition-all hover:bg-primary-500/[0.03]"
                                        >
                                            <td className="p-3.5 font-bold text-foreground first:pl-4">
                                                {row.bucket}
                                            </td>
                                            <td className="p-3.5 font-medium text-muted-foreground">
                                                {row.signals}
                                            </td>
                                            <td className="p-3.5 font-medium text-muted-foreground">
                                                {pct(row.expected_confidence)}
                                            </td>
                                            <td className="p-3.5 font-bold text-success-500">
                                                {pct(row.observed_win_rate)}
                                            </td>
                                            <td className="p-3.5 font-bold tabular-nums text-foreground last:pr-4">
                                                {pct(row.gap)}
                                            </td>
                                        </tr>
                                    ))}
                                </tbody>
                            </table>
                        </div>
                        <p className="mt-4 px-5 text-xs leading-relaxed text-muted-foreground">
                            {t(
                                "Diagnostic only: the gap compares model confidence with observed win rate. It is not a formal probability calibration claim.",
                            )}
                        </p>
                    </CardContent>
                </Card>

                {/* Decision Gate Outcomes Card */}
                <Card className="border-border/70 shadow-md bg-card/90">
                    <CardHeader className="border-b bg-muted/30 pb-4">
                        <CardTitle className="text-sm font-bold">
                            Decision Gate Outcomes
                        </CardTitle>
                    </CardHeader>
                    <CardContent className="px-0 py-4">
                        <div className="-mx-4 max-h-[380px] overflow-y-auto overflow-x-auto px-4 scrollbar-thin scrollbar-thumb-primary-500/20">
                            <table className="w-full min-w-[700px] text-xs">
                                <thead className="sticky top-0 z-10 bg-muted/95 text-left text-muted-foreground backdrop-blur-md shadow-sm">
                                    <tr>
                                        <th className="p-3.5 font-bold uppercase tracking-wider text-[10px] first:pl-4">
                                            Gate Name
                                        </th>
                                        <th className="p-3.5 font-bold uppercase tracking-wider text-[10px]">
                                            Evals
                                        </th>
                                        <th className="p-3.5 font-bold uppercase tracking-wider text-[10px]">
                                            Pass
                                        </th>
                                        <th className="p-3.5 font-bold uppercase tracking-wider text-[10px]">
                                            Block
                                        </th>
                                        <th className="p-3.5 font-bold uppercase tracking-wider text-[10px]">
                                            Warn
                                        </th>
                                        <th className="p-3.5 font-bold uppercase tracking-wider text-[10px] last:pr-4">
                                            Pass Rate
                                        </th>
                                    </tr>
                                </thead>
                                <tbody className="divide-y divide-border/40">
                                    {data.gate_outcomes.map((gate) => (
                                        <tr
                                            key={gate.key}
                                            className="transition-all hover:bg-primary-500/[0.03]"
                                        >
                                            <td className="p-3.5 font-bold text-foreground first:pl-4">
                                                {gate.label}
                                            </td>
                                            <td className="p-3.5 font-medium text-muted-foreground">
                                                {gate.evaluations}
                                            </td>
                                            <td className="p-3.5 font-medium text-success-500">
                                                {gate.passes}
                                            </td>
                                            <td className="p-3.5 font-medium text-destructive-500">
                                                {gate.blocks}
                                            </td>
                                            <td className="p-3.5 font-medium text-warning-500">
                                                {gate.warnings}
                                            </td>
                                            <td className="p-3.5 font-bold tabular-nums text-foreground last:pr-4">
                                                {pct(gate.pass_rate)}
                                            </td>
                                        </tr>
                                    ))}
                                </tbody>
                            </table>
                        </div>
                        <p className="mt-4 px-5 text-xs leading-relaxed text-muted-foreground">
                            Persisted decision traces only. Describes signals
                            recorded in Signal Journal, not every rejected
                            candidate.
                        </p>
                    </CardContent>
                </Card>
            </div>

            {/* Quality Matrix Card */}
            <Card className="border-border/70 shadow-md bg-card/90">
                <CardHeader className="border-b bg-muted/30 pb-4">
                    <CardTitle className="text-sm font-bold flex items-center gap-2">
                        <Sparkles className="size-4 text-primary-500" />
                        Confidence × Confirmation Alignment Matrix
                    </CardTitle>
                </CardHeader>
                <CardContent className="px-0 py-4">
                    <div className="-mx-4 max-h-[420px] overflow-y-auto overflow-x-auto px-4 scrollbar-thin scrollbar-thumb-primary-500/20">
                        <table className="w-full min-w-[780px] text-xs">
                            <thead className="sticky top-0 z-10 bg-muted/95 text-left text-muted-foreground backdrop-blur-md shadow-sm">
                                <tr>
                                    <th className="p-3.5 font-bold uppercase tracking-wider text-[10px] first:pl-4">
                                        Confidence Bucket
                                    </th>
                                    <th className="p-3.5 font-bold uppercase tracking-wider text-[10px]">
                                        Alignment Bucket
                                    </th>
                                    <th className="p-3.5 font-bold uppercase tracking-wider text-[10px]">
                                        Signals
                                    </th>
                                    <th className="p-3.5 font-bold uppercase tracking-wider text-[10px]">
                                        W / L
                                    </th>
                                    <th className="p-3.5 font-bold uppercase tracking-wider text-[10px]">
                                        Win Rate
                                    </th>
                                    <th className="p-3.5 font-bold uppercase tracking-wider text-[10px]">
                                        Avg R
                                    </th>
                                    <th className="p-3.5 font-bold uppercase tracking-wider text-[10px] last:pr-4">
                                        Total R
                                    </th>
                                </tr>
                            </thead>
                            <tbody className="divide-y divide-border/40">
                                {data.quality_matrix.length === 0 ? (
                                    <tr>
                                        <td
                                            colSpan={7}
                                            className="p-8 text-center text-muted-foreground font-medium"
                                        >
                                            No matrix observations found.
                                        </td>
                                    </tr>
                                ) : (
                                    data.quality_matrix.map((row) => (
                                        <tr
                                            key={`${row.confidence_bucket}-${row.alignment_bucket}`}
                                            className="transition-all hover:bg-primary-500/[0.03]"
                                        >
                                            <td className="p-3.5 font-bold text-foreground first:pl-4">
                                                {row.confidence_bucket}
                                            </td>
                                            <td className="p-3.5 font-medium text-muted-foreground">
                                                {row.alignment_bucket}
                                            </td>
                                            <td className="p-3.5 font-medium text-muted-foreground">
                                                {row.signals}
                                            </td>
                                            <td className="p-3.5 font-medium text-muted-foreground">
                                                <span className="text-success-500 font-bold">
                                                    {row.wins}W
                                                </span>{" "}
                                                /{" "}
                                                <span className="text-destructive-500 font-bold">
                                                    {row.losses}L
                                                </span>
                                            </td>
                                            <td className="p-3.5 font-bold text-success-500 dark:text-success-400">
                                                {pct(row.win_rate)}
                                            </td>
                                            <td className="p-3.5 font-bold tabular-nums text-foreground">
                                                {r(row.average_r)}
                                            </td>
                                            <td className="p-3.5 font-bold tabular-nums text-foreground last:pr-4">
                                                <span
                                                    className={`px-2 py-1 rounded-md ${row.total_r && row.total_r >= 0 ? "bg-success-500/10 text-success-600 dark:text-success-400" : "bg-destructive-500/10 text-destructive-600 dark:text-destructive-400"}`}
                                                >
                                                    {r(row.total_r)}
                                                </span>
                                            </td>
                                        </tr>
                                    ))
                                )}
                            </tbody>
                        </table>
                    </div>
                </CardContent>
            </Card>

            <Card className="border-primary-500/20 bg-primary-500/5 shadow-sm">
                <CardContent className="flex gap-3 p-4 text-xs leading-relaxed text-muted-foreground">
                    <ShieldAlert className="mt-0.5 size-4 shrink-0 text-primary-500" />
                    <span>
                        {t(
                            "Signal Quality uses persisted Signal Journal outcomes. An invalidation before entry is treated as No Trade rather than a loss. Use sufficient sample sizes before changing production signal parameters.",
                        )}
                    </span>
                </CardContent>
            </Card>
        </div>
    );
}
