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

test("local AIS track-symbol adapter renders immediately on first add", async () => {
  const listeners = new Map();
  const map = {
    getZoom: () => 10,
    on: (event, listener) => { listeners.set(event, listener); },
    off: (event) => { listeners.delete(event); },
  };
  const markerPrototype = {
    initialize(_latlng, options) { this.options = options; },
    onAdd(addedMap) { this._map = addedMap; this._icon = { innerHTML: "", style: {} }; },
    onRemove() { this._map = null; },
  };
  const L = {
    Marker: {
      prototype: markerPrototype,
      extend(definition) {
        return class TrackSymbol {
          constructor(latlng, options) {
            this.options = { ...definition.options };
            definition.initialize.call(this, latlng, options);
          }
        };
      },
    },
    Util: { extend: Object.assign },
    divIcon: (options) => options,
  };
  const source = await bundleEntry(new URL("../src/leaflet-ais-tracksymbol.ts", import.meta.url));
  new vm.Script(source).runInNewContext({ L, console });
  Object.assign(L.TrxAisTrackSymbol.prototype, {
    onAdd: markerPrototype.onAdd,
    onRemove: markerPrototype.onRemove,
  });
  // The fake `extend` above only models construction; copy plugin methods from
  // a second extend capture so the test exercises the generated adapter.
  let definition;
  L.Marker.extend = (value) => { definition = value; return L.TrxAisTrackSymbol; };
  new vm.Script(source).runInNewContext({ L, console });
  Object.assign(L.TrxAisTrackSymbol.prototype, definition);

  const symbol = L.trxAisTrackSymbol([52, 21], { heading: 90, speed: 12 });
  symbol.onAdd(map);
  assert.match(symbol._icon.innerHTML, /<svg/);
  assert.match(symbol._icon.innerHTML, /rotate\(90\)/);
  assert.equal(listeners.has("zoomend"), true);
});
