import { useEffect, useMemo, useRef, useState } from "react";
import {
    RefreshCw,
    Target,
    TrendingDown,
    TrendingUp,
    ShieldAlert,
    Zap,
    Sparkles,
    Layers3,
} from "lucide-react";
import type { MarketType } from "@/lib/market";
import { useI18n } from "@/lib/i18n";
import {
    getSignalDisplayLabel,
    getSignalDisplayState,
    isExecutableSignal,
} from "@/lib/SignalSnapshot";

import type {
    SignalMode,
    SignalSetup as SignalSetupType,
} from "@/types/insight";
export type { SignalSetup } from "@/types/insight";

import { Card, CardContent, CardHeader } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import {
    Accordion,
    AccordionContent,
    AccordionItem,
    AccordionTrigger,
} from "@/components/ui/accordion";

interface Props {
    symbol: string;
    market: MarketType;
    interval: string;
    provider?: string;
    enabled: boolean;
    requestGeneration: number;
    signalDataIntegrity?: boolean;
    onSignal?: (
        signal: SignalSetupType | null,
        meta: {
            requestId: number;
            symbol: string;
            market: MarketType;
            interval: string;
            provider: string;
            signalMode: SignalMode;
            requestGeneration: number;
        },
    ) => void;
    signalMode: SignalMode;
    onLoadingChange?: (
        loading: boolean,
        meta: {
            requestId: number;
            provider: string;
            signalMode: SignalMode;
            requestGeneration: number;
        },
    ) => void;
    onStatusChange?: (
        status: SignalStatus,
        meta: {
            requestId: number;
            provider: string;
            signalMode: SignalMode;
            requestGeneration: number;
        },
    ) => void;
    onRequestIdChange?: (requestId: number) => void;
}

type SignalStatus = "idle" | "loading" | "success" | "empty" | "error";

type ApiResponse = {
    setup?: SignalSetupType;
    message?: string;
};

export default function SignalEngine({
    symbol,
    market,
    interval,
    provider = "binance",
    enabled,
    requestGeneration,
    signalDataIntegrity = false,
    onSignal,
    signalMode,
    onLoadingChange,
    onStatusChange,
    onRequestIdChange,
}: Props) {
    const { t } = useI18n();
    const [storedSignal, setStoredSignal] = useState<SignalSetupType | null>(
        null,
    );
    const [storedSignalContext, setStoredSignalContext] = useState<
        string | null
    >(null);
    const signalContextKey = [
        symbol,
        market,
        interval,
        provider,
        signalMode,
        requestGeneration,
    ].join("|");
    // Do not leak a last-known signal into a newly selected symbol/market/context.
    // Same-context refresh failures may retain it, visibly marked as stale.
    const signal =
        storedSignalContext === signalContextKey ? storedSignal : null;
    const [loading, setLoading] = useState(false);
    const [whyOpen, setWhyOpen] = useState(false);
    const [error, setError] = useState<string | null>(null);
    const requestIdRef = useRef(0);

    const publishStatus = (status: SignalStatus, requestId: number) => {
        onStatusChange?.(status, {
            requestId,
            provider,
            signalMode,
            requestGeneration,
        });
    };

    const calculate = async (signalRequest?: AbortSignal) => {
        const requestId = ++requestIdRef.current;
        onRequestIdChange?.(requestId);
        if (!enabled) {
            setLoading(false);
            onLoadingChange?.(false, {
                requestId,
                provider,
                signalMode,
                requestGeneration,
            });
            publishStatus("idle", requestId);
            setStoredSignal(null);
            setStoredSignalContext(signalContextKey);
            onSignal?.(null, {
                requestId,
                symbol,
                market,
                interval,
                provider,
                signalMode,
                requestGeneration,
            });
            return;
        }

        setLoading(true);
        onLoadingChange?.(true, {
            requestId,
            provider,
            signalMode,
            requestGeneration,
        });
        publishStatus("loading", requestId);
        setError(null);

        try {
            const query = new URLSearchParams({
                symbol,
                market,
                interval,
                signal_mode: signalMode,
                provider,
                include_backtest: "0",
            });

            const response = await fetch(
                `/market/signals?${query.toString()}`,
                {
                    headers: { Accept: "application/json" },
                    credentials: "same-origin",
                    cache: "no-store",
                    signal: signalRequest,
                },
            );

            const raw = (await response
                .json()
                .catch(() => ({}))) as ApiResponse & { message?: string };

            if (!response.ok) {
                throw new Error(
                    raw.message ||
                        t(
                            "Signal request failed: :status",
                            "Signal request failed: :status",
                            { status: response.status },
                        ),
                );
            }

            if (requestId !== requestIdRef.current) return;

            const next = raw.setup ?? null;
            setStoredSignal(next);
            setStoredSignalContext(signalContextKey);
            onSignal?.(next, {
                requestId,
                symbol,
                market,
                interval,
                provider,
                signalMode,
                requestGeneration,
            });
            publishStatus(next ? "success" : "empty", requestId);
        } catch (caught) {
            if (
                caught instanceof DOMException &&
                caught.name === "AbortError"
            ) {
                return;
            }

            const message =
                caught instanceof Error
                    ? caught.message
                    : t("signal.error", "Signal unavailable");
            if (requestId !== requestIdRef.current) return;

            setError(message);
            // Keep the last known signal visible. The parent/card can mark it stale
            // while the user retries, instead of replacing useful data with a blank state.
            publishStatus("error", requestId);
        } finally {
            if (requestId === requestIdRef.current) {
                setLoading(false);
                onLoadingChange?.(false, {
                    requestId,
                    provider,
                    signalMode,
                    requestGeneration,
                });
            }
        }
    };

    useEffect(() => {
        const controller = new AbortController();
        void calculate(controller.signal).catch((caught) => {
            if (
                caught instanceof DOMException &&
                caught.name === "AbortError"
            ) {
                return;
            }
        });

        return () => controller.abort();
    }, [
        symbol,
        market,
        interval,
        provider,
        enabled,
        signalMode,
        requestGeneration,
    ]);

    const isSpot = market === "spot";

    // Use the same canonical state as the workspace header and Coin Insight.
    // Data that has not passed the parent context/snapshot check is not current.
    const signalDisplayState = signalDataIntegrity
        ? getSignalDisplayState(signal, market)
        : "neutral";
    const hasExecutablePlan = Boolean(
        !error &&
        signalDataIntegrity &&
        isExecutableSignal(signal) &&
        (signalDisplayState === "buy" ||
            signalDisplayState === "sell" ||
            signalDisplayState === "long" ||
            signalDisplayState === "short"),
    );
    const isLong =
        signalDisplayState === "long" || signalDisplayState === "buy";
    const isShort =
        signalDisplayState === "short" || signalDisplayState === "sell";
    const isSpotCandidate =
        isSpot &&
        (signalDisplayState === "buy_candidate" ||
            signalDisplayState === "sell_candidate");

    const Icon = useMemo(
        () => (isLong ? TrendingUp : isShort ? TrendingDown : Target),
        [isLong, isShort],
    );
    const mtf = signal?.mtf;
    const mtfLayer = (
        label: string,
        items: NonNullable<typeof mtf>["bias"],
    ) => (
        <div className="rounded-lg border border-border/60 bg-muted/20 p-3">
            <div className="mb-2 flex items-center justify-between">
                <span className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground">
                    {label}
                </span>
                <span className="text-[10px] font-medium text-muted-foreground">
                    {items.length
                        ? items.map((item) => item.interval).join(" + ")
                        : "—"}
                </span>
            </div>
            {items.length ? (
                <div className="space-y-1.5">
                    {items.map((item) => (
                        <div
                            key={`${label}-${item.interval}`}
                            className="flex items-center justify-between text-xs"
                        >
                            <span>{item.interval}</span>
                            <span
                                className={
                                    item.direction === "long"
                                        ? "font-semibold text-emerald-500"
                                        : item.direction === "short"
                                          ? "font-semibold text-rose-500"
                                          : "text-muted-foreground"
                                }
                            >
                                {item.direction.toUpperCase()} ·{" "}
                                {item.score.toFixed(1)}
                            </span>
                        </div>
                    ))}
                </div>
            ) : (
                <span className="text-xs text-muted-foreground">
                    No higher timeframe available
                </span>
            )}
        </div>
    );

    const actionLabel = signalDataIntegrity
        ? getSignalDisplayLabel(signalDisplayState)
        : "Synchronizing signal";

    const candidateDirection =
        mtf?.entry.direction === "long" || mtf?.entry.direction === "short"
            ? mtf.entry.direction
            : mtf?.bias_direction === "long" || mtf?.bias_direction === "short"
              ? mtf.bias_direction
              : null;
    const visibleActionLabel =
        error && signal
            ? `${getSignalDisplayLabel(getSignalDisplayState(signal, market))} · STALE`
            : actionLabel;
    const candidateRequirements = signal?.policy?.gates?.length
        ? signal.policy.gates.map((gate) => ({
              ...gate,
              detail:
                  gate.key === "btc_context"
                      ? "BTC context adalah faktor soft; tidak menjadi hard blocker."
                      : undefined,
          }))
        : candidateDirection
          ? (signal?.requirements?.[candidateDirection] ?? [])
          : [];
    const unmetHardRequirements = candidateRequirements.filter(
        (item) => item.hard && !item.met,
    );
    const metRequirements = candidateRequirements.filter((item) => item.met);

    useEffect(() => {
        // A blocked/neutral result should explain itself without making the user
        // hunt for the reason. Confirmed setups keep the panel compact.
        if (signal?.direction === "neutral" && mtf && !mtf.hard_gate) {
            setWhyOpen(true);
        } else if (signal?.direction && signal.direction !== "neutral") {
            setWhyOpen(false);
        }
    }, [signal?.direction, mtf?.hard_gate]);

    const mtfPanel = mtf ? (
        <div className="mt-4 rounded-xl border border-border/60 bg-card/70 p-4">
            <div className="mb-3 flex items-center justify-between gap-3">
                <div className="flex items-center gap-2">
                    <Layers3 className="size-4 text-primary" />
                    <span className="text-xs font-semibold uppercase tracking-wider">
                        Multi-Timeframe
                    </span>
                </div>
                <Badge
                    variant={mtf.confirmed ? "default" : "secondary"}
                    className="text-[10px]"
                >
                    {mtf.status === "confirmed"
                        ? "CONFIRMED"
                        : mtf.status === "blocked_conflict"
                          ? "BLOCKED"
                          : mtf.status === "waiting_confirmation"
                            ? "WAITING"
                            : "NEUTRAL"}
                </Badge>
            </div>
            <div className="grid gap-2 sm:grid-cols-3">
                {mtfLayer("Bias", mtf.bias)}
                {mtfLayer("Setup", mtf.setup)}
                {mtfLayer("Entry timeframe", [
                    {
                        interval: mtf.entry.interval,
                        score: mtf.entry.score,
                        direction: mtf.entry.direction,
                        rating: mtf.entry.rating,
                        adx: null,
                        closed: mtf.entry.closed,
                    },
                ])}
            </div>
            <div className="mt-3 flex flex-wrap items-center gap-x-4 gap-y-1 text-[11px] text-muted-foreground">
                <span>
                    Directional alignment:{" "}
                    <strong className="text-foreground">
                        {mtf.alignment_pct == null
                            ? "—"
                            : `${mtf.alignment_pct.toFixed(0)}%`}
                    </strong>
                </span>
                <span>
                    Coverage:{" "}
                    <strong className="text-foreground">
                        {mtf.available}/{mtf.coverage_total}
                    </strong>
                </span>
                <span>
                    Gate:{" "}
                    <strong
                        className={
                            mtf.hard_gate ? "text-emerald-500" : "text-rose-500"
                        }
                    >
                        {mtf.hard_gate ? "PASS" : "BLOCK"}
                    </strong>
                </span>
                <span>Closed candles only</span>
            </div>
            {mtf.blocking_reasons.length > 0 && !mtf.hard_gate && (
                <div className="mt-2 rounded-lg bg-rose-500/5 px-3 py-2 text-[11px] text-rose-500">
                    {mtf.blocking_reasons.join(" ")}
                </div>
            )}
            {mtf.informational_reasons &&
                mtf.informational_reasons.length > 0 && (
                    <div className="mt-2 rounded-lg bg-amber-500/5 px-3 py-2 text-[11px] text-muted-foreground">
                        {mtf.informational_reasons.join(" ")}
                    </div>
                )}
        </div>
    ) : null;

    if (!enabled) return null;

    return (
        <Card
            className={`mt-0 flex h-auto flex-col rounded-2xl border bg-card p-0 shadow-xs transition-all duration-200 ${
                isLong
                    ? "border-emerald-500/30"
                    : isShort
                      ? "border-rose-500/30"
                      : "border-border"
            }`}
        >
            <CardHeader className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between border-b border-border/60 pb-4 p-5">
                <div className="flex items-center gap-3.5">
                    <div
                        className={`flex h-10 w-10 items-center justify-center rounded-xl border ${
                            isLong
                                ? "border-emerald-500/30 bg-emerald-500/10 text-emerald-500"
                                : isShort
                                  ? "border-rose-500/30 bg-rose-500/10 text-rose-500"
                                  : "border-primary/20 bg-primary/10 text-primary"
                        }`}
                    >
                        <Zap className="size-5" />
                    </div>
                    <div>
                        <div className="flex items-center gap-2">
                            <span className="text-[11px] font-semibold uppercase tracking-wider text-muted-foreground">
                                {t("signal.title", "Signal Engine")}
                            </span>
                        </div>
                        <div className="mt-0.5 text-base font-bold text-foreground flex items-center gap-2">
                            {loading ? (
                                <span className="text-muted-foreground font-normal text-xs flex items-center gap-2">
                                    <RefreshCw className="size-3.5 animate-spin text-primary" />
                                    {t("signal.analyzing", "Analyzing market…")}
                                </span>
                            ) : error ? (
                                <span className="text-destructive text-xs font-medium">
                                    {t("signal.error", "Signal unavailable")}
                                </span>
                            ) : (
                                <span
                                    className={
                                        isLong
                                            ? "text-emerald-500"
                                            : isShort
                                              ? "text-rose-500"
                                              : "text-foreground"
                                    }
                                >
                                    {actionLabel}
                                </span>
                            )}
                        </div>
                    </div>
                </div>

                <div className="flex flex-wrap items-center gap-2">
                    <span className="hidden text-[10px] font-semibold uppercase tracking-[0.14em] text-muted-foreground sm:inline">
                        {signalMode}
                    </span>
                    <Button
                        type="button"
                        variant="outline"
                        size="sm"
                        onClick={() => void calculate()}
                        disabled={loading}
                        className="h-9 gap-2 text-xs font-medium shadow-xs"
                    >
                        <RefreshCw
                            className={`size-3.5 ${loading ? "animate-spin" : ""}`}
                        />
                        {t("common.refresh", "Refresh")}
                    </Button>
                </div>
            </CardHeader>

            <CardContent className="flex-1 px-3.5 py-4 pb-9 sm:px-5 sm:pt-4 sm:pb-10">
                {error && (
                    <div className="rounded-xl border border-destructive/30 bg-destructive/10 p-3.5 text-xs text-destructive font-medium flex items-center gap-2 shadow-xs mb-4">
                        <ShieldAlert className="size-4 shrink-0" />
                        <span>{error}</span>
                    </div>
                )}

                {signal ? (
                    <div className="relative">
                        <div className="space-y-4 animate-in fade-in duration-200">
                            <div className="flex flex-wrap items-center justify-between gap-4 rounded-2xl border border-border/70 bg-muted/10 p-4">
                                <div className="flex min-w-0 items-center gap-3">
                                    <div
                                        className={`flex h-9 w-9 shrink-0 items-center justify-center rounded-xl border ${
                                            isLong
                                                ? "border-emerald-500/25 bg-emerald-500/10 text-emerald-500"
                                                : isShort
                                                  ? "border-rose-500/25 bg-rose-500/10 text-rose-500"
                                                  : "border-amber-500/25 bg-amber-500/10 text-amber-500"
                                        }`}
                                    >
                                        <Icon className="size-4" />
                                    </div>
                                    <div className="min-w-0">
                                        <div className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground">
                                            Current decision
                                        </div>
                                        <div
                                            className={`mt-0.5 truncate text-base font-bold ${isLong ? "text-emerald-500" : isShort ? "text-rose-500" : "text-foreground"}`}
                                        >
                                            {visibleActionLabel}
                                        </div>
                                        {isSpotCandidate && (
                                            <p className="mt-0.5 text-[10px] font-medium text-muted-foreground">
                                                Menunggu konfirmasi MTF sebelum
                                                menjadi trade plan.
                                            </p>
                                        )}
                                    </div>
                                </div>

                                <div className="flex items-center gap-2 rounded-xl border border-primary/15 bg-primary/5 px-3 py-2">
                                    <Sparkles className="size-3.5 text-primary" />
                                    <div>
                                        <div className="text-[9px] font-semibold uppercase tracking-wider text-muted-foreground">
                                            Confidence
                                        </div>
                                        <div className="font-mono text-sm font-bold text-foreground">
                                            {signal.confidence}%
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div className="flex flex-wrap items-center gap-2 text-xs">
                                <Badge
                                    variant="secondary"
                                    className="px-3 py-1.5 font-medium shadow-xs"
                                >
                                    {isSpot ? "Spot" : "Futures"} ·{" "}
                                    <span className="font-semibold text-primary ml-1">
                                        {signal.interval ?? interval}
                                    </span>
                                </Badge>
                                <Badge
                                    variant={
                                        signalMode === "strict"
                                            ? "default"
                                            : "outline"
                                    }
                                    className="px-3 py-1.5 font-semibold"
                                >
                                    {signalMode.toUpperCase()}
                                </Badge>
                                {signal.confirmation &&
                                    signal.confirmation.total > 0 && (
                                        <>
                                            <Badge
                                                variant="outline"
                                                className="px-3 py-1.5 font-medium text-muted-foreground shadow-xs"
                                            >
                                                {t(
                                                    "signal.confirmation",
                                                    "Konfirmasi",
                                                )}
                                                :{" "}
                                                <span className="text-foreground font-semibold ml-1">
                                                    {
                                                        signal.confirmation
                                                            .aligned
                                                    }
                                                    /{signal.confirmation.total}
                                                </span>
                                            </Badge>
                                            {signal.confirmation.frames.map(
                                                (frame, index) => (
                                                    <Badge
                                                        key={frame.interval}
                                                        variant="outline"
                                                        className="px-3 py-1.5 font-medium text-muted-foreground shadow-xs"
                                                    >
                                                        {index === 0
                                                            ? t(
                                                                  "signal.confirmation_short",
                                                                  "Confirm",
                                                              )
                                                            : t(
                                                                  "signal.trend_short",
                                                                  "Trend",
                                                              )}{" "}
                                                        {frame.interval}:{" "}
                                                        <strong className="text-foreground font-semibold ml-1">
                                                            {frame.rating
                                                                .replace(
                                                                    "strong_",
                                                                    "",
                                                                )
                                                                .toUpperCase()}
                                                        </strong>
                                                    </Badge>
                                                ),
                                            )}
                                        </>
                                    )}
                            </div>

                            {signal.lifecycle &&
                                signal.lifecycle.status !== "inactive" && (
                                    <div className="rounded-xl border border-border bg-muted/20 p-3 shadow-xs flex items-center justify-between">
                                        <div className="text-xs font-medium text-muted-foreground flex items-center gap-2">
                                            <ShieldAlert className="size-3.5 text-primary" />
                                            {t(
                                                "signal.invalidation",
                                                "Signal validity",
                                            )}
                                        </div>
                                        <Badge
                                            variant="outline"
                                            className="font-medium text-foreground"
                                        >
                                            {signal.lifecycle.status}
                                        </Badge>
                                    </div>
                                )}

                            <div className="grid gap-2 sm:grid-cols-3">
                                <DecisionMetric
                                    label="Confirmation"
                                    value={
                                        signal.confirmation?.total
                                            ? `${signal.confirmation.aligned}/${signal.confirmation.total}`
                                            : "—"
                                    }
                                    detail="Aligned timeframes"
                                />
                                <DecisionMetric
                                    label="Plan status"
                                    value={
                                        hasExecutablePlan ? "READY" : "WAITING"
                                    }
                                    detail={
                                        hasExecutablePlan
                                            ? "Signal context is executable"
                                            : "Waiting for all gates to align"
                                    }
                                    tone={
                                        hasExecutablePlan ? "success" : "muted"
                                    }
                                />
                                <DecisionMetric
                                    label="Signal validity"
                                    value={(
                                        signal.lifecycle?.status ?? "—"
                                    ).toUpperCase()}
                                    detail="Current lifecycle state"
                                />
                            </div>

                            {mtfPanel}
                            {signal.market_context &&
                                !signal.market_context.is_benchmark && (
                                    <div className="rounded-xl border border-primary/20 bg-primary/3 p-3.5 space-y-2">
                                        <div className="flex flex-wrap items-center justify-between gap-2">
                                            <div className="flex min-w-0 flex-wrap items-center gap-2">
                                                <span className="text-xs font-semibold text-foreground">
                                                    BTC-aware context
                                                </span>
                                                <span className="text-[10px] text-muted-foreground">
                                                    {signal.market_context.provider.toUpperCase()}{" "}
                                                    ·{" "}
                                                    {
                                                        signal.market_context
                                                            .interval
                                                    }
                                                </span>
                                            </div>
                                            <Badge
                                                variant={
                                                    signal.market_context
                                                        .signal_alignment
                                                        .status === "supportive"
                                                        ? "default"
                                                        : signal.market_context
                                                                .signal_alignment
                                                                .status ===
                                                            "headwind"
                                                          ? "destructive"
                                                          : "outline"
                                                }
                                            >
                                                {
                                                    signal.market_context
                                                        .signal_alignment.label
                                                }
                                            </Badge>
                                        </div>
                                        <div className="grid grid-cols-1 gap-2 sm:grid-cols-3">
                                            <ContextMetric
                                                label="BTC trend"
                                                value={
                                                    signal.market_context.btc
                                                        .available
                                                        ? signal.market_context
                                                              .btc.state
                                                        : "—"
                                                }
                                            />
                                            <ContextMetric
                                                label="BTC dominance"
                                                value={formatContextPct(
                                                    signal.market_context
                                                        .btc_dominance_pct,
                                                )}
                                            />
                                            <ContextMetric
                                                label="ALT/BTC · 20 candles"
                                                value={
                                                    signal.market_context
                                                        .relative_strength
                                                        .available
                                                        ? `${formatContextPct(signal.market_context.relative_strength.alt_btc_return_pct)} · ${signal.market_context.relative_strength.state}`
                                                        : "Tidak tersedia"
                                                }
                                            />
                                        </div>
                                        <p className="text-[11px] leading-5 text-muted-foreground">
                                            {
                                                signal.market_context
                                                    .signal_alignment.message
                                            }{" "}
                                            Dominasi BTC hanya konteks
                                            deskriptif; struktur altcoin dan
                                            konfirmasi MTF tetap menjadi dasar
                                            setup.
                                        </p>
                                    </div>
                                )}

                            <Accordion
                                type="single"
                                collapsible
                                value={whyOpen ? "why-this-signal" : ""}
                                onValueChange={(value) =>
                                    setWhyOpen(value === "why-this-signal")
                                }
                                className="overflow-hidden rounded-xl border border-border bg-background shadow-xs px-4"
                            >
                                <AccordionItem
                                    value="why-this-signal"
                                    className="border-0"
                                >
                                    <AccordionTrigger className="py-3 hover:no-underline">
                                        <div className="min-w-0 flex-1 text-left">
                                            <div className="flex flex-wrap items-center gap-2">
                                                <div className="text-xs font-semibold text-foreground">
                                                    Why this signal?
                                                </div>
                                                <Badge
                                                    variant={
                                                        hasExecutablePlan
                                                            ? "default"
                                                            : candidateDirection
                                                              ? "secondary"
                                                              : "outline"
                                                    }
                                                    className="px-1.5 py-0 text-[9px]"
                                                >
                                                    {hasExecutablePlan
                                                        ? "READY"
                                                        : candidateDirection
                                                          ? "CANDIDATE"
                                                          : "NO SETUP"}
                                                </Badge>
                                            </div>
                                            <div className="mt-0.5 text-[10px] font-normal text-muted-foreground">
                                                Faktor utama yang mendukung atau
                                                membatasi setup saat ini.
                                            </div>
                                        </div>
                                    </AccordionTrigger>

                                    <AccordionContent className="pb-4 pt-1">
                                        <div className="space-y-4">
                                            <div className="rounded-lg border border-border/70 bg-muted/20 p-3">
                                                <div className="flex flex-wrap items-center justify-between gap-2">
                                                    <div>
                                                        <div className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground">
                                                            Decision status
                                                        </div>
                                                        <div className="mt-1 text-sm font-semibold text-foreground">
                                                            {signal.direction ===
                                                            "neutral"
                                                                ? t(
                                                                      "No confirmed setup — :mode mode",
                                                                      "No confirmed setup — :mode mode",
                                                                      {
                                                                          mode:
                                                                              signal.signal_mode_label ??
                                                                              signalMode,
                                                                      },
                                                                  )
                                                                : `${signal.direction.toUpperCase()} setup confirmed`}
                                                        </div>
                                                    </div>
                                                    <Badge
                                                        variant={
                                                            mtf?.hard_gate
                                                                ? "default"
                                                                : "outline"
                                                        }
                                                    >
                                                        {mtf?.hard_gate
                                                            ? "GATE PASS"
                                                            : "GATE BLOCK"}
                                                    </Badge>
                                                </div>
                                                <p className="mt-2 text-xs leading-5 text-muted-foreground">
                                                    {candidateDirection
                                                        ? t(
                                                              "Candidate direction comes from the :interval entry timeframe. It is not a confirmed signal until every hard requirement for :direction is met.",
                                                              "Candidate direction comes from the :interval entry timeframe. It is not a confirmed signal until every hard requirement for :direction is met.",
                                                              {
                                                                  interval:
                                                                      mtf?.entry
                                                                          .interval ??
                                                                      interval,
                                                                  direction:
                                                                      candidateDirection.toUpperCase(),
                                                              },
                                                          )
                                                        : "No directional candidate is available from the current multi-timeframe context."}
                                                </p>
                                            </div>

                                            {signal.adaptive_score && (
                                                <div className="grid gap-2 sm:grid-cols-3">
                                                    <div className="rounded-lg border border-border/70 bg-muted/20 p-3">
                                                        <div className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground">
                                                            Base score
                                                        </div>
                                                        <div className="mt-1 text-sm font-semibold text-foreground">
                                                            {signal.adaptive_score.base_score.toFixed(
                                                                1,
                                                            )}
                                                        </div>
                                                    </div>
                                                    <div className="rounded-lg border border-border/70 bg-muted/20 p-3">
                                                        <div className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground">
                                                            BTC adjustment
                                                        </div>
                                                        <div className="mt-1 text-sm font-semibold text-foreground">
                                                            {signal
                                                                .adaptive_score
                                                                .adjustment > 0
                                                                ? "+"
                                                                : ""}
                                                            {signal.adaptive_score.adjustment.toFixed(
                                                                1,
                                                            )}
                                                        </div>
                                                    </div>
                                                    <div className="rounded-lg border border-border/70 bg-muted/20 p-3">
                                                        <div className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground">
                                                            Adaptive score
                                                        </div>
                                                        <div className="mt-1 text-sm font-semibold text-foreground">
                                                            {signal.adaptive_score.score.toFixed(
                                                                1,
                                                            )}
                                                        </div>
                                                    </div>
                                                </div>
                                            )}

                                            {signal.policy && (
                                                <div className="rounded-lg border border-border/70 bg-muted/10 p-3">
                                                    <div className="flex flex-wrap items-center justify-between gap-2">
                                                        <div>
                                                            <div className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground">
                                                                Policy decision
                                                            </div>
                                                            <div className="mt-1 text-xs font-semibold text-foreground">
                                                                {signal.policy
                                                                    .execution_allowed
                                                                    ? "Execution policy PASS"
                                                                    : "Execution policy BLOCKED"}
                                                            </div>
                                                        </div>
                                                        <Badge
                                                            variant={
                                                                signal.policy
                                                                    .execution_allowed
                                                                    ? "default"
                                                                    : "outline"
                                                            }
                                                        >
                                                            {signal.policy.market.toUpperCase()}{" "}
                                                            ·{" "}
                                                            {
                                                                signal.policy
                                                                    .label
                                                            }
                                                        </Badge>
                                                    </div>
                                                    {signal.policy.hard_failures
                                                        .length > 0 && (
                                                        <div className="mt-3 space-y-1.5">
                                                            {signal.policy.hard_failures
                                                                .slice(0, 4)
                                                                .map(
                                                                    (
                                                                        failure,
                                                                    ) => (
                                                                        <div
                                                                            key={
                                                                                failure
                                                                            }
                                                                            className="text-[11px] leading-4 text-rose-600 dark:text-rose-300"
                                                                        >
                                                                            •{" "}
                                                                            {
                                                                                failure
                                                                            }
                                                                        </div>
                                                                    ),
                                                                )}
                                                        </div>
                                                    )}
                                                    {signal.policy.hard_failures
                                                        .length === 0 &&
                                                        signal.policy.warnings
                                                            .length === 0 && (
                                                            <div className="mt-2 text-[11px] text-emerald-600 dark:text-emerald-300">
                                                                Semua hard gate
                                                                mode ini
                                                                terpenuhi pada
                                                                snapshot saat
                                                                ini.
                                                            </div>
                                                        )}
                                                </div>
                                            )}

                                            {candidateRequirements.length >
                                                0 && (
                                                <div className="space-y-2">
                                                    <div className="flex items-center justify-between gap-2">
                                                        <div className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground">
                                                            {candidateDirection?.toUpperCase() ??
                                                                "SIGNAL"}{" "}
                                                            requirements
                                                        </div>
                                                        <span className="text-[10px] text-muted-foreground">
                                                            {
                                                                metRequirements.length
                                                            }
                                                            /
                                                            {
                                                                candidateRequirements.length
                                                            }{" "}
                                                            met
                                                        </span>
                                                    </div>
                                                    <div className="grid gap-2 md:grid-cols-2">
                                                        {candidateRequirements
                                                            .slice(0, 8)
                                                            .map((item) => (
                                                                <div
                                                                    key={
                                                                        item.key
                                                                    }
                                                                    className={`rounded-lg border px-3 py-2.5 text-xs ${
                                                                        item.met
                                                                            ? "border-emerald-500/20 bg-emerald-500/5"
                                                                            : item.hard
                                                                              ? "border-rose-500/20 bg-rose-500/5"
                                                                              : "border-border/70 bg-muted/20"
                                                                    }`}
                                                                >
                                                                    <div className="flex items-start gap-2">
                                                                        <span
                                                                            className={`mt-0.5 shrink-0 font-bold ${item.met ? "text-emerald-500" : item.hard ? "text-rose-500" : "text-amber-500"}`}
                                                                        >
                                                                            {item.met
                                                                                ? "✓"
                                                                                : item.hard
                                                                                  ? "✕"
                                                                                  : "○"}
                                                                        </span>
                                                                        <div className="min-w-0 flex-1">
                                                                            <div className="flex items-center justify-between gap-2">
                                                                                <span className="font-medium text-foreground">
                                                                                    {
                                                                                        item.label
                                                                                    }
                                                                                </span>
                                                                                {item.hard && (
                                                                                    <span className="shrink-0 text-[9px] font-semibold uppercase text-muted-foreground">
                                                                                        wajib
                                                                                    </span>
                                                                                )}
                                                                            </div>
                                                                            <div className="mt-1 text-[10px] leading-4 text-muted-foreground">
                                                                                {
                                                                                    item.detail
                                                                                }
                                                                            </div>
                                                                            <div className="mt-1 text-[10px] text-muted-foreground">
                                                                                {item.value !=
                                                                                null
                                                                                    ? `aktual: ${String(item.value)} · `
                                                                                    : ""}
                                                                                target:{" "}
                                                                                {String(
                                                                                    item.target,
                                                                                )}
                                                                            </div>
                                                                        </div>
                                                                    </div>
                                                                </div>
                                                            ))}
                                                    </div>
                                                </div>
                                            )}

                                            {unmetHardRequirements.length ===
                                                0 &&
                                            mtf?.blocking_reasons?.length ? (
                                                <div className="rounded-lg border border-rose-500/20 bg-rose-500/5 px-3 py-2.5 text-xs text-rose-500">
                                                    {mtf.blocking_reasons.join(
                                                        " ",
                                                    )}
                                                </div>
                                            ) : null}

                                            {signal.reason?.length ? (
                                                <div className="space-y-2">
                                                    <div className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground">
                                                        Context
                                                    </div>
                                                    <div className="grid gap-2 md:grid-cols-2">
                                                        {signal.reason
                                                            .slice(0, 6)
                                                            .map(
                                                                (
                                                                    reason,
                                                                    index,
                                                                ) => (
                                                                    <div
                                                                        key={`${index}-${reason}`}
                                                                        className="rounded-lg border border-border/70 bg-muted/20 px-3 py-2 text-xs leading-5"
                                                                    >
                                                                        {reason}
                                                                    </div>
                                                                ),
                                                            )}
                                                    </div>
                                                </div>
                                            ) : null}

                                            {signal.confidence_breakdown && (
                                                <div className="grid gap-2 sm:grid-cols-3">
                                                    <ExplanationMetric
                                                        label="Primary score"
                                                        value={
                                                            signal
                                                                .confidence_breakdown
                                                                .primary_score
                                                        }
                                                    />
                                                    <ExplanationMetric
                                                        label="Primary strength"
                                                        value={
                                                            signal
                                                                .confidence_breakdown
                                                                .primary_strength
                                                        }
                                                    />
                                                    <ExplanationMetric
                                                        label="Confirmation alignment"
                                                        value={
                                                            signal
                                                                .confidence_breakdown
                                                                .confirmation_alignment
                                                        }
                                                    />
                                                </div>
                                            )}

                                            {signal.regime && (
                                                <div className="rounded-lg border border-border/70 bg-muted/20 p-3">
                                                    <div className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground">
                                                        Market context
                                                    </div>
                                                    <div className="mt-2 flex flex-wrap gap-2 text-xs">
                                                        <Badge variant="outline">
                                                            {t(
                                                                "Market regime",
                                                                "Market regime",
                                                            )}
                                                            :{" "}
                                                            {(() => {
                                                                const raw =
                                                                    signal.regime.label?.trim() ??
                                                                    "";
                                                                const normalized =
                                                                    raw
                                                                        .toLowerCase()
                                                                        .replace(
                                                                            /[\s/-]+/g,
                                                                            "_",
                                                                        );
                                                                const mapped: Record<
                                                                    string,
                                                                    string
                                                                > = {
                                                                    bullish_strong:
                                                                        "Strong bullish",
                                                                    bullish_weak:
                                                                        "Weak bullish",
                                                                    bearish_strong:
                                                                        "Strong bearish",
                                                                    bearish_weak:
                                                                        "Weak bearish",
                                                                    bullish:
                                                                        "Bullish",
                                                                    bearish:
                                                                        "Bearish",
                                                                    range: "Range / Mixed",
                                                                    mixed: "Mixed",
                                                                    high_volatility:
                                                                        "High volatility",
                                                                    low_volatility:
                                                                        "Low volatility",
                                                                    bullish_trend:
                                                                        "Bullish Trend",
                                                                    bearish_trend:
                                                                        "Bearish Trend",
                                                                };
                                                                const label =
                                                                    mapped[
                                                                        normalized
                                                                    ] ??
                                                                    raw.replaceAll(
                                                                        "_",
                                                                        " ",
                                                                    );
                                                                return t(
                                                                    label,
                                                                    label,
                                                                );
                                                            })()}
                                                        </Badge>
                                                        <Badge variant="outline">
                                                            {t(
                                                                "Trend",
                                                                "Trend",
                                                            )}
                                                            :{" "}
                                                            {t(
                                                                signal.regime
                                                                    .trend,
                                                                signal.regime
                                                                    .trend,
                                                            )}
                                                        </Badge>
                                                        <Badge variant="outline">
                                                            {t(
                                                                "Strength",
                                                                "Strength",
                                                            )}
                                                            :{" "}
                                                            {t(
                                                                signal.regime
                                                                    .strength,
                                                                signal.regime
                                                                    .strength,
                                                            )}
                                                        </Badge>
                                                        <Badge variant="outline">
                                                            {t(
                                                                "Volatility",
                                                                "Volatility",
                                                            )}
                                                            :{" "}
                                                            {t(
                                                                signal.regime
                                                                    .volatility,
                                                                signal.regime
                                                                    .volatility,
                                                            )}
                                                        </Badge>
                                                    </div>
                                                </div>
                                            )}

                                            {signal.confidence_breakdown
                                                ?.primary_indicators?.length ? (
                                                <div className="space-y-1.5">
                                                    <div className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground">
                                                        Primary indicators
                                                    </div>
                                                    <div className="grid gap-1.5 md:grid-cols-2">
                                                        {signal.confidence_breakdown.primary_indicators
                                                            .slice(0, 6)
                                                            .map((item) => (
                                                                <div
                                                                    key={
                                                                        item.name
                                                                    }
                                                                    className="flex items-start justify-between gap-3 rounded-lg border border-border/60 px-3 py-2 text-xs"
                                                                >
                                                                    <span className="min-w-0">
                                                                        {
                                                                            item.name
                                                                        }
                                                                    </span>
                                                                    <span className="shrink-0 text-muted-foreground">
                                                                        {item.vote >
                                                                        0
                                                                            ? "Bullish"
                                                                            : item.vote <
                                                                                0
                                                                              ? "Bearish"
                                                                              : "Neutral"}
                                                                    </span>
                                                                </div>
                                                            ))}
                                                    </div>
                                                </div>
                                            ) : null}
                                        </div>
                                    </AccordionContent>
                                </AccordionItem>
                            </Accordion>
                        </div>
                        {loading && (
                            <div
                                className="pointer-events-auto absolute inset-0 z-10 flex items-start justify-center rounded-2xl bg-background/55 px-4 pt-4 backdrop-blur-[1px]"
                                role="status"
                                aria-live="polite"
                                aria-label="Refreshing signal"
                            >
                                <div className="inline-flex items-center gap-2 rounded-full border border-border/70 bg-card/95 px-3 py-1.5 text-[10px] font-semibold text-muted-foreground shadow-sm">
                                    <RefreshCw
                                        className="size-3 animate-spin"
                                        aria-hidden="true"
                                    />
                                    Refreshing signal…
                                </div>
                            </div>
                        )}
                    </div>
                ) : loading ? (
                    <SignalEngineSkeleton />
                ) : (
                    <div className="rounded-2xl border border-dashed border-border bg-muted/10 p-4">
                        <div className="flex flex-wrap items-start justify-between gap-3">
                            <div className="min-w-0">
                                <div className="text-sm font-semibold text-foreground">
                                    No confirmed setup
                                </div>
                                <div className="mt-1 max-w-2xl text-xs leading-5 text-muted-foreground">
                                    Signal Engine belum menemukan setup yang
                                    memenuhi seluruh hard requirement pada mode{" "}
                                    {signalMode}.
                                </div>
                            </div>
                            <Badge variant="outline" className="shrink-0">
                                {candidateDirection
                                    ? `${candidateDirection.toUpperCase()} CANDIDATE`
                                    : "WAITING"}
                            </Badge>
                        </div>

                        <div className="mt-3 flex flex-wrap items-center gap-x-4 gap-y-1 text-[10px] text-muted-foreground">
                            {mtf?.entry?.interval && (
                                <span>
                                    Entry TF:{" "}
                                    <strong className="text-foreground">
                                        {mtf.entry.interval}
                                    </strong>
                                </span>
                            )}
                            <span>
                                Hard gates unmet:{" "}
                                <strong className="text-foreground">
                                    {unmetHardRequirements.length}
                                </strong>
                            </span>
                            <span>
                                Conditions met:{" "}
                                <strong className="text-foreground">
                                    {metRequirements.length}
                                </strong>
                            </span>
                        </div>
                    </div>
                )}
            </CardContent>
        </Card>
    );
}

function DecisionMetric({
    label,
    value,
    detail,
    tone = "default",
}: {
    label: string;
    value: string;
    detail: string;
    tone?: "default" | "success" | "muted";
}) {
    return (
        <div className="rounded-xl border border-border/70 bg-background px-3 py-2.5">
            <div className="text-[9px] font-semibold uppercase tracking-wider text-muted-foreground">
                {label}
            </div>
            <div
                className={`mt-0.5 font-mono text-sm font-bold ${
                    tone === "success" ? "text-emerald-500" : "text-foreground"
                }`}
            >
                {value}
            </div>
            <div className="mt-0.5 text-[9px] leading-3.5 text-muted-foreground">
                {detail}
            </div>
        </div>
    );
}

function ExplanationMetric({ label, value }: { label: string; value: number }) {
    return (
        <div className="rounded-lg border border-border/70 bg-muted/20 p-3">
            <div className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground">
                {label}
            </div>
            <div className="mt-1 font-mono text-sm font-bold">
                {value.toLocaleString(undefined, { maximumFractionDigits: 1 })}
            </div>
        </div>
    );
}

function SignalEngineSkeleton() {
    return (
        <div
            className="min-h-[220px] space-y-3 animate-pulse sm:min-h-[270px]"
            role="status"
            aria-label="Calculating signal"
            aria-busy="true"
        >
            <div className="grid gap-3 sm:grid-cols-3">
                {["confidence", "confirmation", "validity"].map((item) => (
                    <div
                        key={item}
                        className="rounded-xl border border-border/60 bg-background p-3"
                    >
                        <div className="h-2.5 w-20 rounded bg-muted" />
                        <div className="mt-2 h-5 w-24 rounded bg-muted" />
                    </div>
                ))}
            </div>
            <div className="rounded-xl border border-border/60 bg-muted/10 p-3">
                <div className="h-2.5 w-28 rounded bg-muted" />
                <div className="mt-3 grid gap-2 sm:grid-cols-3">
                    <div className="h-10 rounded-lg bg-muted" />
                    <div className="h-10 rounded-lg bg-muted" />
                    <div className="h-10 rounded-lg bg-muted" />
                </div>
            </div>
            <div className="h-20 rounded-xl border border-border/60 bg-muted/10" />
            <div className="text-[11px] text-muted-foreground">
                Calculating signal conditions…
            </div>
        </div>
    );
}

function formatContextPct(value: number | null | undefined): string {
    return value == null || !Number.isFinite(value)
        ? "—"
        : `${value >= 0 ? "+" : ""}${value.toFixed(2)}%`;
}

function ContextMetric({ label, value }: { label: string; value: string }) {
    return (
        <div className="min-w-0 rounded-lg border border-border/70 bg-background px-3 py-2">
            <div className="text-[9px] font-semibold uppercase tracking-wider text-muted-foreground">
                {label}
            </div>
            <div className="mt-1 wrap-break-word text-xs font-semibold capitalize text-foreground">
                {value}
            </div>
        </div>
    );
}
