import type { PageKey } from '../layout/AppShell';

const pageKeys = new Set<PageKey>(['dashboard', 'vehicles', 'map', 'realtime', 'detail', 'history', 'history-query', 'mileage', 'time-monitor', 'alert-events', 'quality', 'notification-rules', 'ops-quality']);

export type AppRoute = {
  page?: PageKey;
  keyword?: string;
  protocol?: string;
  filters?: Record<string, string>;
};

const filterKeys = [
  'coverage',
  'serviceStatus',
  'online',
  'bindingStatus',
  'archiveStatus',
  'archiveMissing',
  'missingProtocol',
  'issueType',
  'tab',
  'dateFrom',
  'dateTo',
  'includeFields',
  'fields'
] as const;

export function parseAppHash(hash: string): AppRoute {
  const normalized = hash.trim().replace(/^#\/?/, '');
  if (!normalized) {
    return {};
  }
  const [pagePart, queryPart = ''] = normalized.split('?', 2);
  if (!pageKeys.has(pagePart as PageKey)) {
    return {};
  }
  const params = new URLSearchParams(queryPart);
  const keyword = params.get('keyword')?.trim() || undefined;
  const protocol = params.get('protocol')?.trim() || undefined;
  const filters: Record<string, string> = {};
  for (const key of filterKeys) {
    const value = params.get(key)?.trim();
    if (value) {
      filters[key] = value;
    }
  }
  return { page: pagePart as PageKey, keyword, protocol, filters };
}

export function buildAppHash(route: AppRoute): string {
  const page = route.page && pageKeys.has(route.page) ? route.page : 'dashboard';
  const params = new URLSearchParams();
  const keyword = route.keyword?.trim();
  if (keyword) {
    params.set('keyword', keyword);
  }
  const protocol = route.protocol?.trim();
  if (protocol) {
    params.set('protocol', protocol);
  }
  for (const key of filterKeys) {
    const value = route.filters?.[key]?.trim();
    if (value) {
      params.set(key, value);
    }
  }
  const query = params.toString();
  return query ? `#/${page}?${query}` : `#/${page}`;
}
