import {
  FileCode2,
  History,
  LayoutDashboard,
  Package,
  Server,
  Settings,
  type LucideProps,
} from "lucide-solid";
import type { Component } from "solid-js";
import type { PageProps } from "./types";

type PageModule = {
  default: Component<PageProps>;
};

type PageDefinition = {
  id: string;
  label: string;
  icon: Component<LucideProps>;
  /**
   * Requests that Host retain this page's iframe after navigation.
   *
   * Primary navigation pages normally opt in; detail and short-lived workflow
   * pages should opt out. This is still a preference rather than ownership of
   * the iframe lifetime: Host expires documents that remain hidden beyond its
   * inactivity TTL. A retained page must pause background work while
   * `active()` is false and release all resources when disposed.
   */
  keepAlive: boolean;
  /**
   * Loads only this page's code inside the iframe document.
   *
   * Keep this as a dynamic import. Turning it into a static import would make
   * every iframe evaluate every page and weaken the document lifecycle
   * boundary used to release page-owned memory.
   */
  load: () => Promise<PageModule>;
};

/**
 * The single source of truth for Wasmeld Console pages.
 *
 * Add a page here after creating `src/pages/<id>/index.tsx`. Host navigation,
 * route validation, iframe titles, keep-alive policy and page module loading
 * are all derived from this registry, so they cannot drift independently.
 */
export const PAGE_DEFINITIONS = [
  {
    id: "overview",
    label: "运行概览",
    icon: LayoutDashboard,
    keepAlive: true,
    load: () => import("./overview"),
  },
  {
    id: "services",
    label: "服务版本",
    icon: Package,
    keepAlive: true,
    load: () => import("./services"),
  },
  {
    id: "instances",
    label: "运行实例",
    icon: Server,
    keepAlive: true,
    load: () => import("./instances"),
  },
  {
    id: "wit-packages",
    label: "WIT 包",
    icon: FileCode2,
    keepAlive: true,
    load: () => import("./wit-packages"),
  },
  {
    id: "activity",
    label: "调用记录",
    icon: History,
    keepAlive: true,
    load: () => import("./activity"),
  },
  {
    id: "settings",
    label: "运行设置",
    icon: Settings,
    keepAlive: true,
    load: () => import("./settings"),
  },
] as const satisfies readonly PageDefinition[];

export type View = (typeof PAGE_DEFINITIONS)[number]["id"];

export const VIEWS: readonly View[] = PAGE_DEFINITIONS.map((page) => page.id);

const PAGE_BY_ID = new Map<View, PageDefinition>(PAGE_DEFINITIONS.map((page) => [page.id, page]));

export function isView(value: string | null): value is View {
  return value !== null && PAGE_BY_ID.has(value as View);
}

export function pageDefinition(view: View): PageDefinition {
  // `View` is derived from PAGE_DEFINITIONS, so every valid value has an entry.
  return PAGE_BY_ID.get(view)!;
}
