/**
 * Fabric.js v7 runtime patch for AsukaDesigner.
 *
 * The package targets Fabric 7 ESM and applies one stable patch:
 * force `setCoords()` right before controls render.
 */

import * as FabricNS from 'fabric';

export const fabric: any = FabricNS as any;

/**
 * Fix: after `loadFromJSON` + view switch, the first selection can try to render
 * controls before `oCoords/aCoords` are computed, leading to `undefined` points
 * and a crash when Fabric reads `.x`.
 *
 * Minimal solution: call `setCoords()` right before Fabric renders controls.
 */
(function installAsukaCoordsFix() {
  const fab: any = fabric;

  const candidates: any[] = [
    fab?.InteractiveFabricObject?.prototype,
    fab?.FabricObject?.prototype,
  ];

  for (const proto of candidates) {
    if (!proto || proto.__ASUKA_COORDS_FIX__) continue;
    if (typeof proto._renderControls !== 'function') continue;

    const orig = proto._renderControls;
    proto._renderControls = function (ctx: any, styleOverride?: any) {
      try {
        this.setCoords?.();
      } catch {}
      return orig.call(this, ctx, styleOverride);
    };

    proto.__ASUKA_COORDS_FIX__ = true;
  }
})();
