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

import assert from "node:assert/strict";
import test from "node:test";
import vm from "node:vm";
import { bundleEntry } from "./bundle-entry.mjs";
import { createHost } from "./host-fixture.mjs";

test("FT2 entry normalizes audio offsets and registers typed callbacks", async () => {
  let barRenderer;
  const mapMessages = [];
  const window = {
    ...createHost(),
    ft8BaseHz: 14_074_000,
    trxUi: { confirm: async () => true },
    ft8ExtractAllGrids: () => ["JO91"],
    ft8ExtractLikelyCallsign: () => "SP0ABC",
    mapAddLocator: (...args) => { mapMessages.push(args); },
    registerFt8FamilyBarRenderer: (_decoder, renderer) => { barRenderer = renderer; },
    fmtTime: () => "12:00",
    setInterval() { return 1; },
  };
  const context = vm.createContext({
    window,
    document: { getElementById: () => null, createElement: () => ({ dataset: {} }), createDocumentFragment: () => ({ appendChild() {} }) },
    Date,
    Number,
    String,
    Array,
    console,
  });
  const runtime = await bundleEntry(new URL("../src/plugin-runtime.ts", import.meta.url));
  const source = await bundleEntry(new URL("../src/plugins/ft2.ts", import.meta.url));
  new vm.Script(runtime).runInContext(context);
  new vm.Script(source).runInContext(context);

  window.trxPluginRuntime.dispatch("ft2", { message: "CQ SP0ABC JO91", freq_hz: 1_250, ts_ms: Date.now(), snr_db: -8 });
  assert.equal(mapMessages.length, 1);
  assert.equal(mapMessages[0][4].freq_hz, 14_075_250);
  const bar = barRenderer();
  assert.equal(bar.count, 1);
  assert.match(bar.html, /CQ SP0ABC/);
  assert.match(bar.html, /JO91/);
});

test("FT8 entry installs shared parsing without relying on script globals", async () => {
  const forwarded = [];
  const window = {
    ...createHost(),
    ft8BaseHz: 7_074_000,
    trxUi: { confirm: async () => true },
    mapAddLocator: (...args) => { forwarded.push(args); },
    setInterval() { return 1; },
  };
  const context = vm.createContext({
    window,
    document: { getElementById: () => null, createElement: () => ({ dataset: {} }), createDocumentFragment: () => ({ appendChild() {} }) },
    Date,
    Number,
    String,
    Array,
    Set,
    console,
  });
  const runtime = await bundleEntry(new URL("../src/plugin-runtime.ts", import.meta.url));
  const source = await bundleEntry(new URL("../src/plugins/ft8.ts", import.meta.url));
  new vm.Script(runtime).runInContext(context);
  new vm.Script(source).runInContext(context);

  const details = window.ft8ExtractLocatorDetails("K1ABC SP0ABC JO91");
  assert.equal(details[0].source, "SP0ABC");
  assert.equal(details[0].target, "K1ABC");
  window.trxPluginRuntime.dispatch("ft8", { message: "K1ABC SP0ABC JO91", freq_hz: 500, ts_ms: Date.now() });
  assert.equal(forwarded[0][4].freq_hz, 7_074_500);
});
