import { IconChevronLeft, IconChevronRight, IconClose, IconFilter, IconList, IconMapPin, IconQrCode, IconRefresh, IconSearch } from '@douyinfe/semi-icons';
import { useQuery } from '@tanstack/react-query';
import { memo, useCallback, useDeferredValue, useEffect, useMemo, useRef, useState } from 'react';
import { Link, useSearchParams } from 'react-router-dom';
import { api } from '../../api/client';
import type { Page, VehicleRealtimeRow } from '../../api/types';
import { FleetMap } from '../map/FleetMap';
import { EmptyState, InlineError } from '../shared/AsyncState';
import { VehicleSourceEvidencePanel } from '../shared/VehicleSourceEvidencePanel';
import { formatNumber, relativeFreshness, statusLabel, vehicleStatus } from '../domain/monitor';
import { MAX_MONITOR_SEARCH_TERMS, MONITOR_REFRESH, monitorFilterScope, monitorQueryParams, parseMonitorSearchTerms, useMonitorData, useMonitorVehicleCard, type MonitorViewport } from '../hooks/useMonitorData';
import { LIVE_QUERY_POLICY, QUERY_MEMORY, retainPreviousPageWithinScope } from '../queryPolicy';
import { buildMonitorPath, parseMonitorRouteContext, withMonitorReturn } from '../routing/monitorContext';

const protocols = ['', 'GB32960', 'JT808', 'YUTONG_MQTT'];
const statuses = ['', 'online', 'offline', 'driving', 'idle', 'no_location'];
const EMPTY_VEHICLES: VehicleRealtimeRow[] = [];
const MOBILE_MONITOR_QUERY = '(max-width: 760px)';

function BatchVehicleSearchDialog({ initialValue, onApply, onClose }: { initialValue: string; onApply: (value: string) => void; onClose: () => void }) {
  const [draft, setDraft] = useState(initialValue);
  const terms = useMemo(() => parseMonitorSearchTerms(draft), [draft]);
  useEffect(() => {
    const closeOnEscape = (event: KeyboardEvent) => { if (event.key === 'Escape') onClose(); };
    window.addEventListener('keydown', closeOnEscape);
    return () => window.removeEventListener('keydown', closeOnEscape);
  }, [onClose]);

  return <div className="v2-batch-search-backdrop" role="presentation" onMouseDown={(event) => { if (event.target === event.currentTarget) onClose(); }}>
    <section className="v2-batch-search-dialog" role="dialog" aria-modal="true" aria-labelledby="batch-search-title">
      <header><div><strong id="batch-search-title">批量搜索车辆</strong><span>从 Excel、文本或聊天记录中直接粘贴车牌</span></div><button type="button" onClick={onClose} aria-label="关闭批量搜索"><IconClose /></button></header>
      <label htmlFor="batch-vehicle-search">每行一个车牌，也支持空格、逗号或分号分隔</label>
      <textarea id="batch-vehicle-search" autoFocus value={draft} onChange={(event) => setDraft(event.target.value)} placeholder={'粤A12345\n粤B67890\n粤C24680'} />
      <div className="v2-batch-search-summary"><span>已识别 <strong>{terms.length}</strong> 辆，重复项已自动去除</span><em>最多 {MAX_MONITOR_SEARCH_TERMS} 辆</em></div>
      <footer><button type="button" className="v2-secondary-button" onClick={onClose}>取消</button><button type="button" className="v2-primary-button" disabled={!terms.length} onClick={() => onApply(terms.join('，'))}>应用搜索（{terms.length}）</button></footer>
    </section>
  </div>;
}

function useMobileMonitorLayout() {
  const [mobile, setMobile] = useState(() => window.matchMedia(MOBILE_MONITOR_QUERY).matches);
  useEffect(() => {
    const media = window.matchMedia(MOBILE_MONITOR_QUERY);
    const update = () => setMobile(media.matches);
    media.addEventListener('change', update);
    update();
    return () => media.removeEventListener('change', update);
  }, []);
  return mobile;
}

type AddressCoordinate = { longitude: number; latitude: number; key: string };

function hasRealtimeLocation(vehicle: VehicleRealtimeRow) {
  if (vehicle.locationAvailable != null) return vehicle.locationAvailable;
  return Number.isFinite(vehicle.longitude) && Number.isFinite(vehicle.latitude)
    && Math.abs(vehicle.longitude) <= 180 && Math.abs(vehicle.latitude) <= 90
    && (vehicle.longitude !== 0 || vehicle.latitude !== 0);
}

function hasRealtimeSpeed(vehicle: VehicleRealtimeRow) {
  return vehicle.speedAvailable ?? hasRealtimeLocation(vehicle);
}

function hasRealtimeMileage(vehicle: VehicleRealtimeRow) {
  return vehicle.mileageAvailable ?? hasRealtimeLocation(vehicle);
}

function hasRealtimeSOC(vehicle: VehicleRealtimeRow) {
  return vehicle.socAvailable ?? (vehicle.primaryProtocol === 'GB32960' || vehicle.primaryProtocol === 'YUTONG_MQTT');
}

function addressCoordinate(vehicle: VehicleRealtimeRow): AddressCoordinate | undefined {
  if (!hasRealtimeLocation(vehicle) || !Number.isFinite(vehicle.longitude) || !Number.isFinite(vehicle.latitude)
    || Math.abs(vehicle.longitude) > 180 || Math.abs(vehicle.latitude) > 90
    || (vehicle.longitude === 0 && vehicle.latitude === 0)) return undefined;
  const longitude = Number(vehicle.longitude.toFixed(4));
  const latitude = Number(vehicle.latitude.toFixed(4));
  return { longitude, latitude, key: `${longitude.toFixed(4)},${latitude.toFixed(4)}` };
}

const MonitorAddressCell = memo(function MonitorAddressCell({ vehicle }: { vehicle: VehicleRealtimeRow }) {
  const current = addressCoordinate(vehicle);
  const [requested, setRequested] = useState<AddressCoordinate>();
  const addressQuery = useQuery({
    queryKey: ['monitor', 'list-address', requested?.key],
    queryFn: ({ signal }) => api.reverseGeocode(new URLSearchParams({
      longitude: requested!.longitude.toFixed(4),
      latitude: requested!.latitude.toFixed(4)
    }), signal),
    enabled: Boolean(requested),
    staleTime: 6 * 60 * 60_000,
    gcTime: QUERY_MEMORY.highVolumeGcTime,
    refetchOnWindowFocus: false,
    retry: 1
  });
  const moved = Boolean(current && requested && current.key !== requested.key);

  if (!current) return <span className="v2-monitor-address-empty">暂无实时位置</span>;
  if (!requested) return <button type="button" className="v2-monitor-address-action" aria-label={`解析${vehicle.plate || vehicle.vin}位置`} title="按需调用高德逆地理编码，不随实时数据刷新重复请求" onClick={() => setRequested(current)}><IconMapPin />解析位置</button>;
  if (addressQuery.isFetching && !addressQuery.data) return <span className="v2-monitor-address-loading"><i className="v2-spinner" />解析中</span>;
  if (addressQuery.isError) return <button type="button" className="v2-monitor-address-action is-error" onClick={() => void addressQuery.refetch()}>解析失败，重试</button>;
  return <div className="v2-monitor-address-result"><span title={addressQuery.data?.formattedAddress}>{addressQuery.data?.formattedAddress || '暂无地址'}</span><small>{addressQuery.dataUpdatedAt ? `解析于 ${new Date(addressQuery.dataUpdatedAt).toLocaleTimeString('zh-CN', { hour12: false, hour: '2-digit', minute: '2-digit' })}` : ''}</small>{moved ? <button type="button" title="车辆已移动，按需更新地址" onClick={() => setRequested(current)}>位置已移动 · 更新</button> : null}</div>;
});

function MonitorVehicleTable({ rows, total, page, totalPages, limit, loading, onSelect, onPage, onLimit }: { rows: VehicleRealtimeRow[]; total: number; page: number; totalPages: number; limit: number; loading: boolean; onSelect: (vin: string) => void; onPage: (page: number) => void; onLimit: (limit: number) => void }) {
  const mobile = useMobileMonitorLayout();
  return <section className="v2-monitor-table-panel">
    <header><div><strong>车辆实时列表</strong><span>覆盖全部授权车辆；实时字段缺失时显示“—”，文字地址按需解析</span></div><b>{total.toLocaleString('zh-CN')} 辆车辆</b></header>
    {!mobile ? <div className="v2-monitor-table-scroll"><table><thead><tr><th>车辆</th><th>推荐来源</th><th>速度</th><th>里程</th><th>经纬度</th><th>地理位置</th><th>最新上报</th></tr></thead>
      <tbody>{rows.map((row) => <tr key={row.vin}>
        <td className="v2-monitor-table-vehicle"><button type="button" title="在地图中定位" onClick={() => onSelect(row.vin)}><strong>{row.plate || '未绑定车牌'}</strong><span>{row.vin}</span></button></td>
        <td><span className="v2-monitor-source-badge">{row.primaryProtocol || '—'}</span></td>
        <td><strong className="v2-monitor-live-value">{hasRealtimeSpeed(row) ? formatNumber(row.speedKmh, 1) : '—'}</strong>{hasRealtimeSpeed(row) ? <small className="v2-monitor-live-unit">km/h</small> : null}</td>
        <td><div className="v2-monitor-mileage"><span><small>总</small><strong>{hasRealtimeMileage(row) ? `${formatNumber(row.totalMileageKm, 1)} km` : '—'}</strong></span><span><small>今日</small><strong>{row.todayMileageAvailable ? `${formatNumber(row.todayMileageKm ?? 0, 1)} km` : '—'}</strong></span></div></td>
        <td>{hasRealtimeLocation(row) ? <code className="v2-monitor-coordinate">{row.longitude.toFixed(6)}<br />{row.latitude.toFixed(6)}</code> : <span className="v2-monitor-unavailable">—</span>}</td>
        <td><MonitorAddressCell vehicle={row} /></td>
        <td><div className="v2-monitor-last-seen"><strong>{row.lastSeen ? relativeFreshness(row.lastSeen) : '从未上报'}</strong><span>{row.lastSeen || '—'}</span></div></td>
      </tr>)}</tbody></table>{loading ? <div className="v2-monitor-table-loading"><i className="v2-spinner" />正在更新车辆实时数据…</div> : null}{!loading && !rows.length ? <EmptyState /> : null}</div> : null}
    {mobile ? <div className="v2-monitor-mobile-cards">{rows.map((row) => <article key={row.vin}>
      <header><div><strong>{row.plate || '未绑定车牌'}</strong><span>{row.vin} · {row.primaryProtocol || '暂无来源'}</span></div><b>{hasRealtimeSpeed(row) ? formatNumber(row.speedKmh, 1) : '—'}{hasRealtimeSpeed(row) ? <small>km/h</small> : null}</b></header>
      <dl><div><dt>总里程</dt><dd>{hasRealtimeMileage(row) ? `${formatNumber(row.totalMileageKm, 1)} km` : '—'}</dd></div><div><dt>今日里程</dt><dd>{row.todayMileageAvailable ? `${formatNumber(row.todayMileageKm ?? 0, 1)} km` : '—'}</dd></div><div><dt>经纬度</dt><dd>{hasRealtimeLocation(row) ? <code>{row.longitude.toFixed(6)}, {row.latitude.toFixed(6)}</code> : '—'}</dd></div><div><dt>最新上报</dt><dd>{row.lastSeen ? relativeFreshness(row.lastSeen) : '从未上报'}</dd></div><div className="is-address"><dt>地理位置</dt><dd><MonitorAddressCell vehicle={row} /></dd></div></dl>
      <footer><button type="button" onClick={() => onSelect(row.vin)}><IconMapPin />{hasRealtimeLocation(row) ? '地图定位' : '查看车辆'}</button></footer>
    </article>)}{loading ? <div className="v2-monitor-table-loading"><i className="v2-spinner" />正在更新车辆实时数据…</div> : null}{!loading && !rows.length ? <EmptyState /> : null}</div> : null}
    <footer><span>第 {page} / {totalPages} 页</span><div><button type="button" disabled={page <= 1} onClick={() => onPage(page - 1)}>上一页</button><button type="button" disabled={page >= totalPages} onClick={() => onPage(page + 1)}>下一页</button><select aria-label="每页车辆数" value={limit} onChange={(event) => onLimit(Number(event.target.value))}><option value="20">20 辆/页</option><option value="50">50 辆/页</option><option value="100">100 辆/页</option></select></div></footer>
  </section>;
}

function MobileEntry({ onClose }: { onClose: () => void }) {
  const [qr, setQr] = useState('');
  const [error, setError] = useState('');
  const [copyState, setCopyState] = useState<'idle' | 'copied' | 'error'>('idle');
  const [attempt, setAttempt] = useState(0);
  const url = `${window.location.origin}/monitor`;
  useEffect(() => {
    const closeOnEscape = (event: KeyboardEvent) => { if (event.key === 'Escape') onClose(); };
    window.addEventListener('keydown', closeOnEscape);
    return () => window.removeEventListener('keydown', closeOnEscape);
  }, [onClose]);
  useEffect(() => {
    if (copyState === 'idle') return;
    const timer = window.setTimeout(() => setCopyState('idle'), 1_800);
    return () => window.clearTimeout(timer);
  }, [copyState]);
  useEffect(() => {
    let cancelled = false;
    setQr('');
    setError('');
    void import('qrcode')
      .then(({ default: QRCode }) => QRCode.toDataURL(url, { width: 240, margin: 2, color: { dark: '#122033', light: '#ffffff' } }))
      .then((value) => { if (!cancelled) setQr(value); })
      .catch(() => { if (!cancelled) setError('二维码生成失败，请检查浏览器环境后重试'); });
    return () => { cancelled = true; };
  }, [attempt, url]);
  const copyURL = async () => {
    try {
      if (!navigator.clipboard?.writeText) throw new Error('clipboard unavailable');
      await navigator.clipboard.writeText(url);
      setCopyState('copied');
    } catch {
      setCopyState('error');
    }
  };
  return <div className="v2-monitor-qr-backdrop" role="dialog" aria-modal="true" aria-label="手机端入口" onMouseDown={(event) => { if (event.target === event.currentTarget) onClose(); }}><section><button type="button" autoFocus onClick={onClose} aria-label="关闭手机端入口"><IconClose /></button><IconQrCode /><h3>手机端全局监控</h3><p>扫码后使用现有账号鉴权，不在二维码中保存 Token</p>{qr ? <img src={qr} alt="全局监控手机端二维码" /> : error ? <div className="v2-monitor-qr-error" role="alert"><span>{error}</span><button type="button" onClick={() => setAttempt((value) => value + 1)}>重新生成</button></div> : <span className="v2-spinner" role="status" aria-label="正在生成二维码" />}<code>{url}</code><button type="button" aria-live="polite" onClick={() => void copyURL()}>{copyState === 'copied' ? '已复制访问地址' : copyState === 'error' ? '复制失败，重试' : '复制访问地址'}</button></section></div>;
}

const VehicleRow = memo(function VehicleRow({ vehicle, selected, onSelect }: { vehicle: VehicleRealtimeRow; selected: boolean; onSelect: (vin: string) => void }) {
  const status = vehicleStatus(vehicle);
  return (
    <button type="button" className={`v2-vehicle-row ${selected ? 'is-selected' : ''}`} onClick={() => onSelect(vehicle.vin)}>
      <i className={`v2-status-dot is-${status}`} />
      <span className="v2-vehicle-identity"><strong>{vehicle.plate || '未绑定车牌'}</strong><small>{vehicle.vin}</small></span>
      <span className="v2-vehicle-motion"><strong>{formatNumber(vehicle.speedKmh, 1)} <small>km/h</small></strong><small>{statusLabel(status)}</small></span>
    </button>
  );
});

const MemoFleetMap = memo(FleetMap);

function VehicleDetailCard({
  vehicle,
  monitorReturn,
  onCollapse,
  onClear
}: {
  vehicle: VehicleRealtimeRow;
  monitorReturn: string;
  onCollapse: () => void;
  onClear: () => void;
}) {
  const [sourceEvidenceOpen, setSourceEvidenceOpen] = useState(false);
  const card = useMonitorVehicleCard(vehicle.vin, vehicle, true);
  const detail = card.detail.data;
  const activeAlerts = card.activeAlerts.data;
  const address = card.address.data;
  const status = vehicleStatus(vehicle);
  const dailyMileage = detail?.mileage.items[0]?.dailyMileageKm;
  const latestAlert = activeAlerts?.items[0];
  return (
    <aside className="v2-vehicle-detail">
      <div className="v2-detail-controls">
        <button type="button" aria-label="收起车辆详情" title="收起到地图右侧" onClick={onCollapse}><IconChevronRight /></button>
        <button type="button" aria-label="取消选择车辆" title="取消选择车辆" onClick={onClear}><IconClose /></button>
      </div>
      <div className="v2-detail-title">
        <div><strong>{vehicle.plate || '未绑定车牌'}</strong><span className={`v2-status-text is-${status}`}>{statusLabel(status)}</span></div>
        <small>{vehicle.vin}</small>
      </div>
      <div className="v2-detail-actions">
        <Link to={withMonitorReturn(`/vehicles/${encodeURIComponent(vehicle.vin)}`, monitorReturn)}>单车详情</Link>
        <Link to={withMonitorReturn(`/tracks?vin=${encodeURIComponent(vehicle.vin)}`, monitorReturn)}>轨迹回放</Link>
        <Link to={withMonitorReturn(`/history?vin=${encodeURIComponent(vehicle.vin)}`, monitorReturn)}>历史数据</Link>
        <Link to={withMonitorReturn(`/statistics?vins=${encodeURIComponent(vehicle.vin)}`, monitorReturn)}>里程查询</Link>
      </div>
      <section>
        <h3>车辆信息</h3>
        <dl className="v2-detail-list">
          <div><dt>VIN</dt><dd>{vehicle.vin}</dd></div>
          <div><dt>厂家</dt><dd>{vehicle.oem || '待补充'}</dd></div>
          <div><dt>协议</dt><dd>{vehicle.primaryProtocol || vehicle.protocols.join('、') || '未知'}</dd></div>
          <div><dt>数据来源</dt><dd>{detail?.sources.join('、') || vehicle.protocols.join('、') || '未知'}</dd></div>
          <div><dt>接入供应商</dt><dd>{detail?.profile?.accessProvider || '待补充'}</dd></div>
          <div><dt>来源覆盖</dt><dd>{vehicle.onlineSourceCount}/{vehicle.sourceCount}</dd></div>
        </dl>
      </section>
      <section>
        <h3>实时状态</h3>
        <div className="v2-metric-grid">
          <div><small>速度</small><strong>{hasRealtimeSpeed(vehicle) ? formatNumber(vehicle.speedKmh, 1) : '—'}<em>{hasRealtimeSpeed(vehicle) ? 'km/h' : ''}</em></strong></div>
          <div><small>SOC</small><strong>{hasRealtimeSOC(vehicle) ? formatNumber(vehicle.socPercent, 1) : '—'}<em>{hasRealtimeSOC(vehicle) ? '%' : ''}</em></strong></div>
          <div><small>总里程</small><button type="button" className="v2-metric-source-link" title="展开全部里程来源" onClick={() => setSourceEvidenceOpen(true)}>{hasRealtimeMileage(vehicle) ? formatNumber(vehicle.totalMileageKm, 1) : '—'}<em>{hasRealtimeMileage(vehicle) ? 'km' : ''}</em></button></div>
          <div><small>今日里程</small><button type="button" className="v2-metric-source-link" title="展开全部里程来源" onClick={() => setSourceEvidenceOpen(true)}>{dailyMileage == null ? '—' : formatNumber(dailyMileage, 1)}<em>{dailyMileage == null ? '' : 'km'}</em></button></div>
          <div><small>状态</small><strong>{statusLabel(status)}</strong></div>
          <div><small>当前告警</small><strong>{formatNumber(activeAlerts?.total ?? 0)}<em>条</em></strong></div>
        </div>
      </section>
      <section>
        <h3>最新上报</h3>
        <dl className="v2-detail-list">
          <div><dt>时间</dt><dd>{vehicle.lastSeen || '暂无'}</dd></div>
          <div><dt>新鲜度</dt><dd>{relativeFreshness(vehicle.lastSeen)}</dd></div>
          <div><dt>坐标</dt><dd><button type="button" className="v2-detail-source-link" title="展开全部位置来源" onClick={() => setSourceEvidenceOpen(true)}>{hasRealtimeLocation(vehicle) ? `${vehicle.longitude.toFixed(6)}, ${vehicle.latitude.toFixed(6)}` : '—'}</button></dd></div>
          <div><dt>位置</dt><dd>{hasRealtimeLocation(vehicle) ? address?.formattedAddress || '位置解析中' : '暂无实时位置'}</dd></div>
          <div><dt>告警状态</dt><dd>{latestAlert ? `${latestAlert.ruleName} · ${latestAlert.severity}` : '无当前业务告警'}</dd></div>
        </dl>
      </section>
      <VehicleSourceEvidencePanel vin={vehicle.vin} compact open={sourceEvidenceOpen} onOpenChange={setSourceEvidenceOpen} />
    </aside>
  );
}

export default function MonitorPage() {
  const [routeParams, setRouteParams] = useSearchParams();
  const initialContextRef = useRef(parseMonitorRouteContext(routeParams));
  const initialContext = initialContextRef.current;
  const [mode, setMode] = useState<'map' | 'list'>(initialContext.mode);
  const [mobileEntryOpen, setMobileEntryOpen] = useState(false);
  const [listOffset, setListOffset] = useState(initialContext.listOffset);
  const [listLimit, setListLimit] = useState(initialContext.listLimit);
  const [keyword, setKeyword] = useState(initialContext.keyword);
  const [batchSearchOpen, setBatchSearchOpen] = useState(false);
  const deferredKeyword = useDeferredValue(keyword);
  const searchTerms = useMemo(() => parseMonitorSearchTerms(keyword), [keyword]);
  const [protocol, setProtocol] = useState(initialContext.protocol);
  const [status, setStatus] = useState(initialContext.status);
  const [selectedVin, setSelectedVin] = useState(initialContext.selectedVin);
  const [detailOpen, setDetailOpen] = useState(initialContext.detailOpen);
  const [viewport, setViewport] = useState<MonitorViewport>(initialContext.viewport);
  const updateViewport = useCallback((next: MonitorViewport) => {
    setViewport((current) => current.zoom === next.zoom && current.bounds === next.bounds ? current : next);
  }, []);
  const filters = useMemo(() => ({ keyword: deferredKeyword, protocol, status }), [deferredKeyword, protocol, status]);
  const monitorReturn = useMemo(() => buildMonitorPath({
    mode, keyword, protocol, status, selectedVin, detailOpen, viewport, listOffset, listLimit
  }), [detailOpen, keyword, listLimit, listOffset, mode, protocol, selectedVin, status, viewport]);
  useEffect(() => {
    const next = new URL(monitorReturn, 'https://vehicle-platform.invalid').searchParams;
    if (next.toString() !== routeParams.toString()) setRouteParams(next, { replace: true });
  }, [monitorReturn, routeParams, setRouteParams]);
  const listScope = useMemo(() => monitorFilterScope(filters), [filters]);
  const listParams = useMemo(() => {
    const params = monitorQueryParams(filters, listLimit);
    params.set('offset', String(listOffset));
    return params;
  }, [filters, listLimit, listOffset]);
  const trackedVin = mode === 'map' ? selectedVin : '';
  const { summary, vehicles, map, selectedVehicle } = useMonitorData(filters, viewport, trackedVin, mode === 'map', mode === 'map');
  const realtimeListQuery = useQuery<Page<VehicleRealtimeRow>>({
    queryKey: ['monitor', 'vehicle-list', listScope, listLimit, listOffset],
    queryFn: ({ signal }) => api.vehicleRealtime(listParams, signal),
    enabled: mode === 'list', placeholderData: retainPreviousPageWithinScope<Page<VehicleRealtimeRow>>(listScope, 2), refetchInterval: mode === 'list' ? MONITOR_REFRESH.fleet : false,
    gcTime: QUERY_MEMORY.highVolumeGcTime,
    ...LIVE_QUERY_POLICY
  });
  const rows = useMemo(() => {
    const data = vehicles.data?.items ?? [];
    if (status === 'driving' || status === 'idle') return data.filter((vehicle) => vehicleStatus(vehicle) === status);
    return data;
  }, [status, vehicles.data?.items]);
  const listRows = realtimeListQuery.data?.items ?? EMPTY_VEHICLES;
  const activeBatchRows = mode === 'map' ? rows : listRows;
  const activeBatchQuery = mode === 'map' ? vehicles : realtimeListQuery;
  const filterTransitionPending = keyword !== deferredKeyword || activeBatchQuery.isLoading;
  const batchSearchPending = searchTerms.length > 1 && filterTransitionPending;
  const batchMatch = useMemo(() => {
    const identities = new Set<string>();
    for (const vehicle of activeBatchRows) {
      identities.add(vehicle.vin.toLocaleUpperCase());
      if (vehicle.plate) identities.add(vehicle.plate.toLocaleUpperCase());
    }
    const missing = searchTerms.filter((term) => !identities.has(term));
    return { matched: searchTerms.length - missing.length, missing };
  }, [activeBatchRows, searchTerms]);
  const visibleRows = filterTransitionPending ? [] : rows;
  const batchStatus = batchSearchPending
    ? `正在查找 ${searchTerms.length} 辆`
    : batchMatch.missing.length
      ? `已找到 ${batchMatch.matched}/${searchTerms.length} · 未找到 ${batchMatch.missing.length} 辆`
      : `已找到 ${batchMatch.matched}/${searchTerms.length}`;
  const batchStatusTitle = batchMatch.missing.length
    ? `未找到：${batchMatch.missing.join('、')}`
    : searchTerms.join('、');
  const visibleListRows = filterTransitionPending ? EMPTY_VEHICLES : listRows;
  const visibleListTotal = filterTransitionPending ? 0 : (realtimeListQuery.data?.total ?? 0);
  const selected = selectedVin
    ? rows.find((vehicle) => vehicle.vin === selectedVin) ?? selectedVehicle.data?.items[0]
    : undefined;
  const selectVehicle = useCallback((vin: string) => {
    setSelectedVin(vin);
    setDetailOpen(true);
    setMode('map');
  }, []);
  const clearSelection = useCallback(() => {
    setSelectedVin('');
    setDetailOpen(false);
  }, []);
  const selectMapVehicle = useCallback((vehicle: VehicleRealtimeRow) => selectVehicle(vehicle.vin), [selectVehicle]);
  const collapseDetail = useCallback(() => setDetailOpen(false), []);
  const expandDetail = useCallback(() => setDetailOpen(true), []);
  const driving = rows.filter((vehicle) => vehicleStatus(vehicle) === 'driving').length;
  const idle = rows.filter((vehicle) => vehicleStatus(vehicle) === 'idle').length;
  const offline = rows.filter((vehicle) => vehicleStatus(vehicle) === 'offline').length;

  return (
    <div className="v2-monitor-page">
      <section className="v2-filterbar" aria-label="车辆筛选">
        <div className={`v2-search-field${searchTerms.length > 1 ? ' is-batch' : ''}`}>
          <IconSearch />
          <input
            aria-label="搜索车辆"
            value={keyword}
            onChange={(event) => { setKeyword(event.target.value); setListOffset(0); }}
            onPaste={(event) => {
              const pastedTerms = parseMonitorSearchTerms(event.clipboardData.getData('text'));
              if (pastedTerms.length <= 1) return;
              event.preventDefault();
              setKeyword(pastedTerms.join('，'));
              setListOffset(0);
            }}
            placeholder="车牌 / VIN；可批量粘贴车牌"
          />
          <button type="button" className="v2-search-batch-action" onClick={() => setBatchSearchOpen(true)}>批量</button>
          {searchTerms.length > 1 ? <span className={`v2-search-batch-count${batchMatch.missing.length && !batchSearchPending ? ' has-missing' : ''}`} aria-live="polite" title={searchTerms.length === MAX_MONITOR_SEARCH_TERMS ? `最多支持 ${MAX_MONITOR_SEARCH_TERMS} 条；${batchStatusTitle}` : batchStatusTitle}>{batchSearchPending ? `已识别 ${searchTerms.length} 辆` : `已找到 ${batchMatch.matched}/${searchTerms.length}`}</span> : null}
        </div>
        <select value={protocol} onChange={(event) => { setProtocol(event.target.value); setListOffset(0); }} aria-label="协议">
          {protocols.map((item) => <option key={item} value={item}>{item || '全部协议'}</option>)}
        </select>
        <select value={status} onChange={(event) => { setStatus(event.target.value); setListOffset(0); }} aria-label="在线状态">
          {statuses.map((item) => <option key={item} value={item}>{item === 'no_location' ? '无实时位置' : item ? statusLabel(item as never) : '全部状态'}</option>)}
        </select>
        <button type="button" className="v2-secondary-button" onClick={() => { setKeyword(''); setProtocol(''); setStatus(''); setListOffset(0); }}><IconRefresh />清空</button>
        <span className="v2-filter-live-status" role="status" title="搜索和筛选条件修改后自动生效"><IconFilter />实时筛选</span>
        <div className="v2-monitor-mode" aria-label="监控视图"><button type="button" className={mode === 'map' ? 'is-active' : ''} onClick={() => setMode('map')}><IconMapPin />地图</button><button type="button" className={mode === 'list' ? 'is-active' : ''} onClick={() => { setMode('list'); setDetailOpen(false); }}><IconList />列表</button></div>
        <button type="button" className="v2-monitor-mobile-entry" onClick={() => setMobileEntryOpen(true)}><IconQrCode />手机端</button>
      </section>
      {batchSearchOpen ? <BatchVehicleSearchDialog initialValue={searchTerms.join('\n')} onClose={() => setBatchSearchOpen(false)} onApply={(value) => { setKeyword(value); setListOffset(0); setBatchSearchOpen(false); }} /> : null}

      <section className="v2-kpis" aria-label="车辆整体统计">
        {[
          ['车辆总数', formatNumber(summary.data?.totalVehicles ?? vehicles.data?.total ?? rows.length), 'fleet'],
          ['无实时位置', formatNumber(summary.data?.noLocationVehicles ?? 0), 'missing'],
          ['当前在线', formatNumber(summary.data?.onlineVehicles ?? rows.length - offline), 'online'],
          ['当前离线', formatNumber(summary.data?.offlineVehicles ?? offline), 'offline'],
          ['行驶车辆', formatNumber(summary.data?.drivingVehicles ?? driving), 'driving'],
          ['静止车辆', formatNumber(summary.data?.idleVehicles ?? idle), 'idle'],
          ['告警车辆', summary.data?.alertDataAvailable ? formatNumber(summary.data.alertVehicles) : '—', 'alert'],
          ['今日上报', formatNumber(summary.data?.frameToday ?? 0), 'today']
        ].map(([label, value, tone]) => <div key={label} className={`v2-kpi is-${tone}`}><small>{label}</small><strong>{value}</strong></div>)}
      </section>

      {vehicles.isError ? <InlineError message={vehicles.error instanceof Error ? vehicles.error.message : '车辆数据加载失败'} onRetry={() => vehicles.refetch()} /> : null}
      {mode === 'list' && realtimeListQuery.isError ? <InlineError message={realtimeListQuery.error instanceof Error ? realtimeListQuery.error.message : '车辆列表加载失败'} onRetry={() => realtimeListQuery.refetch()} /> : null}
      {mode === 'map' ? <section className={`v2-monitor-workspace${selected && detailOpen ? ' is-detail-open' : ''}${selected && !detailOpen ? ' is-detail-collapsed' : ''}`}>
        <div className="v2-vehicle-rail">
          <header><strong>车辆列表</strong><span>{batchSearchPending ? '查询中' : `${formatNumber(vehicles.data?.total ?? visibleRows.length)} 辆`}</span></header>
          <div className={`v2-rail-search${batchMatch.missing.length && !batchSearchPending ? ' has-missing' : ''}`} title={searchTerms.length > 1 ? batchStatusTitle : undefined}><IconSearch /><span>{searchTerms.length > 1 ? batchStatus : deferredKeyword ? `正在筛选“${deferredKeyword}”` : '按最新上报排序'}</span></div>
          <div className="v2-vehicle-scroll">
            {vehicles.isLoading || batchSearchPending ? <div className="v2-list-loading"><span className="v2-spinner" />{batchSearchPending ? `正在查找 ${searchTerms.length} 辆车` : '加载车辆'}</div> : null}
            {!vehicles.isLoading && !batchSearchPending && visibleRows.length === 0 ? <EmptyState /> : null}
            {visibleRows.map((vehicle) => <VehicleRow key={vehicle.vin} vehicle={vehicle} selected={vehicle.vin === selectedVin} onSelect={selectVehicle} />)}
          </div>
          <footer>{searchTerms.length > 1 && !batchSearchPending ? batchStatus : `当前载入 ${visibleRows.length} / ${vehicles.data?.total ?? visibleRows.length} 辆`}</footer>
        </div>
        <MemoFleetMap
          vehicles={visibleRows}
          monitorMap={filterTransitionPending ? undefined : map.data}
          selectedVin={selectedVin || undefined}
          onSelect={selectMapVehicle}
          onSelectVin={selectVehicle}
          onViewportChange={updateViewport}
          initialViewport={initialContext.hasViewport ? initialContext.viewport : undefined}
        />
        {selected && detailOpen ? (
          <VehicleDetailCard
            vehicle={selected}
            monitorReturn={monitorReturn}
            onCollapse={collapseDetail}
            onClear={clearSelection}
          />
        ) : null}
        {selected && !detailOpen ? (
          <aside className="v2-detail-peek" aria-label="已收起的车辆详情">
            <button type="button" aria-label="展开车辆详情" title={`展开 ${selected.plate || selected.vin} 的车辆详情`} onClick={expandDetail}>
              <IconChevronLeft />
              <i className={`v2-status-dot is-${vehicleStatus(selected)}`} />
              <span>{selected.plate || '未绑定车牌'}</span>
            </button>
          </aside>
        ) : null}
      </section> : <MonitorVehicleTable rows={visibleListRows} total={visibleListTotal} page={Math.floor(listOffset / listLimit) + 1} totalPages={Math.max(1, Math.ceil(visibleListTotal / listLimit))} limit={listLimit} loading={filterTransitionPending || realtimeListQuery.isFetching} onSelect={selectVehicle} onPage={(page) => setListOffset((page - 1) * listLimit)} onLimit={(next) => { setListLimit(next); setListOffset(0); }} />}

      <section className="v2-event-strip">
        <strong>实时数据状态</strong>
        <span><i className="is-online" />{vehicles.isFetching ? '正在刷新' : '实时车辆已同步'}</span>
        <span>{mode === 'map' ? `列表 ${visibleRows.length} 条 · 地图 ${map.data?.clusters.length ? `${map.data.clusters.length} 个聚合 + ${map.data.points.length} 个车辆点` : `${map.data?.points.length ?? 0} 个点`}` : `实时列表 ${realtimeListQuery.data?.items.length ?? 0} / ${realtimeListQuery.data?.total ?? 0} 辆`}</span>
        <span className="v2-refresh-cadence"><b>智能刷新</b> 重点车辆 {MONITOR_REFRESH.selected / 1000} 秒 · 车队 {MONITOR_REFRESH.fleet / 1000} 秒 · 统计 {MONITOR_REFRESH.summary / 1000} 秒</span>
        <time>{new Date().toLocaleString('zh-CN', { hour12: false })}</time>
      </section>
      {mobileEntryOpen ? <MobileEntry onClose={() => setMobileEntryOpen(false)} /> : null}
    </div>
  );
}
