"use client"; import clsx from "clsx"; import Link from "next/link"; import { Activity, BarChart3, Bell, ChevronLeft, Gauge, GraduationCap, LineChart, Menu, Search, Table2, UserRound, } from "lucide-react"; import { useEffect, useMemo, useRef, useState } from "react"; import { Area, AreaChart, Bar, BarChart as ReBarChart, CartesianGrid, Line, LineChart as ReLineChart, ReferenceLine, ResponsiveContainer, Tooltip, XAxis, YAxis, } from "recharts"; import type { ProAccessState, ScanOpportunityRow } from "@/lib/dashboard-types"; import { getInitialLocaleFromNavigator } from "@/lib/i18n"; import { isBrowserLocalFullAccess } from "@/lib/local-dev-access"; import { sortRowsByUserTime } from "@/components/dashboard/scan-terminal/decision-utils"; import { ProductAccessRequired } from "@/components/dashboard/scan-terminal/ProductAccessRequired"; import { type ContinentGroup, buildContinentGroups, formatPrice, formatSpreadLiquidity, GAP_COLOR_MAP, getDefaultExpanded, getGapColor, getSignalLabel, getSignalState, TRADING_REGIONS, } from "@/components/dashboard/scan-terminal/continent-grouping"; import { MobileCityCard } from "@/components/dashboard/scan-terminal/MobileCityCard"; import { MobileRegionTabs } from "@/components/dashboard/scan-terminal/MobileRegionTabs"; import { useScanTerminalQuery } from "@/components/dashboard/scan-terminal/use-scan-terminal-query"; import { useScanTerminalTheme, useUserLocalClock, } from "@/components/dashboard/scan-terminal/use-scan-terminal-ui-state"; import { ScanTerminalLoadingScreen } from "@/components/dashboard/scan-terminal/ScanTerminalShellParts"; import { scanRootClass } from "@/components/dashboard/scan-root-styles"; import { useRelativeTime } from "@/hooks/useRelativeTime"; import { Panel } from "@/components/dashboard/scan-terminal/Panel"; import { GroupedMarketTable } from "@/components/dashboard/scan-terminal/GroupedMarketTable"; import { rowName, pct, money, temp, edgeClass } from "@/components/dashboard/scan-terminal/utils"; function createEmptyAccess(loading = true): ProAccessState { return { loading, authenticated: false, userId: null, subscriptionActive: false, subscriptionPlanCode: null, subscriptionExpiresAt: null, subscriptionTotalExpiresAt: null, subscriptionQueuedDays: 0, points: 0, error: null, }; } function createLocalAccess(): ProAccessState { return { loading: false, authenticated: true, userId: "local-dev", subscriptionActive: true, subscriptionPlanCode: "local-full-access", subscriptionExpiresAt: "2099-12-31T23:59:59Z", subscriptionTotalExpiresAt: "2099-12-31T23:59:59Z", subscriptionQueuedDays: 0, points: 999_999, error: null, }; } const TERM = { cityContract: { en: "City / Contract", zh: "城市 / 合约" }, live: { en: "Live", zh: "实测" }, deb: { en: "DEB", zh: "DEB" }, mkt: { en: "Mkt", zh: "市场" }, edge: { en: "Edge", zh: "优势" }, liq: { en: "Liq", zh: "流动性" }, signal: { en: "Signal", zh: "信号" }, searchPlaceholder: { en: "Search city, contract, station, or signal", zh: "搜索城市、合约、站点或信号" }, weatherContracts: { en: "Weather Contracts", zh: "天气合约" }, selectedContractMonitor: { en: "Selected Contract Monitor", zh: "选中合约监控" }, probabilityDistribution: { en: "Probability Distribution", zh: "概率分布" }, marketList: { en: "Market List", zh: "市场列表" }, watchlist: { en: "Watchlist", zh: "观察列表" }, rows: { en: "Rows", zh: "行数" }, avgEdge: { en: "Avg Edge", zh: "平均优势" }, liquidity: { en: "Liquidity", zh: "流动性" }, intradayPerformance: { en: "Intraday Performance", zh: "日内表现" }, spread: { en: "Spread", zh: "价差" }, model: { en: "Model", zh: "模型" }, noData: { en: "No data", zh: "无数据" }, noDistributionData: { en: "No distribution data", zh: "无分布数据" }, selectContract: { en: "Select a weather contract to inspect model edge, market price, and live evidence.", zh: "选择天气合约以查看模型优势、市场价格和实况证据。", }, signInToContinue: { en: "Sign in to continue", zh: "请先登录" }, signInHint: { en: "The terminal is only available to registered users. Please sign in or create an account.", zh: "决策台仅对注册用户开放。请登录或创建账号。", }, logIn: { en: "Log in", zh: "登录" }, createAccount: { en: "Create an account", zh: "注册账号" }, learnAbout: { en: "Learn about PolyWeather", zh: "了解 PolyWeather" }, proAccessRequired: { en: "Pro Access Required", zh: "需要付费订阅" }, proDesc: { en: "The PolyWeather terminal is a paid product. Subscribe to unlock real-time weather-market intelligence.", zh: "PolyWeather 决策台为付费产品。订阅以解锁实时天气市场情报。", }, subscriptionTerms: { en: "Billed monthly. Cancel anytime. Payment via USDC on Polygon.", zh: "按月计费,随时可取消。通过 Polygon 链 USDC 支付。", }, month: { en: "/ month", zh: "/ 月" }, subscribeNow: { en: "Subscribe Now — $10/mo", zh: "立即订阅 — $10/月" }, subscribePrompt: { en: "You need an active subscription to access the terminal.", zh: "你需要开通有效订阅才能访问决策台。", }, backToProduct: { en: "Back to product overview", zh: "返回产品介绍页" }, dashboard: { en: "PolyWeather Terminal", zh: "PolyWeather 交易决策台" }, refresh: { en: "Refresh", zh: "刷新" }, switchLang: { en: "Switch to Chinese", zh: "切换到英文" }, globalWeatherFactors: { en: "Global Weather Factors", zh: "全球天气因子" }, heat: { en: "Heat", zh: "高温风险" }, active: { en: "Active", zh: "活跃" }, watch: { en: "Watch", zh: "观察" }, tradable: { en: "Tradable", zh: "可交易" }, primary: { en: "Primary", zh: "主信号" }, ai: { en: "AI", zh: "AI" }, closed: { en: "Closed", zh: "已关闭" }, terminalStatus: { en: "Terminal Status", zh: "终端状态" }, tsData: { en: "Data", zh: "数据" }, tsAccess: { en: "Access", zh: "访问权限" }, tsLayout: { en: "Layout", zh: "布局" }, tsLayoutValue: { en: "Multi-panel grid", zh: "多面板网格" }, tsDataLive: { en: "live", zh: "实时" }, tsAccessPaid: { en: "paid", zh: "付费" }, } as const; function t(key: keyof typeof TERM, isEn: boolean) { return isEn ? TERM[key].en : TERM[key].zh; } function decisionLabel(row?: ScanOpportunityRow | null) { const raw = row?.ai_decision || row?.v4_metar_decision || row?.action || row?.signal_status || ""; const value = String(raw || "").toLowerCase(); if (value.includes("approve")) return "Approve"; if (value.includes("veto")) return "Veto"; if (value.includes("watch")) return "Watch"; if (value.includes("downgrade")) return "Downgrade"; if (row?.tradable) return "Tradable"; return "Monitor"; } function decisionClass(label: string) { const l = label.toLowerCase(); if (l.includes("approve") || l.includes("active") || l.includes("活跃")) { return "bg-emerald-50 border-emerald-200 text-emerald-700"; } if (l.includes("watch") || l.includes("观察") || l.includes("monitor")) { return "bg-amber-50 border-amber-200 text-amber-700"; } if (l.includes("veto") || l.includes("downgrade") || l.includes("closed") || l.includes("关闭")) { return "bg-slate-50 border-slate-200 text-slate-500"; } return "bg-blue-50 border-blue-200 text-blue-700"; } function SparkArea({ color = "#2563eb", data, isEn = true, }: { color?: string; data: { v: number }[]; isEn?: boolean; }) { if (!data.length) { return (
{t("noData", isEn)}
); } return ( ); } function ProbabilityDistributionChart({ points, isEn = true, }: { points?: ScanOpportunityRow["distribution_preview"]; isEn?: boolean; }) { if (!points?.length) { return (
{t("noDistributionData", isEn)}
); } const chartData = points.map((p) => ({ label: p.label || "", model: Number((p.model_probability ?? 0) * 100), market: Number((p.market_probability ?? 0) * 100), })); return ( `${v}%`} /> `${Number(value).toFixed(1)}%` } /> ); } function tablePrice(row: ScanOpportunityRow) { return formatPrice(row.midpoint, row.ask, row.bid); } function ticker(row: ScanOpportunityRow) { return String(row.airport || row.market_key || row.city || "--") .replace(/[^A-Za-z0-9]/g, "") .slice(0, 6) .toUpperCase(); } function KoyfinRowsTable({ compact = false, isEn, onSelect, rows, selectedId, }: { compact?: boolean; isEn: boolean; onSelect: (row: ScanOpportunityRow) => void; rows: ScanOpportunityRow[]; selectedId?: string | null; }) { return ( {!compact && ( )} {rows.map((row) => { const edge = Number(row.edge_percent ?? row.signed_gap ?? row.gap ?? 0); const positive = edge >= 0; return ( onSelect(row)} className={clsx( "cursor-pointer border-b border-slate-100 hover:bg-blue-50/70", selectedId === row.id && "bg-blue-50", )} > {!compact && ( )} ); })}
{isEn ? "Weather Contract" : "天气合约"} {isEn ? "Ticker" : "代码"} {isEn ? "Price" : "价格"} {isEn ? "Chg" : "变化"} %
{rowName(row)}
{row.target_label || row.market_question || row.airport || "--"}
{ticker(row)} {tablePrice(row)} {Number.isFinite(edge) ? `${positive ? "+" : ""}${edge.toFixed(1)}` : "--"} {pct(row.market_probability ?? row.market_event_probability ?? row.model_probability)}
); } function KoyfinMarketPanel({ compact, isEn, onSelect, rows, selectedId, title, }: { compact?: boolean; isEn: boolean; onSelect: (row: ScanOpportunityRow) => void; rows: ScanOpportunityRow[]; selectedId?: string | null; title: string; }) { return ( ); } function performanceSeries(row: ScanOpportunityRow | null) { return buildEvidenceChart(row).data; } type ObsPoint = { time?: string | null; temp?: number | null }; type EvidenceSeries = { key: string; label: string; source: string; color: string; dashed?: boolean; featured?: boolean; values: Array; }; type RunwayObsPayload = { runway_pairs?: Array<[string, string] | string[] | null> | null; temperatures?: Array<[number | null, number | null] | Array | null> | null; point_temperatures?: Array<{ runway?: string | null; tdz_temp?: number | null; mid_temp?: number | null; end_temp?: number | null; } | null> | null; }; function validNumber(value: unknown): number | null { return typeof value === "number" && Number.isFinite(value) ? value : null; } function normalizeObs(points?: ObsPoint[] | null, limit = 88) { return (points || []) .filter((point) => validNumber(point.temp) !== null) .slice(-limit) .map((point, index) => ({ label: point.time || String(index + 1), value: Number(point.temp), })); } function formatChartLabel(value: string) { if (!value) return ""; const maybeDate = new Date(value); if (!Number.isNaN(maybeDate.getTime())) { return maybeDate.toLocaleTimeString("zh-CN", { hour: "2-digit", minute: "2-digit", hour12: false }); } return value.length > 8 ? value.slice(-8) : value; } function seriesStats(values: Array) { const nums = values.filter((value): value is number => validNumber(value) !== null); const latest = nums.length ? nums[nums.length - 1] : null; const high = nums.length ? Math.max(...nums) : null; const first15 = nums.length > 1 ? nums[Math.max(0, nums.length - 15)] : null; const delta15 = latest !== null && first15 !== null ? latest - first15 : null; return { latest, high, delta15 }; } function buildModelPoints(row: ScanOpportunityRow | null, length: number) { const modelEntries = Object.entries(row?.model_cluster_sources || {}) .map(([label, value]) => [label, validNumber(value)] as const) .filter((entry): entry is readonly [string, number] => entry[1] !== null) .slice(0, 4); const constants: EvidenceSeries[] = modelEntries.map(([label, value], index) => ({ key: `model_${index}`, label, source: "Multi-model", color: ["#2563eb", "#14b8a6", "#7c3aed", "#64748b"][index] || "#64748b", dashed: true, values: Array.from({ length }, () => value), })); const deb = validNumber(row?.deb_prediction); if (deb !== null) { constants.unshift({ key: "deb", label: "DEB", source: "DEB", color: "#f97316", dashed: true, values: Array.from({ length }, () => deb), }); } return constants; } function extractRunwayPointSeries(row: ScanOpportunityRow | null, length: number): EvidenceSeries[] { const payload = row as | (ScanOpportunityRow & { amos?: { runway_obs?: RunwayObsPayload | null; source_label?: string | null; source?: string | null } | null; runway_obs?: RunwayObsPayload | null; }) | null; const runwayObs = payload?.amos?.runway_obs || payload?.runway_obs; if (!runwayObs) return []; const pairs = runwayObs.runway_pairs || []; const runwayTemps = runwayObs.temperatures || []; const pointTemps = runwayObs.point_temperatures || []; const source = payload?.amos?.source_label || payload?.amos?.source || "Runway"; const series: EvidenceSeries[] = []; pairs.forEach((pair, index) => { const pairLabel = Array.isArray(pair) && pair.length ? pair.filter(Boolean).join("/") : pointTemps[index]?.runway || `RWY ${index + 1}`; const values = [ ...(Array.isArray(runwayTemps[index]) ? runwayTemps[index] || [] : []), pointTemps[index]?.tdz_temp, pointTemps[index]?.mid_temp, pointTemps[index]?.end_temp, ] .map(validNumber) .filter((value): value is number => value !== null); if (!values.length) return; const maxTemp = Math.max(...values); series.push({ key: `runway_${index}`, label: `${pairLabel} runway`, source, color: ["#009688", "#f97316", "#0ea5e9", "#ef4444"][index] || "#64748b", featured: index === 0, dashed: index !== 0, values: Array.from({ length }, () => maxTemp), }); }); return series.slice(0, 4); } function buildEvidenceChart(row: ScanOpportunityRow | null) { const settlement = normalizeObs(row?.settlement_today_obs || row?.metar_context?.settlement_today_obs); const metar = normalizeObs(row?.metar_today_obs || row?.metar_context?.today_obs || row?.metar_recent_obs || row?.metar_context?.recent_obs); const baseLabels = settlement.length >= metar.length ? settlement.map((point) => point.label) : metar.map((point) => point.label); const length = Math.max(baseLabels.length, settlement.length, metar.length, 24); const labels = length === baseLabels.length ? baseLabels : Array.from({ length }, (_, index) => baseLabels[index] || `${String(index).padStart(2, "0")}:00`); const align = (points: Array<{ label: string; value: number }>) => { if (!points.length) return Array.from({ length }, () => null); const offset = Math.max(0, length - points.length); return Array.from({ length }, (_, index) => (index < offset ? null : points[index - offset]?.value ?? null)); }; const series: EvidenceSeries[] = []; series.push(...extractRunwayPointSeries(row, length)); if (settlement.length) { series.push({ key: "settlement", label: "Settlement runway", source: row?.metar_context?.station_label || row?.metar_context?.station || row?.airport || "Settlement", color: "#009688", featured: true, values: align(settlement), }); } if (metar.length) { series.push({ key: "metar", label: "METAR official", source: row?.airport || row?.metar_context?.source || "METAR", color: "#0ea5e9", dashed: true, values: align(metar), }); } series.push(...buildModelPoints(row, length)); const fallbackValue = validNumber(row?.current_temp) ?? validNumber(row?.current_max_so_far) ?? validNumber(row?.deb_prediction) ?? validNumber(row?.target_value) ?? validNumber(row?.target_threshold); if (!series.length && fallbackValue !== null) { series.push({ key: "current", label: "Current reference", source: row?.metar_context?.source || "Live", color: "#009688", featured: true, values: Array.from({ length }, () => fallbackValue), }); } const data = labels.map((label, index) => { const point: Record = { label: formatChartLabel(label) }; series.forEach((item) => { point[item.key] = item.values[index] ?? null; }); return point; }); return { data, series }; } function NormalizedPerformancePanel({ isEn, row, rows = [], onSelect, }: { isEn: boolean; row: ScanOpportunityRow | null; rows?: ScanOpportunityRow[]; onSelect?: (row: ScanOpportunityRow) => void; }) { const { data, series } = useMemo(() => buildEvidenceChart(row), [row]); const threshold = validNumber(row?.target_threshold) ?? validNumber(row?.target_value); const tableRows = series.slice(0, 5).map((item) => ({ ...item, ...seriesStats(item.values) })); return (
{rows.slice(0, 18).map((item) => ( ))}
{isEn ? "Settlement live" : "跑道实测"} {temp(validNumber(row?.current_temp))}
METAR {temp(validNumber(row?.metar_context?.airport_current_temp ?? row?.metar_context?.last_temp))}
{isEn ? "Threshold" : "当日阈值"} {temp(threshold)}
{tableRows.map((item) => (
{item.label}
now: {temp(item.latest)} max: {temp(item.high)} 15m: {item.delta15 === null ? "--" : `${item.delta15 >= 0 ? "+" : ""}${item.delta15.toFixed(1)}°`}
))}
{rowName(row)} {row?.target_label || row?.market_direction || ""}
`${Number(v).toFixed(1)}°`} orientation="right" axisLine={{ stroke: "#cbd5e1" }} tickLine={false} /> {threshold !== null && ( )} `${Number(value).toFixed(2)}°`} /> {series.map((item) => ( ))}
); } function FactorMatrix({ isEn, rows, }: { isEn: boolean; rows: ScanOpportunityRow[]; }) { const buckets = [ [isEn ? "Heat" : "高温", rows.filter((r) => r.risk_level === "high")], [isEn ? "Live Edge" : "实况优势", rows.filter((r) => Number(r.edge_percent || 0) > 0)], [isEn ? "Tradable" : "可交易", rows.filter((r) => r.tradable)], [isEn ? "AI Approved" : "AI 通过", rows.filter((r) => String(r.ai_decision || "").includes("approve"))], [isEn ? "Watch" : "观察", rows.filter((r) => getSignalState(r) === "watch")], [isEn ? "Closed" : "关闭", rows.filter((r) => r.closed)], ]; return (
{buckets.map(([label, list]) => { const count = Array.isArray(list) ? list.length : 0; const ratio = rows.length ? count / rows.length : 0; const tone = ratio >= 0.5 ? "bg-emerald-100 text-emerald-800 border-emerald-200" : ratio >= 0.2 ? "bg-amber-100 text-amber-800 border-amber-200" : "bg-slate-100 text-slate-600 border-slate-200"; return (
{(ratio * 100).toFixed(1)}%
{String(label)}
); })}
); } function YieldLikeTable({ isEn, rows, }: { isEn: boolean; rows: ScanOpportunityRow[]; }) { const regionStats = TRADING_REGIONS.map((region) => { const regionRows = rows.filter((row) => String(row.trading_region).toLowerCase() === region.key); const avgEdge = regionRows.reduce((sum, row) => sum + Number(row.edge_percent || 0), 0) / Math.max(regionRows.length, 1); const avgProb = regionRows.reduce((sum, row) => sum + Number(row.model_probability ?? row.model_event_probability ?? 0), 0) / Math.max(regionRows.length, 1); return { label: isEn ? region.labelEn : region.labelZh, edge: avgEdge, prob: avgProb, liq: regionRows.reduce((sum, row) => sum + Number(row.book_liquidity || row.market_liquidity || 0), 0), count: regionRows.length, }; }).filter((row) => row.count > 0).slice(0, 7); return ( {regionStats.map((row) => ( ))}
{isEn ? "Region" : "区域"} 1D 5D 10D {isEn ? "Liq" : "流动性"}
{row.label} {pct(row.edge)} {pct(row.prob)} {pct(row.edge + row.prob * 0.2)} {money(row.liq)}
); } function PolyWeatherTerminal({ generatedText, isEn, locale, onRefresh, refreshing, rows, selectedRow, setSelectedRow, toggleLocale, userLocalTime, searchQuery, setSearchQuery, searchInputRef, }: { generatedText: string; isEn: boolean; locale: "zh-CN" | "en-US"; onRefresh: () => void; refreshing: boolean; rows: ScanOpportunityRow[]; selectedRow: ScanOpportunityRow | null; setSelectedRow: (row: ScanOpportunityRow) => void; toggleLocale: () => void; userLocalTime: string; searchQuery: string; setSearchQuery: (val: string) => void; searchInputRef: React.RefObject; }) { useEffect(() => { const handleKeyDown = (e: KeyboardEvent) => { const activeEl = document.activeElement; const isInputFocused = activeEl && (activeEl.tagName === "INPUT" || activeEl.tagName === "TEXTAREA" || (activeEl instanceof HTMLElement && activeEl.isContentEditable)); if (e.key === "/" && !isInputFocused) { e.preventDefault(); searchInputRef.current?.focus(); searchInputRef.current?.select(); } if (e.key === "Escape" && activeEl === searchInputRef.current) { setSearchQuery(""); searchInputRef.current?.blur(); } }; window.addEventListener("keydown", handleKeyDown); return () => window.removeEventListener("keydown", handleKeyDown); }, [searchInputRef, setSearchQuery]); const [navExpanded, setNavExpanded] = useState(false); const [activeNavKey, setActiveNavKey] = useState("contracts"); const [selectedRegionKey, setSelectedRegionKey] = useState("all"); const NAV_ITEMS = [ { key: "contracts", Icon: Table2, labelEn: "Contracts", labelZh: "天气合约" }, { key: "signals", Icon: LineChart, labelEn: "Signals", labelZh: "交易信号" }, { key: "analytics", Icon: BarChart3, labelEn: "Analytics", labelZh: "分析图表" }, { key: "watchlist", Icon: Gauge, labelEn: "Watchlist", labelZh: "自选监控" }, { key: "alerts", Icon: Bell, labelEn: "Alerts", labelZh: "实时预警" }, { key: "markets", Icon: Activity, labelEn: "Markets", labelZh: "市场概览" }, { key: "training", Icon: GraduationCap, labelEn: "Training", labelZh: "训练数据" }, ]; const regionTabs = useMemo(() => { return [ { key: "all", labelEn: "ALL", labelZh: "全部" }, ...TRADING_REGIONS.map((r) => ({ key: r.key, labelEn: r.labelEn.toUpperCase(), labelZh: r.labelZh, })), ]; }, [isEn]); const filteredRegionRows = useMemo(() => { const byRegion = selectedRegionKey === "all" ? rows : rows.filter((row) => String(row.trading_region).toLowerCase() === selectedRegionKey); // Deduplicate: one row per city, keep the first (highest score from sorting) const seen = new Set(); return byRegion.filter((row) => { const key = (row.city || "").toLowerCase(); if (seen.has(key)) return false; seen.add(key); return true; }); }, [rows, selectedRegionKey]); const watchRows = useMemo(() => { return filteredRegionRows .filter((row) => decisionLabel(row) === "Watch" || !row.tradable) .slice(0, 8); }, [filteredRegionRows]); const topRows = filteredRegionRows.slice(0, 18); const heatRows = filteredRegionRows .filter((row) => row.risk_level === "high" || Number(row.current_temp ?? 0) >= 30) .slice(0, 10); const liquidRows = [...filteredRegionRows] .sort( (a, b) => Number(b.book_liquidity || b.market_liquidity || b.volume || 0) - Number(a.book_liquidity || a.market_liquidity || a.volume || 0), ) .slice(0, 9); const negativeRows = filteredRegionRows .filter((row) => Number(row.edge_percent ?? row.signed_gap ?? row.gap ?? 0) < 0) .slice(0, 8); const selectedSignal = selectedRow ? getSignalState(selectedRow) : "data" as const; const selectedLabel = selectedRow ? getSignalLabel(selectedSignal, isEn) : ""; const continentGroups = useMemo( () => buildContinentGroups(filteredRegionRows, isEn), [filteredRegionRows, isEn] ); const [mobileTab, setMobileTab] = useState("active_signals"); const mobileActiveGroup = useMemo( () => continentGroups.find((g) => g.key === mobileTab) || continentGroups[0], [continentGroups, mobileTab] ); useEffect(() => { if (continentGroups.length > 0 && !continentGroups.find((g) => g.key === mobileTab)) { setMobileTab(continentGroups[0].key); } }, [continentGroups, mobileTab]); useEffect(() => { if (!filteredRegionRows.length) return; if (!selectedRow || !filteredRegionRows.some((row) => row.id === selectedRow.id)) { setSelectedRow(filteredRegionRows[0]); } }, [filteredRegionRows, selectedRow, setSelectedRow]); const avgEdge = useMemo(() => { const list = filteredRegionRows; return list.reduce((sum, row) => sum + Number(row.edge_percent || 0), 0) / Math.max(list.length, 1); }, [filteredRegionRows]); const totalLiquidity = useMemo(() => { const list = filteredRegionRows; return list.reduce( (sum, row) => sum + Number(row.book_liquidity || row.market_liquidity || row.volume || 0), 0 ); }, [filteredRegionRows]); return (
setSearchQuery(e.target.value)} placeholder={t("searchPlaceholder", isEn)} className="w-full bg-transparent text-xs font-semibold text-slate-800 placeholder-slate-400 outline-none" /> {searchQuery && ( )} /
{t("dashboard", isEn)}
{userLocalTime}
{/* Mobile layout */}
{mobileActiveGroup?.rows.map((row) => ( ))}
{/* Mobile Selected Row Detail */} {selectedRow && (

{rowName(selectedRow)}

{[ ["Obs", temp(selectedRow.current_temp, selectedRow.temp_symbol)], ["High", temp(selectedRow.current_max_so_far, selectedRow.temp_symbol)], ["DEB", temp(selectedRow.deb_prediction, selectedRow.temp_symbol)], ["Gap", temp(selectedRow.signed_gap ?? selectedRow.gap_to_target, selectedRow.temp_symbol)], ["Edge", pct(selectedRow.edge_percent)], ["Market", formatPrice(selectedRow.midpoint, selectedRow.ask, selectedRow.bid)], ].map(([label, value]) => (
{label}
{value}
))}
)}
{/* Desktop layout */}
{regionTabs.map((tab) => { const isActive = selectedRegionKey === tab.key; return ( ); })}
{[ [t("rows", isEn), filteredRegionRows.length], [t("avgEdge", isEn), pct(avgEdge)], [t("liquidity", isEn), money(totalLiquidity)], [t("tsData", isEn), generatedText || t("tsDataLive", isEn)], [t("tsAccess", isEn), t("tsAccessPaid", isEn)], [t("tsLayout", isEn), "Koyfin"], ].map(([label, value]) => (
{label}
{value}
))}
); } function TrainingDataPanel({ isEn }: { isEn: boolean }) { const [data, setData] = useState | null>(null); useEffect(() => { let cancelled = false; fetch("/api/ops/training/accuracy", { cache: "no-store", headers: { Accept: "application/json" }, }) .then(async (res) => { if (!res.ok) return null; return (res.json() as Promise<{ accuracy: typeof data }>); }) .then((payload) => { if (cancelled || !payload?.accuracy) return; setData(payload.accuracy.filter((c) => c.deb && c.deb.total_days >= 5)); }) .catch(() => {}); return () => { cancelled = true; }; }, []); const debSorted = (data || []) .sort((a, b) => (b.deb?.hit_rate ?? 0) - (a.deb?.hit_rate ?? 0)); return (
{debSorted.length ? debSorted.map((c) => ( )) : ( )}
{isEn ? "City" : "城市"} {isEn ? "Hit" : "命中"} MAE {isEn ? "Days" : "天"}
{c.name} = 60 ? "bg-emerald-50 text-emerald-700" : (c.deb?.hit_rate ?? 0) >= 30 ? "bg-amber-50 text-amber-700" : "bg-red-50 text-red-700" }`}> {(c.deb?.hit_rate ?? 0).toFixed(0)}% {(c.deb?.mae ?? 0).toFixed(1)}° {c.deb?.total_days ?? 0}
{data === null ? (isEn ? "Loading..." : "加载中...") : (isEn ? "No data" : "无数据")}
); } function ScanTerminalScreen() { const [proAccess, setProAccess] = useState(() => createEmptyAccess(true), ); const [locale, setLocale] = useState<"zh-CN" | "en-US">("zh-CN"); const isEn = locale === "en-US"; const toggleLocale = () => setLocale((prev) => (prev === "zh-CN" ? "en-US" : "zh-CN")); const [hydrated, setHydrated] = useState(false); const [localFullAccess, setLocalFullAccess] = useState(false); const canUseLocalFullAccess = hydrated && localFullAccess; const isAuthenticated = hydrated && (proAccess.authenticated || canUseLocalFullAccess); const isPro = hydrated && (proAccess.subscriptionActive || canUseLocalFullAccess); const userLocalTime = useUserLocalClock(); const { themeMode } = useScanTerminalTheme(); useEffect(() => { let cancelled = false; setHydrated(true); setLocale(getInitialLocaleFromNavigator()); const localAccess = isBrowserLocalFullAccess(); setLocalFullAccess(localAccess); if (localAccess) { setProAccess(createLocalAccess()); return () => { cancelled = true; }; } if (typeof fetch !== "function") { setProAccess(createEmptyAccess(false)); return () => { cancelled = true; }; } fetch("/api/auth/me", { cache: "no-store", headers: { Accept: "application/json" }, }) .then(async (response) => { if (!response.ok) throw new Error(`HTTP ${response.status}`); return response.json() as Promise<{ authenticated?: boolean; user_id?: string | null; subscription_active?: boolean | null; subscription_plan_code?: string | null; subscription_expires_at?: string | null; subscription_total_expires_at?: string | null; subscription_queued_days?: number | null; points?: number | null; }>; }) .then((payload) => { if (cancelled) return; setProAccess({ loading: false, authenticated: Boolean(payload.authenticated), userId: payload.user_id ?? null, subscriptionActive: payload.subscription_active === true, subscriptionPlanCode: payload.subscription_plan_code ?? null, subscriptionExpiresAt: payload.subscription_expires_at ?? null, subscriptionTotalExpiresAt: payload.subscription_total_expires_at ?? payload.subscription_expires_at ?? null, subscriptionQueuedDays: Math.max( 0, Number(payload.subscription_queued_days ?? 0), ), points: Number(payload.points ?? 0), error: null, }); }) .catch((error) => { if (cancelled) return; setProAccess({ ...createEmptyAccess(false), error: String(error), }); }); return () => { cancelled = true; }; }, []); const { refreshScanTerminalManually, scanLoading, terminalData } = useScanTerminalQuery({ isPro, proAccessLoading: !hydrated || (proAccess.loading && !canUseLocalFullAccess), }); const rows = useMemo( () => sortRowsByUserTime(terminalData?.rows || []), [terminalData?.rows], ); const [searchQuery, setSearchQuery] = useState(""); const searchInputRef = useRef(null); const filteredRows = useMemo(() => { if (!searchQuery.trim()) return rows; const q = searchQuery.toLowerCase().trim(); return rows.filter((row) => { const haystack = [ row.city, row.city_display_name, row.display_name, row.airport, row.trading_region_label, row.trading_region_label_zh, row.market_question, row.target_label, row.ai_decision, row.v4_metar_decision, row.signal_status, ] .filter(Boolean) .map((v) => String(v).toLowerCase()); return haystack.some((s) => s.includes(q)); }); }, [rows, searchQuery]); const [selectedId, setSelectedId] = useState(null); const selectedRow = useMemo( () => filteredRows.find((row) => row.id === selectedId) || filteredRows[0] || null, [filteredRows, selectedId], ); const generatedText = useRelativeTime(terminalData?.generated_at ?? null); if (!hydrated || (proAccess.loading && !canUseLocalFullAccess)) { return ( ); } if (!isAuthenticated || !isPro) { return ( ); } return ( setSelectedId(row.id)} toggleLocale={toggleLocale} userLocalTime={userLocalTime} searchQuery={searchQuery} setSearchQuery={setSearchQuery} searchInputRef={searchInputRef} /> ); } export function ScanTerminalDashboard() { return ; }