import { Head } from "@inertiajs/react";
import {
    Activity,
    CheckCircle2,
    BrainCircuit,
    Gauge,
    RefreshCw,
    TrendingUp,
    TrendingDown,
    Layers,
    BarChart,
} from "lucide-react";
import { type ReactNode, useEffect, useMemo, useRef, useState } from "react";

import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from "@/components/ui/select";
import SearchableCoinSelect from "@/components/ui/searchable-coin-select";
import { Skeleton } from "@/components/ui/skeleton";
import { usePolledJson } from "@/hooks/use-polled-json";
import {
    formatCompact,
    formatPrice,
    formatPct,
    type MarketType,
} from "@/lib/market";
import { useI18n } from "@/lib/i18n";
import CustomerWorkspaceNav from "@/components/customer-workspace-nav";
import AnalysisPageHeader from "@/components/analysis-page-header";
import IntelligenceEvidenceStrip from "@/components/intelligence-evidence-strip";
import DataFreshness from "@/components/data-freshness";
import { DataState } from "@/components/data-state";

interface SymbolItem {
    symbol: string;
    name: string;
}

type ProviderOption = {
    id: number;
    name: string;
    slug: string;
    driver: string;
    markets: string[];
    capabilities: Record<string, boolean | string[]>;
};

type Flow = {
    available: boolean;
    derivative_period: string;
    error: string | null;
    derivatives: {
        funding: {
            rate_pct: number | null;
            next_funding_time: number | null;
        };
        open_interest: {
            contracts: number | null;
            change_pct: number | null;
            samples: number;
        };
        taker: {
            buy_pct: number | null;
            sell_pct: number | null;
            buy_sell_ratio: number | null;
            samples: number;
        };
        long_short: {
            account: {
                ratio: number | null;
                long_pct: number | null;
                short_pct: number | null;
            };
            top_trader_position: {
                ratio: number | null;
                long_pct: number | null;
                short_pct: number | null;
            };
        };
        liquidations: {
            long_value: number;
            short_value: number;
            total_value: number;
            events: number;
        };
    };
};

type Intelligence = {
    provider: string;
    market: MarketType;
    symbol: string;
    interval: string;
    updated_at: string;
    structure: {
        trend: string;
        structure_bias: string;
        bos: { direction: string; level: number; time: number } | null;
        choch: { direction: string; level: number; time: number } | null;
        protected_high: { price: number } | null;
        protected_low: { price: number } | null;
        last_swing_high: { price: number } | null;
        last_swing_low: { price: number } | null;
    };
    volume_profile: {
        poc: { price: number };
        vah: { low: number; high: number };
        val: { low: number; high: number };
        current: {
            price: number;
            position: string;
            distance_from_poc_percent: number;
        };
        value_area: {
            low: number;
            high: number;
            volume_share: number;
        };
        nodes: { hvn: unknown[]; lvn: unknown[] };
        profile: {
            used_candles: number;
            bins: number;
            value_area_percent: number;
        };
        data_quality: { source: string };
    };
    flow: Flow;
    phase_d: PhaseD;
    anomalies: {
        status: string;
        state: string;
        score: number;
        anomalies: Anomaly[];
        data_quality: {
            closed_candles: number;
            derivatives_available: boolean;
        };
    };
};

type Anomaly = {
    type: string;
    category: string;
    severity: "high" | "medium" | "low" | string;
    direction: string;
    value: number;
    baseline?: number;
    z_score?: number;
    ratio?: number;
};

type RotationCandidate = {
    symbol: string;
    last: number;
    change_pct: number;
    quote_volume: number;
    relative_strength_score?: number;
    liquidity_score?: number;
    current_score: number;
    theme: string | null;
};

type RotationRadarData = {
    status: "ok" | "no_signal" | string;
    provider: string;
    market: string;
    leader: {
        symbol: string;
        change_pct: number;
        last: number;
    };
    scope: "same_narrative" | "market_wide" | string;
    narrative: string | null;
    signal_strength?: "strong" | "weak" | string;
    candidates: RotationCandidate[];
    message: string | null;
    updated_at: string;
};

type ValidationHorizon = {
    hours: number;
    sample_events: number;
    follow_rate_pct: number | null;
    failure_rate_pct: number | null;
    average_follow_through_pct: number | null;
    median_follow_through_pct: number | null;
};

type ValidationCandidate = {
    symbol: string;
    status: "validated" | "insufficient_history" | string;
    validation_score: number | null;
    median_lag_hours: number | null;
    horizons: ValidationHorizon[];
};

type RotationValidationData = {
    status: "validated" | "insufficient_history" | string;
    provider: string;
    market: string;
    leader: string;
    trigger: {
        move_pct: number;
        timeframe: string;
        description: string;
    };
    sample_events: number;
    history_candles: number;
    minimum_events: number;
    horizons: number[];
    candidates: ValidationCandidate[];
    message: string | null;
    updated_at: string;
};

type PhaseD = {
    smart_money: {
        status: string;
        pressure: string;
        score: number | null;
        confidence: number;
        sample_trades: number;
        large_trade_count: number;
        threshold: number | null;
        buy_value: number;
        sell_value: number;
        net_value: number;
        buy_pct: number | null;
        sell_pct: number | null;
        largest_trade: {
            time: number;
            price: number;
            notional: number;
            side: string;
        } | null;
        order_book_confirmation: { bid_share_pct: number; bias: string } | null;
        method: string;
        message?: string;
    };
};

type Props = {
    providers: ProviderOption[];
    defaultProvider: string;
    defaultSymbol: string;
    defaultMarket: MarketType;
    defaultInterval: string;
};

const intervals = ["1m", "5m", "15m", "30m", "1h", "4h", "1d", "1w"];

function label(value: string): string {
    return value.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
}

function numberOrDash(value: number | null | undefined, digits = 2): string {
    return value == null || !Number.isFinite(value)
        ? "—"
        : value.toFixed(digits);
}

function compactOrDash(value: number | null | undefined, digits = 2): string {
    return value == null || !Number.isFinite(value)
        ? "—"
        : formatCompact(value, digits);
}

export default function MarketIntelligence({
    providers,
    defaultProvider,
    defaultSymbol,
    defaultMarket,
    defaultInterval,
}: Props) {
    const { t } = useI18n();
    const [provider, setProvider] = useState(defaultProvider);
    const [market, setMarket] = useState<MarketType>(defaultMarket);
    const [symbol, setSymbol] = useState(defaultSymbol);
    const [interval, setInterval] = useState(defaultInterval);
    const [availableSymbols, setAvailableSymbols] = useState<SymbolItem[]>([]);
    const [coinSearch, setCoinSearch] = useState("");
    const [coinOffset, setCoinOffset] = useState(0);
    const [coinHasMore, setCoinHasMore] = useState(false);
    const [coinLoading, setCoinLoading] = useState(false);
    const [coinError, setCoinError] = useState<string | null>(null);

    const selectedSymbol = useMemo(
        () =>
            availableSymbols.some((item) => item.symbol === symbol)
                ? symbol
                : symbol || defaultSymbol,
        [availableSymbols, symbol, defaultSymbol],
    );

    useEffect(() => {
        let cancelled = false;
        const timer = window.setTimeout(
            async () => {
                setCoinLoading(true);
                setCoinError(null);
                try {
                    const params = new URLSearchParams({
                        provider,
                        market,
                        limit: "25",
                        offset: "0",
                    });
                    if (coinSearch.trim())
                        params.set("search", coinSearch.trim());
                    const response = await fetch(
                        `/market-intelligence/catalog?${params}`,
                        {
                            headers: { Accept: "application/json" },
                            credentials: "same-origin",
                        },
                    );
                    const payload = (await response.json()) as {
                        items?: SymbolItem[];
                        has_more?: boolean;
                        next_offset?: number;
                    };
                    if (!response.ok || !Array.isArray(payload.items)) {
                        throw new Error("Market catalog could not be loaded.");
                    }
                    if (cancelled) return;
                    setAvailableSymbols(payload.items);
                    setCoinOffset(payload.next_offset ?? payload.items.length);
                    setCoinHasMore(Boolean(payload.has_more));
                    if (
                        payload.items.length > 0 &&
                        !payload.items.some((item) => item.symbol === symbol)
                    ) {
                        if (!coinSearch.trim())
                            setSymbol(payload.items[0].symbol);
                    }
                } catch (reason) {
                    if (!cancelled) {
                        setAvailableSymbols([]);
                        setCoinHasMore(false);
                        setCoinError(
                            reason instanceof Error
                                ? reason.message
                                : "Market catalog could not be loaded.",
                        );
                    }
                } finally {
                    if (!cancelled) setCoinLoading(false);
                }
            },
            coinSearch.trim() ? 250 : 0,
        );

        return () => {
            cancelled = true;
            window.clearTimeout(timer);
        };
    }, [provider, market, coinSearch]);

    const loadMoreCoins = async () => {
        if (coinLoading || !coinHasMore) return;
        setCoinLoading(true);
        try {
            const params = new URLSearchParams({
                provider,
                market,
                limit: "25",
                offset: String(coinOffset),
            });
            if (coinSearch.trim()) params.set("search", coinSearch.trim());
            const response = await fetch(
                `/market-intelligence/catalog?${params}`,
                {
                    headers: { Accept: "application/json" },
                    credentials: "same-origin",
                },
            );
            const payload = (await response.json()) as {
                items?: SymbolItem[];
                has_more?: boolean;
                next_offset?: number;
            };
            if (!response.ok || !Array.isArray(payload.items))
                throw new Error("Market catalog could not be loaded.");
            setAvailableSymbols((current) => [...current, ...payload.items!]);
            setCoinOffset(
                payload.next_offset ?? coinOffset + payload.items.length,
            );
            setCoinHasMore(Boolean(payload.has_more));
        } catch (reason) {
            setCoinError(
                reason instanceof Error
                    ? reason.message
                    : "Market catalog could not be loaded.",
            );
        } finally {
            setCoinLoading(false);
        }
    };

    const query = new URLSearchParams({
        provider,
        market,
        symbol: selectedSymbol,
        interval,
    }).toString();

    const { data, error, loading, updatedAt, refetch } =
        usePolledJson<Intelligence>(
            `/market-intelligence/data?${query}`,
            15_000,
            true,
        );
    const [manualRefreshing, setManualRefreshing] = useState(false);

    useEffect(() => {
        if (updatedAt !== null) {
            setManualRefreshing(false);
        }
    }, [updatedAt]);

    useEffect(() => {
        if (!manualRefreshing) return;

        const timeout = window.setTimeout(() => {
            setManualRefreshing(false);
        }, 10_000);

        return () => window.clearTimeout(timeout);
    }, [manualRefreshing]);

    const changeProvider = (next: string) => {
        setProvider(next);
        setCoinSearch("");
        setAvailableSymbols([]);
        setCoinOffset(0);
        setCoinHasMore(false);
    };

    const changeMarket = (next: MarketType) => {
        setMarket(next);
        setCoinSearch("");
        setAvailableSymbols([]);
        setCoinOffset(0);
        setCoinHasMore(false);
    };

    return (
        <>
            <Head title={t("Market Intelligence")} />
            <div className="product-page min-h-full min-w-0">
                <div className="mx-auto w-full min-w-0 max-w-[1600px] space-y-5">
                    <CustomerWorkspaceNav group="analysis" />

                    <AnalysisPageHeader
                        eyebrow={t("Market Intelligence")}
                        title={t(
                            "Understand what the market is doing · and why",
                        )}
                        description={t(
                            "Connect structure, value, participation, and anomalies into a clear research view before you dive into the individual modules.",
                        )}
                        icon={BrainCircuit}
                        actions={
                            <div className="grid w-full gap-3 sm:grid-cols-2 lg:grid-cols-4 xl:w-auto xl:min-w-180">
                                <Control label={t("Provider")}>
                                    <Select
                                        value={provider}
                                        onValueChange={changeProvider}
                                    >
                                        <SelectTrigger>
                                            <SelectValue />
                                        </SelectTrigger>
                                        <SelectContent>
                                            {providers.map((item) => (
                                                <SelectItem
                                                    key={item.slug}
                                                    value={item.slug}
                                                >
                                                    {item.name}
                                                </SelectItem>
                                            ))}
                                        </SelectContent>
                                    </Select>
                                </Control>
                                <Control label={t("Market")}>
                                    <Select
                                        value={market}
                                        onValueChange={(value) =>
                                            changeMarket(value as MarketType)
                                        }
                                    >
                                        <SelectTrigger>
                                            <SelectValue />
                                        </SelectTrigger>
                                        <SelectContent>
                                            <SelectItem value="spot">
                                                Spot
                                            </SelectItem>
                                            <SelectItem value="futures">
                                                Futures
                                            </SelectItem>
                                        </SelectContent>
                                    </Select>
                                </Control>
                                <Control label={t("Coin")}>
                                    <SearchableCoinSelect
                                        value={selectedSymbol}
                                        items={availableSymbols}
                                        search={coinSearch}
                                        onSearchChange={setCoinSearch}
                                        onValueChange={setSymbol}
                                        loading={coinLoading}
                                        hasMore={coinHasMore}
                                        onLoadMore={loadMoreCoins}
                                        error={coinError}
                                        placeholder={t("Select coin")}
                                    />
                                </Control>
                                <Control label={t("Timeframe")}>
                                    <div className="flex gap-2">
                                        <Select
                                            value={interval}
                                            onValueChange={setInterval}
                                        >
                                            <SelectTrigger>
                                                <SelectValue />
                                            </SelectTrigger>
                                            <SelectContent>
                                                {intervals.map((item) => (
                                                    <SelectItem
                                                        key={item}
                                                        value={item}
                                                    >
                                                        {item}
                                                    </SelectItem>
                                                ))}
                                            </SelectContent>
                                        </Select>
                                        <Button
                                            variant="outline"
                                            size="icon"
                                            onClick={() => {
                                                setManualRefreshing(true);
                                                refetch();
                                            }}
                                            disabled={
                                                loading || manualRefreshing
                                            }
                                            aria-label={t("Refresh")}
                                            title={t("Refresh")}
                                        >
                                            <RefreshCw
                                                className={`size-4 ${loading || manualRefreshing ? "animate-spin" : ""}`}
                                            />
                                        </Button>
                                    </div>
                                </Control>
                            </div>
                        }
                    />

                    <div className="flex flex-wrap items-center justify-between gap-2 text-[11px] text-muted-foreground">
                        <div className="flex flex-wrap items-center gap-2">
                            <Badge variant="outline">
                                {provider.toUpperCase()}
                            </Badge>
                            <Badge variant="outline">{market}</Badge>
                            <Badge variant="outline">{selectedSymbol}</Badge>
                            <span className="ml-1">
                                {t(
                                    "Refreshes every 15 seconds while the tab is active.",
                                )}
                            </span>
                        </div>
                        <DataFreshness
                            updatedAt={updatedAt}
                            loading={loading}
                            staleAfterMs={45_000}
                        />
                    </div>

                    {error && (
                        <DataState
                            kind="error"
                            title={t("Market data could not be refreshed.")}
                            description={error}
                            actionLabel={t("Retry")}
                            onAction={refetch}
                        />
                    )}

                    {loading && !data ? <PageSkeleton /> : null}

                    {data ? (
                        <>
                            <IntelligenceSummary data={data} />

                            <IntelligenceEvidenceStrip
                                structure={data.structure.structure_bias}
                                valueArea={data.volume_profile.current.position}
                                flow={
                                    data.market === "futures"
                                        ? data.flow.derivatives.taker.buy_pct ==
                                          null
                                            ? "neutral"
                                            : data.flow.derivatives.taker
                                                    .buy_pct > 50
                                              ? "bullish"
                                              : data.flow.derivatives.taker
                                                      .buy_pct < 50
                                                ? "bearish"
                                                : "neutral"
                                        : "neutral"
                                }
                                anomalies={data.anomalies.anomalies.length}
                                smartMoney={data.phase_d.smart_money.pressure}
                            />

                            <section>
                                <SectionHeading
                                    eyebrow={t("Market context")}
                                    title={t("Regime & price location")}
                                    description={t(
                                        "Start with the market state, then locate price inside the current value area.",
                                    )}
                                />
                                <div className="mt-3 grid gap-4 lg:grid-cols-[1.05fr_1fr]">
                                    <RegimeCard data={data} />
                                    <VolumeProfileCard data={data} />
                                </div>
                            </section>

                            <section>
                                <SectionHeading
                                    eyebrow={t("Confirmation")}
                                    title={t("Market flow")}
                                    description={t(
                                        "Use derivatives flow to confirm participation and identify conditions that can invalidate the current market thesis.",
                                    )}
                                />
                                <div className="mt-3">
                                    <FlowCard data={data} />
                                </div>
                            </section>

                            <section>
                                <SectionHeading
                                    eyebrow={t("Rotation research")}
                                    title={t("Rotation Radar")}
                                    description={t(
                                        "Research which assets may catch up after the selected leader. This is a ranked research signal, not a guaranteed prediction.",
                                    )}
                                />
                                <div className="mt-3">
                                    <RotationRadarCard
                                        provider={provider}
                                        market={market}
                                        symbol={selectedSymbol}
                                    />
                                </div>
                            </section>
                        </>
                    ) : null}
                </div>
            </div>
        </>
    );
}

function SectionHeading({
    eyebrow,
    title,
    description,
}: {
    eyebrow: string;
    title: string;
    description: string;
}) {
    return (
        <div className="flex flex-col gap-1 sm:flex-row sm:items-end sm:justify-between sm:gap-6">
            <div>
                <div className="text-[10px] font-bold uppercase tracking-[.18em] text-muted-foreground">
                    {eyebrow}
                </div>
                <h2 className="mt-1 text-base font-semibold tracking-tight text-foreground">
                    {title}
                </h2>
            </div>
            <p className="max-w-2xl text-xs leading-5 text-muted-foreground">
                {description}
            </p>
        </div>
    );
}

function IntelligenceSummary({ data }: { data: Intelligence }) {
    const { t } = useI18n();
    const bullish = data.structure.structure_bias === "long";
    const bearish = data.structure.structure_bias === "short";
    const neutral = !bullish && !bearish;
    const flow = data.flow.derivatives;
    const takerBuy = flow.taker.buy_pct;
    const smartPressure = data.phase_d.smart_money.pressure;
    const anomalyCount = data.anomalies.anomalies.length;
    const highAnomalies = data.anomalies.anomalies.filter(
        (item) => item.severity === "high",
    ).length;

    const confirmations = [
        bullish || bearish,
        data.volume_profile.current.position !== "unknown",
        data.market === "futures" && takerBuy != null
            ? bullish
                ? takerBuy > 50
                : bearish
                  ? takerBuy < 50
                  : true
            : true,
        data.market === "futures" && smartPressure !== "unavailable"
            ? bullish
                ? smartPressure === "accumulation"
                : bearish
                  ? smartPressure === "distribution"
                  : true
            : true,
    ];
    const confirmationCount = confirmations.filter(Boolean).length;
    const confidence =
        confirmationCount >= 3
            ? "High"
            : confirmationCount >= 2
              ? "Moderate"
              : "Early";

    const biasLabel = bullish
        ? t("Bullish")
        : bearish
          ? t("Bearish")
          : t("Neutral");
    const biasClass = bullish
        ? "ui-status-success"
        : bearish
          ? "ui-status-danger"
          : "ui-status-info";
    const biasSurface = bullish
        ? "ui-status-success-surface"
        : bearish
          ? "ui-status-danger-surface"
          : "ui-status-info-surface";

    const thesis = neutral
        ? t(
              "Structure is currently neutral. Treat flow, value-area location, and anomalies as context until a directional structure develops.",
          )
        : bullish
          ? t(
                "Structure is bullish. Continuation has stronger context when participation and smart-money pressure agree with the directional bias.",
            )
          : t(
                "Structure is bearish. Continuation has stronger context when selling pressure and smart-money distribution agree with the directional bias.",
            );

    const risks = [];
    if (highAnomalies > 0) {
        risks.push(
            `${highAnomalies} ${t("high-severity anomaly")}${highAnomalies > 1 ? "s" : ""}`,
        );
    } else if (anomalyCount > 0) {
        risks.push(
            `${anomalyCount} ${t("unusual condition")}${anomalyCount > 1 ? "s" : ""}`,
        );
    }
    if (data.market === "futures" && flow.funding.rate_pct != null) {
        risks.push(`${t("funding")} ${formatPct(flow.funding.rate_pct, 4)}`);
    }
    if (data.volume_profile.current.position) {
        risks.push(
            `${t("price")} ${label(data.volume_profile.current.position)} ${t("of POC")}`,
        );
    }

    return (
        <Card className="overflow-hidden border-border/70 bg-card shadow-sm">
            <CardContent className="p-5 sm:p-6">
                <div className="flex flex-col gap-5 lg:flex-row lg:items-stretch lg:justify-between">
                    <div className="min-w-0 flex-1">
                        <div className="flex flex-wrap items-center gap-2">
                            <Badge
                                variant="outline"
                                className="text-[10px] uppercase tracking-wide"
                            >
                                {t("Intelligence Summary")}
                            </Badge>
                            <Badge variant="secondary" className="text-[10px]">
                                {data.symbol} · {data.interval}
                            </Badge>
                        </div>
                        <div className="mt-3 flex flex-wrap items-end gap-x-4 gap-y-2">
                            <h2
                                className={`text-3xl font-black tracking-tight ${biasClass}`}
                            >
                                {biasLabel}
                            </h2>
                            <span className="pb-1 text-xs text-muted-foreground">
                                {confidence} {t("context confidence")}
                            </span>
                        </div>
                        <p className="mt-3 max-w-3xl text-sm leading-6 text-muted-foreground">
                            {thesis}
                        </p>
                    </div>

                    <div
                        className={`min-w-0 rounded-2xl border p-4 lg:w-80 ${biasSurface}`}
                    >
                        <div className="flex items-center gap-2 text-xs font-semibold text-foreground">
                            <Gauge className="size-4" />
                            {t("Intelligence read")}
                        </div>
                        <div className="mt-3 grid grid-cols-2 gap-x-4 gap-y-3 text-xs">
                            <SummarySignal
                                label={t("Structure")}
                                value={label(data.structure.structure_bias)}
                                positive={bullish}
                                negative={bearish}
                            />
                            <SummarySignal
                                label={t("Value area")}
                                value={label(
                                    data.volume_profile.current.position,
                                )}
                            />
                            <SummarySignal
                                label={t("Flow")}
                                value={
                                    data.market === "futures" &&
                                    takerBuy != null
                                        ? `${numberOrDash(takerBuy, 1)}% buy`
                                        : t("Spot context")
                                }
                                positive={
                                    data.market === "futures" &&
                                    takerBuy != null
                                        ? takerBuy > 50
                                        : undefined
                                }
                            />
                            <SummarySignal
                                label={t("Risk")}
                                value={
                                    highAnomalies > 0
                                        ? t("Elevated")
                                        : anomalyCount > 0
                                          ? t("Watch")
                                          : t("Normal")
                                }
                                negative={highAnomalies > 0}
                            />
                        </div>
                    </div>
                </div>

                <div className="mt-5 grid gap-3 border-t border-border/60 pt-4 md:grid-cols-2">
                    <div>
                        <div className="text-[10px] font-bold uppercase tracking-[.16em] text-muted-foreground">
                            {t("Confirmation")}
                        </div>
                        <div className="mt-2 flex flex-wrap gap-2">
                            {[
                                bullish || bearish
                                    ? t("Structure aligned")
                                    : t("Structure neutral"),
                                data.volume_profile.current.position !==
                                "unknown"
                                    ? t("Value location available")
                                    : t("Value location unavailable"),
                                data.market === "futures" && takerBuy != null
                                    ? takerBuy > 50
                                        ? t("Buy pressure")
                                        : t("Sell pressure")
                                    : t("Derivatives unavailable"),
                            ].map((item) => (
                                <span
                                    key={item}
                                    className="inline-flex items-center gap-1.5 rounded-full border border-border/60 bg-muted/25 px-2.5 py-1 text-[11px] text-muted-foreground"
                                >
                                    <CheckCircle2 className="size-3 text-success-500" />
                                    {item}
                                </span>
                            ))}
                        </div>
                    </div>
                    <div>
                        <div className="text-[10px] font-bold uppercase tracking-[.16em] text-muted-foreground">
                            {t("Watch")}
                        </div>
                        <div className="mt-2 flex flex-wrap gap-2">
                            {(risks.length
                                ? risks
                                : [t("No immediate anomaly detected")]
                            ).map((item) => (
                                <span
                                    key={item}
                                    className="inline-flex items-center rounded-full border border-warning-500/20 bg-warning-500/5 px-2.5 py-1 text-[11px] text-muted-foreground"
                                >
                                    {item}
                                </span>
                            ))}
                        </div>
                    </div>
                </div>
            </CardContent>
        </Card>
    );
}

function SummarySignal({
    label: labelText,
    value,
    positive,
    negative,
}: {
    label: string;
    value: string;
    positive?: boolean;
    negative?: boolean;
}) {
    const className = positive
        ? "ui-status-success"
        : negative
          ? "ui-status-danger"
          : "text-foreground";

    return (
        <div>
            <div className="text-[10px] text-muted-foreground">{labelText}</div>
            <div className={`mt-0.5 font-semibold capitalize ${className}`}>
                {value}
            </div>
        </div>
    );
}

function RegimeCard({ data }: { data: Intelligence }) {
    const { t } = useI18n();
    const bullish = data.structure.structure_bias === "long";
    const bearish = data.structure.structure_bias === "short";
    const TrendIcon = bullish ? TrendingUp : bearish ? TrendingDown : Activity;
    const trendClass = bullish
        ? "ui-status-success"
        : bearish
          ? "ui-status-danger"
          : "ui-status-info";

    return (
        <Card className="overflow-hidden border-border/70 bg-card/95 shadow-xs">
            <CardHeader className="border-b border-border/60 p-5 pb-4">
                <div className="flex items-start justify-between gap-3">
                    <div className="flex items-center gap-3">
                        <div className="flex size-10 items-center justify-center rounded-xl border border-border bg-muted/40 text-warning-500">
                            <Layers className="size-5" />
                        </div>
                        <div>
                            <CardTitle className="text-sm">
                                {t("Market Regime")}
                            </CardTitle>
                            <div className="mt-0.5 text-[11px] text-muted-foreground">
                                {t(
                                    "Structure state from confirmed closed-candle pivots",
                                )}
                            </div>
                        </div>
                    </div>
                    <Badge
                        variant="secondary"
                        className={`capitalize ${trendClass}`}
                    >
                        <TrendIcon className="mr-1.5 size-3.5" />
                        {label(data.structure.trend)}
                    </Badge>
                </div>
            </CardHeader>
            <CardContent className="space-y-4 p-5 pt-4">
                <div className="grid gap-3 sm:grid-cols-3">
                    <Metric
                        label={t("Bias")}
                        value={label(data.structure.structure_bias)}
                    />
                    <Metric
                        label="BOS"
                        value={
                            data.structure.bos
                                ? `${label(data.structure.bos.direction)} · ${formatPrice(data.structure.bos.level)}`
                                : "—"
                        }
                    />
                    <Metric
                        label="CHoCH"
                        value={
                            data.structure.choch
                                ? `${label(data.structure.choch.direction)} · ${formatPrice(data.structure.choch.level)}`
                                : "—"
                        }
                    />
                </div>
                <div className="grid gap-3 sm:grid-cols-2">
                    <Metric
                        label={t("Protected High")}
                        value={
                            data.structure.protected_high
                                ? formatPrice(
                                      data.structure.protected_high.price,
                                  )
                                : "—"
                        }
                    />
                    <Metric
                        label={t("Protected Low")}
                        value={
                            data.structure.protected_low
                                ? formatPrice(
                                      data.structure.protected_low.price,
                                  )
                                : "—"
                        }
                    />
                    <Metric
                        label={t("Last Swing High")}
                        value={
                            data.structure.last_swing_high
                                ? formatPrice(
                                      data.structure.last_swing_high.price,
                                  )
                                : "—"
                        }
                    />
                    <Metric
                        label={t("Last Swing Low")}
                        value={
                            data.structure.last_swing_low
                                ? formatPrice(
                                      data.structure.last_swing_low.price,
                                  )
                                : "—"
                        }
                    />
                </div>
                <div className="rounded-xl border border-border/60 bg-muted/20 p-3 text-[11px] leading-5 text-muted-foreground">
                    {t(
                        "BOS and CHoCH use confirmed swing pivots and closed candles, so the regime does not depend on the unfinished candle.",
                    )}
                </div>
            </CardContent>
        </Card>
    );
}

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

function VolumeProfileCard({ data }: { data: Intelligence }) {
    const { t } = useI18n();
    const profile = data.volume_profile;
    const distance = profile.current.distance_from_poc_percent;

    return (
        <Card className="overflow-hidden border-border/70 bg-card/95 shadow-xs">
            <CardHeader className="border-b border-border/60 p-5 pb-4">
                <div className="flex items-center justify-between gap-3">
                    <div className="flex items-center gap-3">
                        <div className="flex size-10 items-center justify-center rounded-xl border border-border bg-muted/40 text-info-500">
                            <BarChart className="size-5" />
                        </div>
                        <div>
                            <CardTitle className="text-sm">
                                {t("Volume Profile")}
                            </CardTitle>
                            <div className="mt-0.5 text-[11px] text-muted-foreground">
                                {profile.profile.used_candles}{" "}
                                {t("closed candles")} · {profile.profile.bins}{" "}
                                {t("price bins")}
                            </div>
                        </div>
                    </div>
                    <Badge variant="outline" className="text-[10px]">
                        {label(profile.current.position)}
                    </Badge>
                </div>
            </CardHeader>
            <CardContent className="space-y-4 p-5 pt-4">
                <div className="grid gap-3 sm:grid-cols-3">
                    <Metric label="VAH" value={formatPrice(profile.vah.high)} />
                    <Metric
                        label="POC"
                        value={formatPrice(profile.poc.price)}
                        emphasis
                    />
                    <Metric label="VAL" value={formatPrice(profile.val.low)} />
                </div>
                <div className="grid gap-3 sm:grid-cols-2">
                    <Metric
                        label={t("Current")}
                        value={formatPrice(profile.current.price)}
                    />
                    <Metric
                        label={t("Distance from POC")}
                        value={formatPct(distance, 2)}
                    />
                    <Metric
                        label="HVN"
                        value={String(profile.nodes.hvn.length)}
                    />
                    <Metric
                        label="LVN"
                        value={String(profile.nodes.lvn.length)}
                    />
                </div>
                <div>
                    <div className="mb-2 flex items-center justify-between text-[10px] uppercase tracking-wider text-muted-foreground">
                        <span>{t("Value Area")}</span>
                        <span>
                            {(profile.value_area.volume_share * 100).toFixed(1)}
                            %
                        </span>
                    </div>
                    <div className="h-2 overflow-hidden rounded-full bg-muted/60">
                        <div
                            className="h-full rounded-full bg-info-500/70"
                            style={{
                                width: `${Math.min(100, profile.value_area.volume_share * 100)}%`,
                            }}
                        />
                    </div>
                </div>
                <div className="rounded-xl border border-border/60 bg-muted/20 p-3 text-[11px] leading-5 text-muted-foreground">
                    {t(
                        "POC, VAH, and VAL are estimated from candle ranges because standard OHLCV does not contain true trade-level volume-at-price.",
                    )}
                </div>
            </CardContent>
        </Card>
    );
}

function FlowCard({ data }: { data: Intelligence }) {
    const { t } = useI18n();
    const flow = data.flow;
    const derivatives = flow.derivatives;

    if (data.market !== "futures") {
        return (
            <Card className="border-border/70 bg-card/95 shadow-xs">
                <CardHeader className="p-5 pb-3">
                    <div className="flex items-center gap-3">
                        <div className="flex size-10 items-center justify-center rounded-xl border border-border bg-muted/40 text-primary-500">
                            <Activity className="size-5" />
                        </div>
                        <div>
                            <CardTitle className="text-sm">
                                {t("Market Flow")}
                            </CardTitle>
                            <div className="mt-0.5 text-[11px] text-muted-foreground">
                                {t("Futures-only derivatives context")}
                            </div>
                        </div>
                    </div>
                </CardHeader>
                <CardContent className="p-5 pt-2">
                    <div className="rounded-xl border border-dashed border-border/70 bg-muted/20 p-4 text-xs leading-5 text-muted-foreground">
                        {t(
                            "Switch to Futures to see provider-native funding, open interest, taker flow, long/short, and liquidation metrics.",
                        )}
                    </div>
                </CardContent>
            </Card>
        );
    }

    return (
        <Card className="border-border/70 bg-card/95 shadow-xs">
            <CardHeader className="p-5 pb-3">
                <div className="flex items-center justify-between gap-3">
                    <div className="flex items-center gap-3">
                        <div className="flex size-10 items-center justify-center rounded-xl border border-border bg-muted/40 text-primary-500">
                            <Activity className="size-5" />
                        </div>
                        <div>
                            <CardTitle className="text-sm">
                                {t("Market Flow")}
                            </CardTitle>
                            <div className="mt-0.5 text-[11px] text-muted-foreground">
                                {t("Derivative period")}:{" "}
                                {flow.derivative_period}
                            </div>
                        </div>
                    </div>
                    {flow.available ? (
                        <Badge variant="secondary">{t("Live")}</Badge>
                    ) : (
                        <Badge variant="outline">{t("Partial")}</Badge>
                    )}
                </div>
            </CardHeader>
            <CardContent className="space-y-4 p-5 pt-2">
                {!flow.available && (
                    <div className="rounded-xl border border-warning-500/30 bg-warning-500/5 p-3 text-xs text-muted-foreground">
                        {flow.error ??
                            t(
                                "Derivative flow is unavailable for this provider right now.",
                            )}
                    </div>
                )}
                <div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
                    <Metric
                        label="Funding"
                        value={
                            derivatives.funding.rate_pct == null
                                ? "—"
                                : formatPct(derivatives.funding.rate_pct, 4)
                        }
                    />
                    <Metric
                        label="OI Change"
                        value={
                            derivatives.open_interest.change_pct == null
                                ? "—"
                                : formatPct(
                                      derivatives.open_interest.change_pct,
                                      2,
                                  )
                        }
                    />
                    <Metric
                        label="Taker Buy"
                        value={
                            derivatives.taker.buy_pct == null
                                ? "—"
                                : `${numberOrDash(derivatives.taker.buy_pct, 1)}%`
                        }
                    />
                    <Metric
                        label="Liquidations"
                        value={formatCompact(
                            derivatives.liquidations.total_value,
                        )}
                    />
                </div>
                <div className="grid gap-3 sm:grid-cols-2">
                    <Metric
                        label="Open Interest"
                        value={compactOrDash(
                            derivatives.open_interest.contracts,
                        )}
                    />
                    <Metric
                        label="Buy / Sell Ratio"
                        value={numberOrDash(
                            derivatives.taker.buy_sell_ratio,
                            3,
                        )}
                    />
                    <Metric
                        label="Account Long"
                        value={
                            derivatives.long_short.account.long_pct == null
                                ? "—"
                                : `${numberOrDash(derivatives.long_short.account.long_pct, 1)}%`
                        }
                    />
                    <Metric
                        label="Top Trader Long"
                        value={
                            derivatives.long_short.top_trader_position
                                .long_pct == null
                                ? "—"
                                : `${numberOrDash(derivatives.long_short.top_trader_position.long_pct, 1)}%`
                        }
                    />
                    <Metric
                        label="Long Liquidated"
                        value={formatCompact(
                            derivatives.liquidations.long_value,
                        )}
                    />
                    <Metric
                        label="Short Liquidated"
                        value={formatCompact(
                            derivatives.liquidations.short_value,
                        )}
                    />
                </div>
                <p className="text-[11px] leading-5 text-muted-foreground">
                    {t(
                        "Funding, OI, taker flow, and liquidation values are kept provider-native. Missing venue-specific data stays unavailable rather than being substituted from another exchange.",
                    )}
                </p>
            </CardContent>
        </Card>
    );
}

function RotationRadarCard({
    provider,
    market,
    symbol,
}: {
    provider: string;
    market: MarketType;
    symbol: string;
}) {
    const { t } = useI18n();
    const [radar, setRadar] = useState<RotationRadarData | null>(null);
    const [validation, setValidation] = useState<RotationValidationData | null>(
        null,
    );
    const [loading, setLoading] = useState(false);
    const [validationLoading, setValidationLoading] = useState(false);
    const [error, setError] = useState("");
    const [validationError, setValidationError] = useState("");
    const requestRef = useRef<AbortController | null>(null);
    const validationRequestRef = useRef<AbortController | null>(null);

    useEffect(() => {
        requestRef.current?.abort();
        const controller = new AbortController();
        requestRef.current = controller;
        setLoading(true);
        setError("");
        setRadar(null);
        setValidation(null);
        setValidationError("");

        const params = new URLSearchParams({
            provider,
            market,
            symbol,
        });

        fetch(`/market-intelligence/rotation-radar?${params.toString()}`, {
            headers: {
                Accept: "application/json",
                "X-Requested-With": "XMLHttpRequest",
            },
            credentials: "same-origin",
            cache: "no-store",
            signal: controller.signal,
        })
            .then(async (response) => {
                if (!response.ok) {
                    let message = `HTTP ${response.status}`;
                    try {
                        const payload = (await response.json()) as {
                            message?: string;
                        };
                        message = payload.message ?? message;
                    } catch {
                        // Keep HTTP status.
                    }
                    throw new Error(message);
                }
                return (await response.json()) as RotationRadarData;
            })
            .then((next) => {
                if (!controller.signal.aborted) setRadar(next);
            })
            .catch((reason) => {
                if (controller.signal.aborted) return;
                setError(
                    reason instanceof Error
                        ? reason.message
                        : "Unable to load rotation data.",
                );
            })
            .finally(() => {
                if (requestRef.current === controller) {
                    requestRef.current = null;
                    setLoading(false);
                }
            });

        return () => {
            controller.abort();
            if (requestRef.current === controller) {
                requestRef.current = null;
            }
        };
    }, [provider, market, symbol]);

    useEffect(() => {
        validationRequestRef.current?.abort();

        if (!radar?.candidates.length) {
            setValidation(null);
            setValidationLoading(false);
            return;
        }

        const controller = new AbortController();
        validationRequestRef.current = controller;
        setValidationLoading(true);
        setValidationError("");

        const params = new URLSearchParams({
            provider,
            market,
            leader: radar.leader.symbol,
            symbols: radar.candidates.map((item) => item.symbol).join(","),
        });

        fetch(`/market-intelligence/rotation-validation?${params.toString()}`, {
            headers: {
                Accept: "application/json",
                "X-Requested-With": "XMLHttpRequest",
            },
            credentials: "same-origin",
            cache: "no-store",
            signal: controller.signal,
        })
            .then(async (response) => {
                if (!response.ok) {
                    let message = `HTTP ${response.status}`;
                    try {
                        const payload = (await response.json()) as {
                            message?: string;
                        };
                        message = payload.message ?? message;
                    } catch {
                        // Keep HTTP status.
                    }
                    throw new Error(message);
                }
                return (await response.json()) as RotationValidationData;
            })
            .then((next) => {
                if (!controller.signal.aborted) setValidation(next);
            })
            .catch((reason) => {
                if (controller.signal.aborted) return;
                setValidationError(
                    reason instanceof Error
                        ? reason.message
                        : "Historical validation is unavailable.",
                );
            })
            .finally(() => {
                if (validationRequestRef.current === controller) {
                    validationRequestRef.current = null;
                    setValidationLoading(false);
                }
            });

        return () => {
            controller.abort();
            if (validationRequestRef.current === controller) {
                validationRequestRef.current = null;
            }
        };
    }, [provider, market, radar]);

    if (loading && !radar) {
        return (
            <Card className="border-border/70 bg-card/95 shadow-xs">
                <CardContent className="space-y-4 p-5">
                    <div className="flex items-center justify-between">
                        <div className="space-y-2">
                            <Skeleton className="h-4 w-32" />
                            <Skeleton className="h-3 w-48" />
                        </div>
                        <Skeleton className="h-5 w-24 rounded-full" />
                    </div>
                    <div className="grid gap-3 sm:grid-cols-3">
                        {[1, 2, 3].map((item) => (
                            <Skeleton key={item} className="h-20 rounded-xl" />
                        ))}
                    </div>
                </CardContent>
            </Card>
        );
    }

    if (error) {
        return (
            <Card className="border-border/70 bg-card/95 shadow-xs">
                <CardContent className="p-5 text-sm text-destructive">
                    {error}
                </CardContent>
            </Card>
        );
    }

    if (!radar) {
        return (
            <Card className="border-border/70 bg-card/95 shadow-xs">
                <CardContent className="p-5 text-sm text-muted-foreground">
                    {t("No rotation radar data is available yet.")}
                </CardContent>
            </Card>
        );
    }

    const validationBySymbol = new Map<string, ValidationCandidate>(
        (validation?.candidates ?? []).map((item) => [item.symbol, item]),
    );
    const validationSample = validation?.sample_events ?? 0;
    const validationReady = validation?.status === "validated";

    return (
        <Card className="overflow-hidden border-border/70 bg-card/95 shadow-xs">
            <CardHeader className="border-b border-border/60 p-5 pb-4">
                <div className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
                    <div>
                        <div className="flex items-center gap-2">
                            <div className="flex size-9 items-center justify-center rounded-xl border border-border bg-muted/40 text-info-500">
                                <TrendingUp className="size-4.5" />
                            </div>
                            <div>
                                <CardTitle className="text-sm">
                                    {t("Rotation Radar")}
                                </CardTitle>
                                <div className="text-[11px] text-muted-foreground">
                                    {radar.leader.symbol} ·{" "}
                                    {radar.scope === "same_narrative"
                                        ? t("same narrative")
                                        : t("market wide")}
                                </div>
                            </div>
                        </div>
                    </div>
                    <div className="flex items-center gap-2">
                        <Badge variant="outline" className="w-fit text-[10px]">
                            {t("Research signal")}
                        </Badge>
                        <Badge
                            variant="secondary"
                            className="w-fit text-[10px]"
                        >
                            {radar.signal_strength === "strong"
                                ? t("Strong leader move")
                                : t("Weak leader move")}
                        </Badge>
                        <Badge
                            variant={validationReady ? "secondary" : "outline"}
                            className="w-fit text-[10px]"
                        >
                            {validationLoading
                                ? t("Validating…")
                                : validationReady
                                  ? t("Historically validated")
                                  : t("Validation warming up")}
                        </Badge>
                    </div>
                </div>
            </CardHeader>

            <CardContent className="space-y-4 p-5 pt-4">
                <div className="grid gap-3 sm:grid-cols-3">
                    <Metric
                        label={t("Leader")}
                        value={`${radar.leader.symbol} ${formatPct(radar.leader.change_pct, 2)}`}
                        emphasis
                    />
                    <Metric
                        label={t("Current candidates")}
                        value={`${radar.candidates.length}`}
                    />
                    <Metric
                        label={t("Historical trigger events")}
                        value={
                            validationLoading
                                ? "…"
                                : validationSample > 0
                                  ? `${validationSample}`
                                  : "—"
                        }
                    />
                </div>

                {radar.candidates.length === 0 ? (
                    <div className="rounded-xl border border-dashed border-border/70 bg-muted/20 p-4 text-xs leading-5 text-muted-foreground">
                        {radar.message ??
                            t(
                                "No clear catch-up candidate is supported by the current market move.",
                            )}
                    </div>
                ) : (
                    <div className="space-y-2">
                        <div className="flex items-center justify-between gap-3">
                            <div>
                                <div className="text-xs font-semibold text-foreground">
                                    {t("Potential Catch-Up")}
                                </div>
                                <div className="text-[10px] text-muted-foreground">
                                    {t(
                                        "Current rank combines relative performance versus the selected leader and liquidity. A candidate can still be negative when the leader is positive, because the radar measures relative lag rather than absolute direction.",
                                    )}
                                </div>
                            </div>
                            <span className="shrink-0 text-[10px] text-muted-foreground">
                                +{radar.candidates.length} {t("ranked")}
                            </span>
                        </div>

                        <div className="space-y-2">
                            {radar.candidates.map((item, index) => {
                                const historical = validationBySymbol.get(
                                    item.symbol,
                                );
                                const horizon1 = historical?.horizons.find(
                                    (row) => row.hours === 1,
                                );
                                const horizon4 = historical?.horizons.find(
                                    (row) => row.hours === 4,
                                );
                                const horizon24 = historical?.horizons.find(
                                    (row) => row.hours === 24,
                                );

                                return (
                                    <div
                                        key={item.symbol}
                                        className="rounded-xl border border-border/60 bg-background/50 px-3 py-3"
                                    >
                                        <div className="grid gap-3 lg:grid-cols-[auto_minmax(0,1fr)_auto_auto_auto] lg:items-center">
                                            <span className="text-[10px] font-bold text-muted-foreground">
                                                #{index + 1}
                                            </span>
                                            <div className="min-w-0">
                                                <div className="flex flex-wrap items-center gap-2">
                                                    <span className="text-xs font-semibold text-foreground">
                                                        {item.symbol}
                                                    </span>
                                                    <span className="text-[10px] text-muted-foreground">
                                                        {formatPct(
                                                            item.change_pct,
                                                            2,
                                                        )}
                                                    </span>
                                                    <Badge
                                                        variant="secondary"
                                                        className="text-[9px]"
                                                    >
                                                        {t("Current")}{" "}
                                                        {item.current_score}
                                                    </Badge>
                                                </div>
                                                <div className="mt-1 h-1.5 overflow-hidden rounded-full bg-muted">
                                                    <div
                                                        className="h-full rounded-full bg-info-500/70"
                                                        style={{
                                                            width: `${Math.max(5, item.current_score)}%`,
                                                        }}
                                                    />
                                                </div>
                                            </div>
                                            <div className="min-w-16 text-left lg:text-right">
                                                <div className="text-[9px] uppercase tracking-[.1em] text-muted-foreground">
                                                    {t("Validated score")}
                                                </div>
                                                <div className="text-sm font-semibold tabular-nums text-foreground">
                                                    {historical?.validation_score ??
                                                        "—"}
                                                </div>
                                            </div>
                                            <div className="min-w-16 text-left lg:text-right">
                                                <div className="text-[9px] uppercase tracking-[.1em] text-muted-foreground">
                                                    {t("Median lag")}
                                                </div>
                                                <div className="text-sm font-semibold tabular-nums text-foreground">
                                                    {historical?.median_lag_hours !=
                                                    null
                                                        ? `${historical.median_lag_hours}h`
                                                        : "—"}
                                                </div>
                                            </div>
                                            <div className="min-w-16 text-left lg:text-right">
                                                <div className="text-[9px] uppercase tracking-[.1em] text-muted-foreground">
                                                    {t("24h follow")}
                                                </div>
                                                <div className="text-sm font-semibold tabular-nums text-success-500">
                                                    {horizon24?.follow_rate_pct !=
                                                    null
                                                        ? `${horizon24.follow_rate_pct.toFixed(1)}%`
                                                        : "—"}
                                                </div>
                                            </div>
                                        </div>

                                        <div className="mt-3 grid grid-cols-2 gap-2 border-t border-border/50 pt-3 sm:grid-cols-4">
                                            {[
                                                [
                                                    t("1h follow"),
                                                    horizon1?.follow_rate_pct,
                                                ],
                                                [
                                                    t("4h follow"),
                                                    horizon4?.follow_rate_pct,
                                                ],
                                                [
                                                    t("24h avg"),
                                                    horizon24?.average_follow_through_pct,
                                                ],
                                                [
                                                    t("24h failure"),
                                                    horizon24?.failure_rate_pct,
                                                ],
                                            ].map(([labelText, value]) => (
                                                <div key={labelText as string}>
                                                    <div className="text-[9px] uppercase tracking-[.1em] text-muted-foreground">
                                                        {labelText}
                                                    </div>
                                                    <div className="mt-0.5 text-xs font-semibold tabular-nums text-foreground">
                                                        {typeof value ===
                                                        "number"
                                                            ? labelText ===
                                                              t("24h avg")
                                                                ? formatPct(
                                                                      value,
                                                                      2,
                                                                  )
                                                                : `${value.toFixed(1)}%`
                                                            : "—"}
                                                    </div>
                                                </div>
                                            ))}
                                        </div>
                                    </div>
                                );
                            })}
                        </div>
                    </div>
                )}

                {validationError ? (
                    <div className="rounded-xl border border-warning-500/20 bg-warning-500/5 p-3 text-[10px] leading-5 text-muted-foreground">
                        {validationError}
                    </div>
                ) : validation?.status === "insufficient_history" ? (
                    <div className="rounded-xl border border-warning-500/20 bg-warning-500/5 p-3 text-[10px] leading-5 text-muted-foreground">
                        <span className="font-semibold text-foreground">
                            {t(
                                "Historical validation is not a probability yet.",
                            )}{" "}
                        </span>
                        {t(
                            "The model needs at least 20 qualifying leader events. Current history is still warming up, so the validated score stays blank instead of pretending to be reliable.",
                        )}
                    </div>
                ) : (
                    <div className="rounded-xl border border-border/60 bg-muted/20 p-3 text-[10px] leading-5 text-muted-foreground">
                        <span className="font-semibold text-foreground">
                            {t("Method:")}{" "}
                        </span>
                        {t(
                            "A qualifying event is a leader 1h move of at least +1%. Follow-through is measured at 1h, 4h, and 24h. Median lag is the first time the candidate gains at least +0.25% within 24h. The validated score is a research ranking, not a probability.",
                        )}
                    </div>
                )}
            </CardContent>
        </Card>
    );
}

function Metric({
    label,
    value,
    emphasis = false,
}: {
    label: string;
    value: string;
    emphasis?: boolean;
}) {
    return (
        <div className="rounded-xl border border-border/60 bg-background/55 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-semibold tabular-nums ${emphasis ? "text-info-500" : "text-foreground"}`}
            >
                {value}
            </div>
        </div>
    );
}

function PageSkeleton() {
    return (
        <div className="grid gap-4 lg:grid-cols-2">
            {[1, 2, 3, 4].map((item) => (
                <Card key={item} className="border-border/60 bg-card/70">
                    <CardContent className="space-y-3 p-5">
                        <div className="h-4 w-36 animate-pulse rounded bg-muted/60" />
                        <div className="grid gap-3 sm:grid-cols-3">
                            {[1, 2, 3].map((metric) => (
                                <div
                                    key={metric}
                                    className="h-16 animate-pulse rounded-xl bg-muted/40"
                                />
                            ))}
                        </div>
                        <div className="h-12 animate-pulse rounded-xl bg-muted/30" />
                    </CardContent>
                </Card>
            ))}
        </div>
    );
}
