

export const createDrawingAreasLifecycleRuntime = (config: {
  drawingAreaRuntime: Map<string, any>;
  ensureRuntime: (id: string) => any;
  ensureZonePlaceholder: (id: string) => void;
  isUserLayer: (obj: any) => boolean;
  findBestZoneForObject: (obj: any) => any;
  registerObjectInZoneRuntime: (zoneId: string, obj: any) => void;
  applyClipForObject: (obj: any) => void;
}) => {
  const {
    drawingAreaRuntime,
    ensureRuntime,
    ensureZonePlaceholder,
    isUserLayer,
    findBestZoneForObject,
    registerObjectInZoneRuntime,
    applyClipForObject,
  } = config;

  const rebuildZoneRuntimeFromCanvas = (canvas: any, drawingZones: any[]) => {
    try {
      const ids = new Set((drawingZones ?? []).map((z: any) => z.id));
      for (const key of Array.from(drawingAreaRuntime.keys())) {
        if (!ids.has(key)) drawingAreaRuntime.delete(key);
      }
      for (const id of ids) {
        const rt = ensureRuntime(id);
        rt.objectIds = [];
      }
      const objs = canvas?.getObjects?.() ?? [];
      for (const o of objs) {
        if (!isUserLayer(o)) continue;
        const zid = String((o as any)._asukaZoneId ?? '') || null;
        const zone = zid && ids.has(zid) ? zid : (findBestZoneForObject(o)?.id ?? null);
        if (!zone) continue;
        try { (o as any)._asukaZoneId = zone; } catch {}
        try { registerObjectInZoneRuntime(zone, o); } catch {}
      }
      for (const id of ids) {
        try { ensureZonePlaceholder(id); } catch {}
      }
    } catch {}
  };

  const reapplyClipPathsForZone = (canvas: any, zoneId: string) => {
    if (!zoneId) return;
    try {
      const objs = canvas?.getObjects?.() ?? [];
      for (const o of objs) {
        if (String((o as any)._asukaZoneId ?? '') === zoneId) {
          try { applyClipForObject(o); } catch {}
        }
      }
      canvas?.requestRenderAll?.();
    } catch {}
  };

  return {
    rebuildZoneRuntimeFromCanvas,
    reapplyClipPathsForZone,
  };
};
