import { FONT_SMALL } from '../kanbans/Const';
import { EndlessCanvas } from './EndlessCanvas';

export default (scene: EndlessCanvas) => {
  const ZOOM_MAX = 2;
  const ZOOM_MIN = 0.1;
  const ZOOM_STEP = 0.1;
  const ZOOM_SENSITIVITY = 0.0003;
  let zoomText: Phaser.GameObjects.Text;

  const zoomButtonsBackground = scene.add
    .image(
      scene.cameras.main.width - 170,
      scene.cameras.main.height - 31,
      'iconZ',
    )
    .setScale(1.25);
  zoomButtonsBackground.setInteractive({ cursor: 'pointer' });

  function createZoomButton(
    x: number,
    y: number,
    texture: string,
    zoomChange: number,
  ) {
    const button = scene.add.image(x, y, texture).setScale(0.15);
    button.setInteractive({ cursor: 'pointer' });
    button.on('pointerdown', () => updateZoom(zoomChange));
    return button;
  }

  function updateZoom(change: number) {
    let newZoom = scene.cameras.main.zoom + change;
    newZoom = Phaser.Math.Clamp(newZoom, ZOOM_MIN, ZOOM_MAX);
    scene.cameras.main.zoom = newZoom;
    updateZoomPercentage();
  }

  function updateZoomPercentage() {
    zoomText.setText(`${(scene.cameras.main.zoom * 100).toFixed(0)}%`);
  }

  function updateButtonPositions() {
    zoomButtonsBackground.y = scene.cameras.main.height - 31;
    zoomText.y = scene.cameras.main.height - 38;
    zoomPlusButton.y = scene.cameras.main.height - 30;
    zoomMinusButton.y = scene.cameras.main.height - 30;
    fullscreenButton.y = scene.cameras.main.height - 30;
  }

  zoomText = scene.add.text(
    scene.cameras.main.width - 190,
    scene.cameras.main.height - 38,
    `${(scene.cameras.main.zoom * 100).toFixed(0)}%`,
    { fontSize: FONT_SMALL, color: '#000' },
  );

  const zoomPlusButton = createZoomButton(
    scene.cameras.main.width - 210,
    scene.cameras.main.height - 30,
    'plus',
    ZOOM_STEP,
  );

  const zoomMinusButton = createZoomButton(
    scene.cameras.main.width - 125,
    scene.cameras.main.height - 30,
    'minus',
    -ZOOM_STEP,
  );

  // Добавляем кнопку Fullscreen
  const fullscreenButton = scene.add
    .image(
      scene.cameras.main.width - 80,
      scene.cameras.main.height - 30,
      'fullscreen',
    )
    .setScale(0.15);
  fullscreenButton.setInteractive({ cursor: 'pointer' });
  fullscreenButton.on('pointerdown', toggleFullscreen);

  function toggleFullscreen() {
    if (scene.scale.isFullscreen) {
      scene.scale.stopFullscreen();
    } else {
      scene.scale.startFullscreen();
    }
    updateButtonPositions();
  }

  scene.input.on('wheel', (pointer, gameObjects, deltaX, deltaY) => {
    //@ts-ignore
    if (scene.keys.ctrl.isDown) {
      updateZoom(deltaY * ZOOM_SENSITIVITY);
    }
  });

  scene.cameras.main.ignore([
    zoomButtonsBackground,
    zoomPlusButton,
    zoomMinusButton,
    zoomText,
    fullscreenButton,
  ]);

  // Обработчик события изменения размера окна
  window.addEventListener('resize', () => {
    updateButtonPositions();
  });
};
