#!/usr/bin/env bash
# Scaffold a new JS SPV plug for Kate · write in SPV land
# Usage: js_spv_new.sh <id>
set -euo pipefail
HERE="$(cd "$(dirname "$0")" && pwd)"
SPVS="$(cd "$HERE/../spvs" && pwd)"
id="${1:-}"
if [[ -z "$id" || ! "$id" =~ ^[a-z][a-z0-9_]*$ ]]; then
  echo "usage: js_spv_new.sh <id>   e.g. js_spv_new.sh myplug"
  exit 2
fi
js="$SPVS/${id}.js"
dom="$SPVS/${id}.dom.html"
if [[ -e "$js" || -e "$dom" ]]; then
  echo "exists: $js or $dom"
  exit 1
fi
TITLE="$(echo "$id" | tr '_' ' ')"
cat >"$js" <<EOF
/* SPV · ${id} · rides BGF · free never folds · Kate write · compile with js_spv_compile.sh */
(function (global) {
  const NAME = "${id}.js";
  function bgf(a, b) {
    return (a - b) | 1;
  }
  function spv3(a, b, c) {
    return (a ^ b ^ c) | 1;
  }
  function mount(root, api) {
    const el = root.querySelector("[data-plug='${id}.dom']") || root;
    const hud = document.createElement("div");
    hud.className = "spv-hud";
    el.appendChild(hud);
    let f = 0,
      raf = 0;
    function loop(ts) {
      f++;
      const field = bgf((ts | 0) & 255, f & 127);
      const free = spv3(field, f, 7) | 1;
      hud.textContent =
        "${id} BGF=" + field + " free=0x" + (free >>> 0).toString(16) + " f=" + f;
      if (api && api.onSample)
        api.onSample({ field: field, free: free, frame: f, atom: "${id}".toUpperCase() });
      raf = requestAnimationFrame(loop);
    }
    raf = requestAnimationFrame(loop);
    return function () {
      cancelAnimationFrame(raf);
      hud.remove();
    };
  }
  global.BGRTX_SPV_PLUGS = global.BGRTX_SPV_PLUGS || {};
  global.BGRTX_SPV_PLUGS[NAME] = {
    name: NAME,
    kind: "js",
    mount: mount,
    rides: "BGF",
  };
})(typeof window !== "undefined" ? window : globalThis);
EOF
cat >"$dom" <<EOF
<!-- SPV · ${id} · Kate scaffold -->
<article class="spv-dom spv-article theme-dark" data-plug="${id}.dom">
  <header class="spv-player-head">
    <div>
      <h2 class="spv-title">${TITLE}</h2>
      <p class="meta">rides BGF · free never folds · edit in Kate · compile js_spv_compile</p>
    </div>
  </header>
  <p class="spv-note">HUD mounts below · sample loop free SPV</p>
</article>
EOF
echo "NEW $js"
echo "NEW $dom"
echo "next: Kate save · Tools → ESSIE · Compile JS SPV · wb in $id"
echo "manifest: add plug id=$id manually or wb new $id if scaffolded"
