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

export function createSnapLinesRuntime(params: {
  canvas: any;
  getZoneRect: () => { left: number; top: number; width: number; height: number };
}) {
  const { canvas, getZoneRect } = params;
  let vertical: any = null;
  let horizontal: any = null;

  const ensure = () => {
    const zone = getZoneRect();
    if (!vertical) {
      vertical = new fabric.Line([0, zone.top, 0, zone.top + zone.height], {
        stroke: '#3b82f6',
        strokeWidth: 1,
        selectable: false,
        evented: false,
        visible: false,
        hasControls: false,
        hasBorders: false,
        excludeFromExport: true,
      });
      (vertical as any)._asukaRole = 'snapVertical';
      (vertical as any).itemGroup = 'Tools';
      canvas.add(vertical);
    }
    if (!horizontal) {
      horizontal = new fabric.Line([zone.left, 0, zone.left + zone.width, 0], {
        stroke: '#3b82f6',
        strokeWidth: 1,
        selectable: false,
        evented: false,
        visible: false,
        hasControls: false,
        hasBorders: false,
        excludeFromExport: true,
      });
      (horizontal as any)._asukaRole = 'snapHorizontal';
      (horizontal as any).itemGroup = 'Tools';
      canvas.add(horizontal);
    }
  };

  const hide = () => {
    if (vertical) vertical.visible = false;
    if (horizontal) horizontal.visible = false;
  };

  const show = (state: {
    x?: { value: number; span?: { from: number; to: number } } | null;
    y?: { value: number; span?: { from: number; to: number } } | null;
  }) => {
    ensure();
    const zone = getZoneRect();
    if (state?.x && vertical) {
      const span = state.x.span ?? { from: zone.top, to: zone.top + zone.height };
      vertical.set({ x1: state.x.value, x2: state.x.value, y1: span.from, y2: span.to, visible: true });
    } else if (vertical) {
      vertical.visible = false;
    }
    if (state?.y && horizontal) {
      const span = state.y.span ?? { from: zone.left, to: zone.left + zone.width };
      horizontal.set({ x1: span.from, x2: span.to, y1: state.y.value, y2: state.y.value, visible: true });
    } else if (horizontal) {
      horizontal.visible = false;
    }
  };

  const remove = () => {
    try {
      if (vertical) canvas.remove(vertical);
      if (horizontal) canvas.remove(horizontal);
    } catch {}
    vertical = null;
    horizontal = null;
  };

  const reset = () => {
    vertical = null;
    horizontal = null;
  };

  return {
    ensure,
    hide,
    show,
    remove,
    reset,
    getState: () => ({ vertical, horizontal }),
  };
}
