// SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
//
// SPDX-License-Identifier: GPL-2.0-or-later

type PluginGroup = "digital-modes" | "map-data" | "map" | "statistics" | "bookmarks" | "recorder" | "settings";

const pluginGroups: Readonly<Record<PluginGroup, readonly string[]>> = {
  "digital-modes": ["/ft8.js", "/ft4.js", "/ft2.js", "/wspr.js", "/cw.js", "/background-decode.js", "/sat.js", "/wefax.js"],
  "map-data": ["/map-core.js", "/ais.js", "/vdes.js", "/aprs.js", "/hf-aprs.js"],
  map: ["/map-core.js", "/ais.js", "/vdes.js", "/aprs.js", "/hf-aprs.js", "/sat.js", "/sat-scheduler.js"],
  statistics: ["/map-core.js"],
  bookmarks: ["/bookmarks.js"],
  recorder: [],
  settings: ["/vchan.js", "/scheduler.js"],
};

const loaded = new Set<string>();
const loading = new Map<string, Promise<void>>();
async function loadPlugin(path: string): Promise<void> {
  if (loaded.has(path)) return;
  const pending = loading.get(path);
  if (pending) return pending;
  const request = import(path).then(() => {
    loaded.add(path);
    loading.delete(path);
  }).catch((error: unknown) => {
    loading.delete(path);
    throw new Error(`Failed to load plugin module: ${path}`, { cause: error });
  });
  loading.set(path, request);
  return request;
}

async function loadPlugins(group: string): Promise<void> {
  if (!(group in pluginGroups)) return;
  for (const path of pluginGroups[group as PluginGroup]) await loadPlugin(path);
}

export async function loadEagerPlugins(): Promise<void> {
  await Promise.all(["digital-modes", "bookmarks", "settings"].map(loadPlugins));
}

export async function loadPluginsForTab(tab: string): Promise<void> {
  await loadPlugins(tab);
}
