import { useEffect, useRef, useState, type ReactNode } from "react";
import { Save } from "lucide-react";
import type { MarketType } from "@/lib/market";
import type { SignalMode } from "@/types/insight";
import { Card, CardContent, CardHeader } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from "@/components/ui/select";
import { useI18n } from "@/lib/i18n";

type Props = {
    symbol: string;
    market: MarketType;
    interval: string;
    provider?: string;
};

type ModeComparisonResult = {
    symbol: string;
    market: MarketType;
    interval: string;
    modes: Record<SignalMode, Result>;
};

type ComparisonResult = {
    symbol: string;
    market: MarketType;
    comparison: { a: Result; b: Result };
};
type Result = {
    signal_mode?: SignalMode;
    symbol: string;
    market: MarketType;
    interval: string;
    lookahead_safe: boolean;
    candles: number;
    summary: {
        signals: number;
        wins: number;
        losses: number;
        win_rate: number;
        total_r: number;
        average_r: number;
        max_drawdown_r: number;
        fees?: number;
        funding_fee?: number;
    };
    rules: {
        signal_uses_candle_close: boolean;
        entry_uses_next_candle_open: boolean;
        confirmation_uses_data_at_signal_time_only: boolean;
        same_candle_sl_tp: string;
    };
    trades: Array<{
        signal_time: number;
        entry_time: number;
        exit_time: number;
        direction: string;
        score: number;
        base_score?: number;
        adaptive_adjustment?: number;
        signal_mode?: SignalMode;
        confidence: number;
        confirmation_alignment: number;
        entry: number;
        sl: number;
        tp: number;
        exit: number;
        reason: string;
        r_multiple: number | null;
        cumulative_r: number;
    }>;
    equity_curve: Array<{
        index: number;
        time: number;
        cumulative_r: number;
        drawdown_r: number;
        r_multiple: number | null;
        outcome: string;
    }>;
    quality_matrix: Array<{
        confidence_bucket: string;
        alignment_bucket: string;
        signals: number;
        wins: number;
        losses: number;
        total_r: number;
        average_r: number;
        win_rate: number;
    }>;
};

const n = (v: number | null, d = 2) => (v == null ? "—" : v.toFixed(d));

export default function SignalEngineReplayPanel({
    symbol,
    market,
    interval,
    provider = "binance",
}: Props) {
    const { t } = useI18n();
    const [direction, setDirection] = useState("both");
    const [signalMode, setSignalMode] = useState<SignalMode>("strict");
    const [candles, setCandles] = useState("500");
    const [ambiguity, setAmbiguity] = useState("conservative");
    const [startDate, setStartDate] = useState("");
    const [endDate, setEndDate] = useState("");
    const [result, setResult] = useState<Result | null>(null);
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState<string | null>(null);
    const [compareInterval, setCompareInterval] = useState(
        interval === "15m" ? "1h" : "15m",
    );
    const [comparison, setComparison] = useState<ComparisonResult | null>(null);
    const [modeComparison, setModeComparison] =
        useState<ModeComparisonResult | null>(null);
    const [modeCompareLoading, setModeCompareLoading] = useState(false);
    const [compareLoading, setCompareLoading] = useState(false);
    const [savingReport, setSavingReport] = useState(false);
    const contextKey = `${symbol}|${market}|${interval}|${provider}`;
    const contextKeyRef = useRef(contextKey);
    const runControllerRef = useRef<AbortController | null>(null);
    const compareControllerRef = useRef<AbortController | null>(null);
    const modeControllerRef = useRef<AbortController | null>(null);
    const effectiveDirection = market === "spot" ? "long" : direction;

    useEffect(() => {
        contextKeyRef.current = contextKey;
        runControllerRef.current?.abort();
        compareControllerRef.current?.abort();
        modeControllerRef.current?.abort();
        setResult(null);
        setComparison(null);
        setModeComparison(null);
        setError(null);
        setLoading(false);
        setCompareLoading(false);
        setModeCompareLoading(false);
    }, [contextKey]);

    useEffect(() => {
        if (market === "spot" && direction !== "long") {
            setDirection("long");
        }
    }, [market, direction]);

    const run = async () => {
        runControllerRef.current?.abort();
        const controller = new AbortController();
        runControllerRef.current = controller;
        const requestContext = contextKey;
        setLoading(true);
        setError(null);
        try {
            const response = await fetch("/market/backtest/signal-engine", {
                method: "POST",
                headers: {
                    Accept: "application/json",
                    "Content-Type": "application/json",
                    "X-Requested-With": "XMLHttpRequest",
                },
                credentials: "same-origin",
                signal: controller.signal,
                body: JSON.stringify({
                    symbol,
                    market,
                    provider,
                    interval,
                    direction: effectiveDirection,
                    signal_mode: signalMode,
                    candles_limit: Number(candles),
                    ambiguity,
                    fee_pct: 0.1,
                    slippage_pct: 0.05,
                    max_trades: 100,
                    start_date: startDate || null,
                    end_date: endDate || null,
                }),
            });
            const payload = await response.json().catch(() => ({}));
            if (!response.ok)
                throw new Error(
                    payload?.message ?? "Gagal menjalankan historical replay.",
                );
            if (
                controller.signal.aborted ||
                contextKeyRef.current !== requestContext
            )
                return;
            setResult(payload as Result);
        } catch (e) {
            if (
                controller.signal.aborted ||
                contextKeyRef.current !== requestContext
            )
                return;
            setResult(null);
            setError(
                e instanceof Error
                    ? e.message
                    : "Gagal menjalankan historical replay.",
            );
        } finally {
            if (contextKeyRef.current === requestContext) setLoading(false);
            if (runControllerRef.current === controller)
                runControllerRef.current = null;
        }
    };

    const saveReport = async () => {
        if (!result || savingReport) return;

        const name = window.prompt(
            t("Backtest report name"),
            `${symbol} ${interval} ${t("Signal Engine")}`,
        );
        if (!name?.trim()) return;

        setSavingReport(true);
        setError(null);
        try {
            const response = await fetch("/market/backtest/reports", {
                method: "POST",
                headers: {
                    Accept: "application/json",
                    "Content-Type": "application/json",
                    "X-Requested-With": "XMLHttpRequest",
                    "X-CSRF-TOKEN":
                        document
                            .querySelector('meta[name="csrf-token"]')
                            ?.getAttribute("content") ?? "",
                },
                credentials: "same-origin",
                body: JSON.stringify({
                    name: name.trim(),
                    symbol,
                    market,
                    provider,
                    interval,
                    direction: effectiveDirection,
                    configuration: {
                        direction: effectiveDirection,
                        provider,
                        signal_mode: signalMode,
                        candles_limit: Number(candles),
                        ambiguity,
                        fee_pct: 0.1,
                        slippage_pct: 0.05,
                        max_trades: 100,
                        start_date: startDate || null,
                        end_date: endDate || null,
                        mode_comparison: modeComparison,
                    },
                    result,
                    comparison,
                }),
            });
            const payload = await response.json().catch(() => ({}));
            if (!response.ok) {
                throw new Error(payload?.message ?? "Gagal menyimpan report.");
            }
            if (payload?.url) {
                window.location.assign(payload.url);
            }
        } catch (e) {
            setError(
                e instanceof Error ? e.message : "Gagal menyimpan report.",
            );
        } finally {
            setSavingReport(false);
        }
    };

    const runComparison = async () => {
        if (compareInterval === interval) {
            setError("Pilih timeframe pembanding yang berbeda.");
            return;
        }
        compareControllerRef.current?.abort();
        const controller = new AbortController();
        compareControllerRef.current = controller;
        const requestContext = contextKey;
        setCompareLoading(true);
        setError(null);
        try {
            const response = await fetch(
                "/market/backtest/signal-engine/compare",
                {
                    method: "POST",
                    headers: {
                        Accept: "application/json",
                        "Content-Type": "application/json",
                        "X-Requested-With": "XMLHttpRequest",
                    },
                    credentials: "same-origin",
                    signal: controller.signal,
                    body: JSON.stringify({
                        symbol,
                        market,
                        provider,
                        interval_a: interval,
                        interval_b: compareInterval,
                        direction: effectiveDirection,
                        candles_limit: Number(candles),
                        ambiguity,
                        fee_pct: 0.1,
                        slippage_pct: 0.05,
                        max_trades: 100,
                        start_date: startDate || null,
                        end_date: endDate || null,
                    }),
                },
            );
            const payload = await response.json().catch(() => ({}));
            if (!response.ok)
                throw new Error(
                    payload?.message ?? "Gagal menjalankan comparison.",
                );
            if (
                controller.signal.aborted ||
                contextKeyRef.current !== requestContext
            )
                return;
            setComparison(payload as ComparisonResult);
        } catch (e) {
            if (
                controller.signal.aborted ||
                contextKeyRef.current !== requestContext
            )
                return;
            setComparison(null);
            setError(
                e instanceof Error
                    ? e.message
                    : "Gagal menjalankan comparison.",
            );
        } finally {
            if (contextKeyRef.current === requestContext)
                setCompareLoading(false);
            if (compareControllerRef.current === controller)
                compareControllerRef.current = null;
        }
    };

    const runModeComparison = async () => {
        modeControllerRef.current?.abort();
        const controller = new AbortController();
        modeControllerRef.current = controller;
        const requestContext = contextKey;
        setModeCompareLoading(true);
        setError(null);
        try {
            const response = await fetch(
                "/market/backtest/signal-engine/modes",
                {
                    method: "POST",
                    headers: {
                        Accept: "application/json",
                        "Content-Type": "application/json",
                        "X-Requested-With": "XMLHttpRequest",
                    },
                    credentials: "same-origin",
                    signal: controller.signal,
                    body: JSON.stringify({
                        symbol,
                        market,
                        provider,
                        interval,
                        direction: effectiveDirection,
                        candles_limit: Number(candles),
                        ambiguity,
                        fee_pct: 0.1,
                        slippage_pct: 0.05,
                        max_trades: 100,
                        start_date: startDate || null,
                        end_date: endDate || null,
                    }),
                },
            );
            const payload = await response.json().catch(() => ({}));
            if (!response.ok) {
                throw new Error(
                    payload?.message ?? "Gagal membandingkan signal modes.",
                );
            }
            if (
                controller.signal.aborted ||
                contextKeyRef.current !== requestContext
            )
                return;
            setModeComparison(payload as ModeComparisonResult);
        } catch (e) {
            if (
                controller.signal.aborted ||
                contextKeyRef.current !== requestContext
            )
                return;
            setModeComparison(null);
            setError(
                e instanceof Error
                    ? e.message
                    : "Gagal membandingkan signal modes.",
            );
        } finally {
            if (contextKeyRef.current === requestContext)
                setModeCompareLoading(false);
            if (modeControllerRef.current === controller)
                modeControllerRef.current = null;
        }
    };

    return (
        <Card className="mt-4 border-border bg-card shadow-xs">
            <CardHeader className="flex flex-row items-start justify-between border-b border-border/60 pb-4 p-5">
                <div>
                    <div className="text-[11px] font-bold uppercase tracking-[.16em] text-violet-500">
                        Signal Engine Historical Replay
                    </div>
                    <p className="mt-1 text-xs text-muted-foreground">
                        Replay engine yang sama pada candle historis tanpa
                        memakai candle masa depan untuk mendeteksi signal.
                    </p>
                </div>
                <Badge
                    variant="outline"
                    className="border-violet-500/20 bg-violet-500/10 text-[10px] font-semibold text-violet-600 dark:text-violet-300"
                >
                    NO LOOK-AHEAD
                </Badge>
            </CardHeader>

            <CardContent className="p-5 pt-4 space-y-4">
                <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
                    <Field label="Signal mode">
                        <Select
                            value={signalMode}
                            onValueChange={(value) =>
                                setSignalMode(value as SignalMode)
                            }
                        >
                            <SelectTrigger className="h-9 text-xs shadow-xs">
                                <SelectValue />
                            </SelectTrigger>
                            <SelectContent>
                                <SelectItem value="strict">Strict</SelectItem>
                                <SelectItem value="balanced">
                                    Balanced
                                </SelectItem>
                                <SelectItem value="flexible">
                                    Flexible
                                </SelectItem>
                            </SelectContent>
                        </Select>
                    </Field>
                    <Field label="Direction">
                        <Select
                            value={effectiveDirection}
                            onValueChange={setDirection}
                        >
                            <SelectTrigger className="h-9 text-xs shadow-xs">
                                <SelectValue />
                            </SelectTrigger>
                            <SelectContent>
                                <SelectItem value="long">Long only</SelectItem>
                                {market === "futures" ? (
                                    <>
                                        <SelectItem value="both">
                                            Long + Short
                                        </SelectItem>
                                        <SelectItem value="short">
                                            Short only
                                        </SelectItem>
                                    </>
                                ) : null}
                            </SelectContent>
                        </Select>
                    </Field>
                    <Field label="Historical candles">
                        <Select value={candles} onValueChange={setCandles}>
                            <SelectTrigger className="h-9 text-xs shadow-xs">
                                <SelectValue />
                            </SelectTrigger>
                            <SelectContent>
                                <SelectItem value="250">250</SelectItem>
                                <SelectItem value="500">500</SelectItem>
                                <SelectItem value="1000">1000</SelectItem>
                            </SelectContent>
                        </Select>
                    </Field>
                    <Field label="Same-candle SL/TP">
                        <Select value={ambiguity} onValueChange={setAmbiguity}>
                            <SelectTrigger className="h-9 text-xs shadow-xs">
                                <SelectValue />
                            </SelectTrigger>
                            <SelectContent>
                                <SelectItem value="conservative">
                                    Conservative — SL first
                                </SelectItem>
                                <SelectItem value="optimistic">
                                    Optimistic — TP first
                                </SelectItem>
                                <SelectItem value="skip">
                                    Skip ambiguous
                                </SelectItem>
                            </SelectContent>
                        </Select>
                    </Field>
                    <Field label="Start date">
                        <input
                            type="date"
                            value={startDate}
                            onChange={(event) => setStartDate(event.target.value)}
                            className="h-9 w-full rounded-md border border-input bg-background px-3 text-xs shadow-xs"
                        />
                    </Field>
                    <Field label="End date">
                        <input
                            type="date"
                            min={startDate || undefined}
                            value={endDate}
                            onChange={(event) => setEndDate(event.target.value)}
                            className="h-9 w-full rounded-md border border-input bg-background px-3 text-xs shadow-xs"
                        />
                    </Field>
                </div>

                <div className="flex flex-wrap items-end gap-3 pt-1">
                    <Field label={`${t("Compare")} ${interval} ${t("vs")}`}>
                        <Select
                            value={compareInterval}
                            onValueChange={setCompareInterval}
                        >
                            <SelectTrigger className="h-9 min-w-[150px] text-xs shadow-xs">
                                <SelectValue />
                            </SelectTrigger>
                            <SelectContent>
                                {["5m", "15m", "30m", "1h", "4h"]
                                    .filter((value) => value !== interval)
                                    .map((value) => (
                                        <SelectItem key={value} value={value}>
                                            {value}
                                        </SelectItem>
                                    ))}
                            </SelectContent>
                        </Select>
                    </Field>
                    <Button
                        type="button"
                        variant="outline"
                        onClick={() => void runComparison()}
                        disabled={compareLoading}
                        className="h-9 text-xs font-semibold shadow-xs"
                    >
                        {compareLoading ? "Comparing…" : "Compare Timeframes"}
                    </Button>
                    <Button
                        type="button"
                        variant="outline"
                        onClick={() => void runModeComparison()}
                        disabled={modeCompareLoading}
                        className="h-9 border-violet-500/30 text-xs font-semibold text-violet-600 shadow-xs dark:text-violet-300"
                    >
                        {modeCompareLoading
                            ? "Comparing modes…"
                            : "Compare Signal Modes"}
                    </Button>
                    <Button
                        type="button"
                        onClick={() => void run()}
                        disabled={loading}
                        className="h-9 text-xs font-semibold shadow-xs"
                    >
                        {loading
                            ? "Replaying engine…"
                            : "Run Historical Replay"}
                    </Button>
                </div>

                {error && (
                    <div className="rounded-xl border border-destructive/30 bg-destructive/10 p-3.5 text-xs text-destructive font-medium shadow-xs">
                        {error}
                    </div>
                )}

                {modeComparison && (
                    <div className="rounded-xl border border-violet-500/20 bg-violet-500/5 p-4 shadow-xs space-y-3">
                        <div className="flex flex-wrap items-start justify-between gap-2">
                            <div>
                                <div className="text-xs font-semibold text-foreground">
                                    Strict vs Balanced vs Flexible
                                </div>
                                <p className="mt-1 text-[10px] text-muted-foreground">
                                    Ketiga mode dihitung independen dengan
                                    aturan market, BTC context, biaya, slippage,
                                    dan risk guard masing-masing.
                                </p>
                            </div>
                            <Badge variant="outline" className="text-[10px]">
                                {modeComparison.symbol} ·{" "}
                                {modeComparison.market} ·{" "}
                                {modeComparison.interval}
                            </Badge>
                        </div>
                        <div className="grid gap-3 lg:grid-cols-3">
                            {(
                                [
                                    "strict",
                                    "balanced",
                                    "flexible",
                                ] as SignalMode[]
                            ).map((mode) => {
                                const item = modeComparison.modes[mode];
                                return (
                                    <div
                                        key={mode}
                                        className="rounded-lg border border-border/70 bg-background/50 p-3"
                                    >
                                        <div className="flex items-center justify-between gap-2">
                                            <span className="text-xs font-semibold capitalize">
                                                {mode}
                                            </span>
                                            <Badge
                                                variant="outline"
                                                className="text-[9px]"
                                            >
                                                {item.signal_mode ?? mode}
                                            </Badge>
                                        </div>
                                        <div className="mt-3 grid grid-cols-2 gap-2 text-[11px]">
                                            <Metric
                                                label="Signals"
                                                value={String(
                                                    item.summary.signals,
                                                )}
                                            />
                                            <Metric
                                                label="Win rate"
                                                value={`${n(item.summary.win_rate, 1)}%`}
                                            />
                                            <Metric
                                                label="Total R"
                                                value={`${n(item.summary.total_r)}R`}
                                            />
                                            <Metric
                                                label="Max DD"
                                                value={`${n(item.summary.max_drawdown_r)}R`}
                                            />
                                            <Metric
                                                label="Fees"
                                                value={
                                                    item.summary.fees == null
                                                        ? "—"
                                                        : item.summary.fees.toFixed(
                                                              4,
                                                          )
                                                }
                                            />
                                            {modeComparison.market ===
                                                "futures" && (
                                                <Metric
                                                    label="Funding"
                                                    value={
                                                        item.summary
                                                            .funding_fee == null
                                                            ? "—"
                                                            : item.summary.funding_fee.toFixed(
                                                                  4,
                                                              )
                                                    }
                                                />
                                            )}
                                        </div>
                                    </div>
                                );
                            })}
                        </div>
                        <div className="text-[10px] text-muted-foreground">
                            Ketiga mode direplay independen tanpa memakai active
                            calibration pada window evaluasi. Candle masa depan
                            tidak dipakai untuk membentuk signal, dan hasil
                            tidak menjamin performa masa depan.
                        </div>
                    </div>
                )}

                {comparison && (
                    <div className="rounded-xl border border-border bg-background/40 p-4 shadow-xs space-y-3">
                        <div className="flex flex-wrap items-start justify-between gap-2">
                            <div>
                                <div className="text-xs font-semibold text-foreground">
                                    Backtest Comparison
                                </div>
                                <p className="mt-1 text-[10px] text-muted-foreground">
                                    Kedua konfigurasi memakai engine replay yang
                                    sama, periode candle, biaya, slippage, arah,
                                    dan aturan ambiguity yang sama.
                                </p>
                            </div>
                            <Badge variant="outline" className="text-[10px]">
                                {comparison.symbol} · {comparison.market}
                            </Badge>
                        </div>
                        <div className="grid gap-3 lg:grid-cols-2">
                            <ComparisonCard
                                label={comparison.comparison.a.interval}
                                result={comparison.comparison.a}
                            />
                            <ComparisonCard
                                label={comparison.comparison.b.interval}
                                result={comparison.comparison.b}
                            />
                        </div>
                        <div className="overflow-x-auto rounded-xl border border-border shadow-xs">
                            <table className="w-full min-w-[680px] text-xs">
                                <thead className="bg-muted/40 text-left text-muted-foreground">
                                    <tr>
                                        <th className="p-2.5">Metric</th>
                                        <th className="p-2.5">
                                            {comparison.comparison.a.interval}
                                        </th>
                                        <th className="p-2.5">
                                            {comparison.comparison.b.interval}
                                        </th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {[
                                        [
                                            "Signals",
                                            comparison.comparison.a.summary
                                                .signals,
                                            comparison.comparison.b.summary
                                                .signals,
                                        ],
                                        [
                                            "Win rate",
                                            `${n(comparison.comparison.a.summary.win_rate, 1)}%`,
                                            `${n(comparison.comparison.b.summary.win_rate, 1)}%`,
                                        ],
                                        [
                                            "Total R",
                                            `${n(comparison.comparison.a.summary.total_r)}R`,
                                            `${n(comparison.comparison.b.summary.total_r)}R`,
                                        ],
                                        [
                                            "Average R",
                                            `${n(comparison.comparison.a.summary.average_r)}R`,
                                            `${n(comparison.comparison.b.summary.average_r)}R`,
                                        ],
                                        [
                                            "Max DD",
                                            `${n(comparison.comparison.a.summary.max_drawdown_r)}R`,
                                            `${n(comparison.comparison.b.summary.max_drawdown_r)}R`,
                                        ],
                                    ].map(([metric, a, b]) => (
                                        <tr
                                            key={String(metric)}
                                            className="border-b border-border/60 last:border-0 hover:bg-muted/20"
                                        >
                                            <td className="p-2.5 font-medium text-foreground">
                                                {metric}
                                            </td>
                                            <td className="p-2.5">{a}</td>
                                            <td className="p-2.5">{b}</td>
                                        </tr>
                                    ))}
                                </tbody>
                            </table>
                        </div>
                    </div>
                )}

                {result && (
                    <div className="space-y-4 pt-2">
                        <div className="flex flex-wrap items-center justify-between gap-3 rounded-xl border border-border bg-background p-4 shadow-xs">
                            <div>
                                <div className="text-xs font-semibold text-foreground">
                                    Simpan hasil replay
                                </div>
                                <div className="mt-1 text-[10px] text-muted-foreground">
                                    Simpan konfigurasi, trade, equity curve,
                                    drawdown, quality matrix, dan comparison.
                                </div>
                            </div>
                            <Button
                                type="button"
                                variant="outline"
                                size="sm"
                                onClick={() => void saveReport()}
                                disabled={savingReport}
                                className="h-9 text-xs font-semibold shadow-xs"
                            >
                                <Save className="mr-2 size-4" />
                                {savingReport
                                    ? "Menyimpan…"
                                    : "Save Backtest Report"}
                            </Button>
                        </div>

                        <div className="grid grid-cols-2 gap-2 sm:grid-cols-4 lg:grid-cols-7">
                            <Metric
                                label="Signals"
                                value={String(result.summary.signals)}
                            />
                            <Metric
                                label="Wins"
                                value={String(result.summary.wins)}
                            />
                            <Metric
                                label="Losses"
                                value={String(result.summary.losses)}
                            />
                            <Metric
                                label="Win Rate"
                                value={`${n(result.summary.win_rate, 1)}%`}
                            />
                            <Metric
                                label="Total R"
                                value={`${n(result.summary.total_r)}R`}
                            />
                            <Metric
                                label="Average R"
                                value={`${n(result.summary.average_r)}R`}
                            />
                            <Metric
                                label="Max DD"
                                value={`${n(result.summary.max_drawdown_r)}R`}
                            />
                        </div>

                        <div className="rounded-xl border border-border bg-background p-3.5 text-xs text-muted-foreground shadow-xs">
                            <div className="font-semibold text-foreground">
                                Replay rules
                            </div>
                            <div className="mt-1">
                                Signal: closed candle · Entry: next candle open
                                · Confirmation: data available at signal time
                                only · Ambiguous candle:{" "}
                                {result.rules.same_candle_sl_tp}.
                            </div>
                        </div>

                        <div className="grid gap-3 lg:grid-cols-2">
                            <div className="rounded-xl border border-border bg-background p-4 shadow-xs">
                                <div className="text-xs font-semibold text-foreground">
                                    Cumulative R
                                </div>
                                <div className="mt-3 flex h-32 items-end gap-1 overflow-hidden">
                                    {result.equity_curve.length === 0 ? (
                                        <div className="text-xs text-muted-foreground">
                                            Belum ada trade.
                                        </div>
                                    ) : (
                                        result.equity_curve
                                            .slice(-40)
                                            .map((point) => {
                                                const values =
                                                    result.equity_curve
                                                        .slice(-40)
                                                        .map((p) =>
                                                            Math.abs(
                                                                p.cumulative_r,
                                                            ),
                                                        );
                                                const max = Math.max(
                                                    1,
                                                    ...values,
                                                );
                                                const height = Math.max(
                                                    4,
                                                    Math.min(
                                                        100,
                                                        (Math.abs(
                                                            point.cumulative_r,
                                                        ) /
                                                            max) *
                                                            100,
                                                    ),
                                                );
                                                return (
                                                    <div
                                                        key={point.index}
                                                        title={`${new Date(point.time * 1000).toLocaleString()} · ${n(point.cumulative_r)}R`}
                                                        className="flex-1 rounded-t bg-violet-500/70"
                                                        style={{
                                                            height: `${height}%`,
                                                        }}
                                                    />
                                                );
                                            })
                                    )}
                                </div>
                                <div className="mt-2 flex justify-between text-[10px] text-muted-foreground">
                                    <span>
                                        Trade{" "}
                                        {Math.max(
                                            1,
                                            result.equity_curve.length - 39,
                                        )}
                                    </span>
                                    <span>
                                        {n(
                                            result.equity_curve.at(-1)
                                                ?.cumulative_r ?? 0,
                                        )}
                                        R
                                    </span>
                                </div>
                            </div>
                            <div className="rounded-xl border border-border bg-background p-4 shadow-xs">
                                <div className="text-xs font-semibold text-foreground">
                                    Drawdown
                                </div>
                                <div className="mt-3 flex h-32 items-end gap-1 overflow-hidden">
                                    {result.equity_curve.length === 0 ? (
                                        <div className="text-xs text-muted-foreground">
                                            Belum ada trade.
                                        </div>
                                    ) : (
                                        result.equity_curve
                                            .slice(-40)
                                            .map((point) => {
                                                const max = Math.max(
                                                    1,
                                                    ...result.equity_curve
                                                        .slice(-40)
                                                        .map(
                                                            (p) => p.drawdown_r,
                                                        ),
                                                );
                                                const height = Math.max(
                                                    2,
                                                    Math.min(
                                                        100,
                                                        (point.drawdown_r /
                                                            max) *
                                                            100,
                                                    ),
                                                );
                                                return (
                                                    <div
                                                        key={point.index}
                                                        title={`${new Date(point.time * 1000).toLocaleString()} · DD ${n(point.drawdown_r)}R`}
                                                        className="flex-1 rounded-t bg-red-500/50"
                                                        style={{
                                                            height: `${height}%`,
                                                        }}
                                                    />
                                                );
                                            })
                                    )}
                                </div>
                                <div className="mt-2 flex justify-between text-[10px] text-muted-foreground">
                                    <span>Peak-to-trough</span>
                                    <span>
                                        {n(result.summary.max_drawdown_r)}R max
                                    </span>
                                </div>
                            </div>
                        </div>

                        <div className="rounded-xl border border-border bg-background p-4 shadow-xs space-y-2">
                            <div className="text-xs font-semibold text-foreground">
                                Signal Quality Matrix
                            </div>
                            <p className="text-[10px] text-muted-foreground">
                                Confidence × confirmation alignment dari signal
                                yang benar-benar direplay.
                            </p>
                            <div className="overflow-x-auto rounded-xl border border-border shadow-xs">
                                <table className="w-full min-w-[700px] text-xs">
                                    <thead className="bg-muted/40 text-left text-muted-foreground">
                                        <tr>
                                            <th className="p-2.5">
                                                Confidence
                                            </th>
                                            <th className="p-2.5">Alignment</th>
                                            <th className="p-2.5">Signals</th>
                                            <th className="p-2.5">W / L</th>
                                            <th className="p-2.5">Win rate</th>
                                            <th className="p-2.5">Avg R</th>
                                            <th className="p-2.5">Total R</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        {result.quality_matrix.length === 0 ? (
                                            <tr>
                                                <td
                                                    colSpan={7}
                                                    className="p-4 text-center text-muted-foreground"
                                                >
                                                    Belum ada data quality
                                                    matrix.
                                                </td>
                                            </tr>
                                        ) : (
                                            result.quality_matrix.map(
                                                (cell, i) => (
                                                    <tr
                                                        key={`${cell.confidence_bucket}-${cell.alignment_bucket}-${i}`}
                                                        className="border-b border-border/60 last:border-0 hover:bg-muted/20"
                                                    >
                                                        <td className="p-2.5 font-medium text-foreground">
                                                            {
                                                                cell.confidence_bucket
                                                            }
                                                        </td>
                                                        <td className="p-2.5">
                                                            {
                                                                cell.alignment_bucket
                                                            }
                                                        </td>
                                                        <td className="p-2.5">
                                                            {cell.signals}
                                                        </td>
                                                        <td className="p-2.5">
                                                            {cell.wins} /{" "}
                                                            {cell.losses}
                                                        </td>
                                                        <td className="p-2.5">
                                                            {n(
                                                                cell.win_rate,
                                                                1,
                                                            )}
                                                            %
                                                        </td>
                                                        <td className="p-2.5 font-semibold">
                                                            {n(cell.average_r)}R
                                                        </td>
                                                        <td className="p-2.5 font-semibold">
                                                            {n(cell.total_r)}R
                                                        </td>
                                                    </tr>
                                                ),
                                            )
                                        )}
                                    </tbody>
                                </table>
                            </div>
                        </div>

                        <div className="overflow-x-auto rounded-xl border border-border shadow-xs">
                            <table className="w-full min-w-[760px] text-xs">
                                <thead className="bg-muted/40 text-left text-muted-foreground">
                                    <tr>
                                        <th className="p-2.5">Signal</th>
                                        <th className="p-2.5">Dir</th>
                                        <th className="p-2.5">Confidence</th>
                                        <th className="p-2.5">Entry</th>
                                        <th className="p-2.5">SL</th>
                                        <th className="p-2.5">TP</th>
                                        <th className="p-2.5">Result</th>
                                        <th className="p-2.5">R</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {result.trades
                                        .slice(-20)
                                        .reverse()
                                        .map((trade, i) => (
                                            <tr
                                                key={`${trade.signal_time}-${i}`}
                                                className="border-b border-border/60 last:border-0 hover:bg-muted/20"
                                            >
                                                <td className="p-2.5">
                                                    {new Date(
                                                        trade.signal_time *
                                                            1000,
                                                    ).toLocaleString()}
                                                </td>
                                                <td className="p-2.5 font-semibold">
                                                    {trade.direction.toUpperCase()}
                                                </td>
                                                <td className="p-2.5">
                                                    {trade.confidence}%
                                                </td>
                                                <td className="p-2.5">
                                                    {trade.entry}
                                                </td>
                                                <td className="p-2.5">
                                                    {trade.sl}
                                                </td>
                                                <td className="p-2.5">
                                                    {trade.tp}
                                                </td>
                                                <td className="p-2.5">
                                                    {trade.reason.replaceAll(
                                                        "_",
                                                        " ",
                                                    )}
                                                </td>
                                                <td className="p-2.5 font-semibold">
                                                    {trade.r_multiple == null
                                                        ? "—"
                                                        : `${n(trade.r_multiple)}R`}
                                                </td>
                                            </tr>
                                        ))}
                                </tbody>
                            </table>
                        </div>
                    </div>
                )}
            </CardContent>
        </Card>
    );
}

function ComparisonCard({ label, result }: { label: string; result: Result }) {
    return (
        <div className="rounded-xl border border-border bg-background p-3.5 shadow-xs">
            <div className="text-xs font-semibold text-foreground">{label}</div>
            <div className="mt-2 grid grid-cols-2 gap-2 sm:grid-cols-4">
                <Metric
                    label="Signals"
                    value={String(result.summary.signals)}
                />
                <Metric
                    label="Win rate"
                    value={`${n(result.summary.win_rate, 1)}%`}
                />
                <Metric
                    label="Total R"
                    value={`${n(result.summary.total_r)}R`}
                />
                <Metric
                    label="Max DD"
                    value={`${n(result.summary.max_drawdown_r)}R`}
                />
            </div>
        </div>
    );
}

function Field({ label, children }: { label: string; children: ReactNode }) {
    return (
        <label className="space-y-1 block">
            <span className="text-[10px] font-semibold uppercase tracking-[.12em] text-muted-foreground block">
                {label}
            </span>
            {children}
        </label>
    );
}

function Metric({ label, value }: { label: string; value: string }) {
    return (
        <div className="rounded-xl border border-border bg-background p-3 shadow-xs">
            <div className="text-[10px] font-semibold uppercase tracking-[.12em] text-muted-foreground">
                {label}
            </div>
            <div className="mt-1 text-sm font-bold text-foreground">
                {value}
            </div>
        </div>
    );
}
