import React from 'react';
import { afterEach, vi } from 'vitest';
import { cleanup } from '@testing-library/react';
import '@testing-library/jest-dom/vitest';

afterEach(() => {
  cleanup();
  localStorage.clear();
});

vi.stubGlobal('alert', vi.fn());
vi.stubGlobal('confirm', vi.fn(() => true));
URL.createObjectURL = vi.fn(() => 'blob:mock-url');
URL.revokeObjectURL = vi.fn();
HTMLAnchorElement.prototype.click = vi.fn();

function makeStageEvent(x = 120, y = 80) {
  const stage = {
    getPointerPosition: () => ({ x, y }),
    getRelativePointerPosition: () => ({ x, y }),
    scaleX: () => 1,
    x: () => 0,
    y: () => 0,
  };

  return {
    evt: { preventDefault: vi.fn(), deltaY: -1 },
    target: {
      getStage: () => stage,
    },
  };
}

vi.mock('react-konva', () => ({
  Stage: ({ children, onClick, onMouseDown, onMouseUp, onMouseMove, onWheel }: any) => (
    <div
      data-testid="konva-stage"
      onClick={() => onClick?.(makeStageEvent())}
      onMouseDown={() => onMouseDown?.(makeStageEvent())}
      onMouseUp={() => onMouseUp?.(makeStageEvent(260, 200))}
      onMouseMove={() => onMouseMove?.(makeStageEvent(180, 120))}
      onWheel={() => onWheel?.(makeStageEvent())}
    >
      {children}
    </div>
  ),
  Layer: ({ children }: any) => <div data-testid="konva-layer">{children}</div>,
  Group: ({ children }: any) => <div data-testid="konva-group">{children}</div>,
  Image: ({ image }: any) => <img data-testid="konva-image" alt="" src={image?.src || ''} />,
  Circle: (props: any) => <span data-testid="konva-circle" data-fill={props.fill} />,
  Rect: (props: any) => <span data-testid="konva-rect" data-width={props.width} />,
  Path: (props: any) => <span data-testid="konva-path" data-path={props.data} data-fill={props.fill} />,
}));

vi.mock('use-image', () => ({
  default: (src: string) => [
    {
      src,
      width: 640,
      height: 360,
      naturalWidth: 640,
      naturalHeight: 360,
    },
    'loaded',
  ],
}));
