import assert from "node:assert/strict";

import { mount } from "./card_runtime_fixture_card.mjs";

function createFakeRoot() {
  return {
    dataset: {},
    innerHTML: "",
  };
}

async function main() {
  const root = createFakeRoot();
  const liveContentCalls = [];
  const refreshHandlers = [];

  const host = {
    setLiveContent(value) {
      liveContentCalls.push(value);
    },
    setRefreshHandler(handler) {
      refreshHandlers.push(handler);
    },
  };

  const mounted = mount({
    root,
    state: { title: "alpha" },
    host,
  });

  assert.equal(typeof mounted?.update, "function");
  assert.equal(typeof mounted?.destroy, "function");
  assert.match(root.innerHTML, /alpha/);
  assert.deepEqual(liveContentCalls.at(-1), { phase: "mount", title: "alpha" });
  assert.equal(typeof refreshHandlers.at(-1), "function");

  refreshHandlers.at(-1)?.();
  assert.equal(root.dataset.refreshed, "1");

  mounted.update({
    root,
    state: { title: "beta" },
    host,
  });
  assert.match(root.innerHTML, /beta/);
  assert.deepEqual(liveContentCalls.at(-1), { phase: "update", title: "beta" });

  mounted.destroy();
  assert.equal(root.innerHTML, "");
  assert.equal(root.dataset.destroyed, "1");
  assert.equal(refreshHandlers.at(-1), null);

  console.log("card runtime fixture ok");
}

await main();
