// 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";

class ElementFixture {
  constructor() { this.children = []; this.textContent = ""; this.style = {}; this.classList = { toggle() {} }; }
  appendChild(child) { this.children.push(child); return child; }
  removeChild(child) { this.children.splice(this.children.indexOf(child), 1); }
  get firstChild() { return this.children[0] ?? null; }
  get lastElementChild() { return this.children.at(-1) ?? null; }
  get scrollHeight() { return this.children.length; }
}

test("CW entry appends server-decoded text and registers lifecycle callbacks", async () => {
  const output = new ElementFixture();
  const status = new ElementFixture();
  const elements = new Map([["cw-output", output], ["cw-status", status]]);
  const window = { ...createHost(), trxUi: { confirm: async () => true }, addEventListener() {} };
  const context = vm.createContext({
    window,
    document: {
      documentElement: {},
      getElementById: (id) => elements.get(id) ?? null,
      querySelector: () => null,
      createElement: () => new ElementFixture(),
    },
    requestAnimationFrame(callback) { callback(); return 1; },
    getComputedStyle: () => ({ getPropertyValue: () => "" }),
    Date,
    Number,
    String,
    Math,
    console,
  });
  const runtime = await bundleEntry(new URL("../src/plugin-runtime.ts", import.meta.url));
  const source = await bundleEntry(new URL("../src/plugins/cw.ts", import.meta.url));
  new vm.Script(runtime).runInContext(context);
  new vm.Script(source).runInContext(context);

  window.trxPluginRuntime.dispatch("cw", { text: "CQ", wpm: 18, tone_hz: 700, signal_on: true });
  assert.equal(status.textContent, "Receiving");
  assert.equal(output.children.length, 1);
  assert.equal(output.children[0].textContent, "CQ");
  assert.equal(window.onServerCw, undefined);
  assert.equal(window.trxPluginRuntime.hasDecoder("cw"), true);
});
