/**
 * Full editor bundle for WordPress. Loaded on demand by launcher.ts, from this
 * plugin's own folder (never a remote CDN — WP-003).
 */
import { openEditor } from "@pictureeditor/ui";
import type { SaveResult } from "@pictureeditor/adapters";
import { config, type OpenContext } from "./config";
import { WordPressAdapter, type AssociationResult } from "./adapter";

function open(id: number, ctx: OpenContext = {}) {
  const cfg = config();
  const adapter = new WordPressAdapter(cfg, { postId: ctx.postId ?? (cfg.contextPost || undefined), slot: ctx.slot });
  return new Promise<{ saved: SaveResult[]; association: AssociationResult | null }>((resolve) => {
    openEditor({
      adapter,
      assetId: String(id),
      strings: cfg.strings,
      // Drafts are scoped to this site + user so admins sharing a browser never see each other's.
      draftScope: `wp:${location.host}:${cfg.siteId}:${cfg.userId}`,
      assetUrl: (assetId) => cfg.mediaEditUrl + encodeURIComponent(assetId),
      onClose: ({ saved }) => resolve({ saved, association: adapter.lastAssociation }),
    });
  });
}

window.PictureEditorWP = { open };
