
import { fabric } from '../fabric';

export function createCurvedGuideRuntime(params: {
  canvas: any;
  isCurvedPathTextObject: (target: any) => boolean;
  getCurvedPathInnerText: (target: any) => any;
}) {
  const { canvas, isCurvedPathTextObject, getCurvedPathInnerText } = params;
  let curvedGuidePath: any = null;

  const hide = () => {
    if (curvedGuidePath) {
      try { canvas.remove(curvedGuidePath); } catch {}
      curvedGuidePath = null;
      try { canvas.requestRenderAll?.(); } catch { try { canvas.renderAll?.(); } catch {} }
    }
  };

  const show = (target: any) => {
    try {
      hide();
      if (!target || !isCurvedPathTextObject(target)) return;

      const inner = getCurvedPathInnerText(target);
      const p: any = (inner as any)?._asukaCurvedPath || (inner as any)?.path;
      const cmds = p?.path;
      if (!cmds) return;

      const guide = new fabric.Path(cmds, {
        fill: 'transparent',
        stroke: '#3b82f6',
        strokeWidth: 1,
        strokeDashArray: [6, 6],
        selectable: false,
        evented: false,
        excludeFromExport: true,
        objectCaching: false,
      });

      guide.set({
        left: target.left,
        top: target.top,
        angle: target.angle,
        scaleX: target.scaleX,
        scaleY: target.scaleY,
        originX: target.originX || 'left',
        originY: target.originY || 'top',
      });
      (guide as any)._asukaRole = 'curvedGuidePath';
      (guide as any).itemGroup = 'Tools';

      curvedGuidePath = guide;
      canvas.add(curvedGuidePath);
      canvas.bringToFront?.(curvedGuidePath);
      try { target.bringToFront?.(); } catch {}
      try { canvas.requestRenderAll?.(); } catch { try { canvas.renderAll?.(); } catch {} }
    } catch {}
  };

  const maybeUpdate = (event: any) => {
    const target = event?.target;
    if (!target || !curvedGuidePath) return;
    const active = canvas.getActiveObject?.();
    if (!active || active !== target) return;
    show(target);
  };

  const reset = () => {
    curvedGuidePath = null;
  };

  return {
    hide,
    show,
    maybeUpdate,
    reset,
    getCurrent: () => curvedGuidePath,
  };
}
