import { I18N_JS_HREF } from "@wrnexus/i18n";
import type { ClientRuntimeDefinition } from "@wrnexus/plugin";
import { THEME_JS_HREF } from "@wrnexus/styles";
import type { RenderScript } from "@wrnexus/ssr";
import { runtimeScriptsForMarkup } from "./plugin-assets.ts";

/** Select browser runtimes from capabilities present in rendered markup. */
export function collectScripts(
  body: string,
  clientRuntimes: readonly ClientRuntimeDefinition[] = [],
  navigation: { mode?: "auto" | "client" | "document" } = {},
): RenderScript[] {
  const scripts: RenderScript[] = [];
  if (
    /\bdata-scope=/.test(body) ||
    /\bdata-wrnexus-csr=/.test(body) ||
    /\bdata-wrn-client-template=/.test(body) ||
    /\bdata-wrn-async=/.test(body)
  ) {
    scripts.push("/__wrnexus/reactive.js");
  }
  if (/\bdata-wrn-action=/.test(body)) scripts.push("/__wrnexus/actions.js");
  if (
    /\bdata-wire-theme-(toggle|set)\b/.test(body) ||
    /\bdata-wire-accent-(set|clear)\b/.test(body)
  ) {
    scripts.push(THEME_JS_HREF);
  }
  if (/\bdata-schema="[A-Za-z0-9_-]+"/.test(body)) {
    scripts.push("/__wrnexus/schemas.js", "/__wrnexus/validate.js");
  }
  if (/\bdata-wire-lang-set\b/.test(body) || /\bselect[^>]*\bdata-wire-lang\b/.test(body)) {
    scripts.push(I18N_JS_HREF);
  }
  if (/\bdata-room=/.test(body)) scripts.push("/__wrnexus/realtime.js");
  if (/\bdata-uploader\b/.test(body)) scripts.push("/__wrnexus/uploader.js");
  scripts.push(...runtimeScriptsForMarkup(body, clientRuntimes));

  const mode = navigation.mode ?? "auto";
  if (mode === "client" || (mode === "auto" && scripts.length > 0)) {
    scripts.unshift("/__wrnexus/nav.js");
  }
  return scripts;
}

/** Whether rendered markup needs the Capacitor/native browser bridge. */
export function usesMobileRuntime(body: string): boolean {
  return /\b(?:data-mobile-[\w-]+|data-native-(?:browser|mobile|only|requires|unsupported|options)|data-on-wrnexus-(?:browser|mobile)-[\w-]+)\b/.test(
    body,
  );
}
