// fal-extras — local-only extensions injected by the proxy:
//   • "Save image…" / "Copy image URL" on SaveImage / PreviewImage right-click
//
// The MaskEditor option is provided natively by upstream ComfyUI (handled by
// our /api/upload/mask endpoint server-side), so we don't add a duplicate here.

import { app } from "/scripts/app.js";

function downloadUrl(url, filename) {
  const a = document.createElement("a");
  a.href = url;
  a.download = filename || (url.split("/").pop() || "image");
  a.target = "_blank";
  a.rel = "noopener";
  document.body.appendChild(a);
  a.click();
  a.remove();
}

function firstImageUrl(node) {
  if (node.imgs && node.imgs.length > 0 && node.imgs[0].src) return node.imgs[0].src;
  const imgs = node.images;
  if (Array.isArray(imgs) && imgs[0] && imgs[0].filename) {
    const img = imgs[0];
    const params = new URLSearchParams({
      filename: img.filename,
      type: img.type || "output",
      subfolder: img.subfolder || "",
    });
    return `/api/view?${params.toString()}`;
  }
  return null;
}

app.registerExtension({
  name: "fal.extras",
  async beforeRegisterNodeDef(nodeType, nodeData, app) {
    const name = nodeData.name;
    if (name !== "SaveImage" && name !== "PreviewImage") return;

    const orig = nodeType.prototype.getExtraMenuOptions;
    nodeType.prototype.getExtraMenuOptions = function (_, options) {
      const r = orig?.apply(this, arguments);
      const url = firstImageUrl(this);
      if (url) {
        options.unshift(
          {
            content: "Save image…",
            callback: () => downloadUrl(url, null),
          },
          {
            content: "Copy image URL",
            callback: async () => {
              try { await navigator.clipboard.writeText(url); } catch (_) {}
            },
          },
          null,
        );
      }
      return r;
    };
  },
});
