<template>
  <div id="phaser-container"></div>
</template>

<script lang="ts">
//@ts-nocheck
import Phaser from 'phaser';
// import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin';

// Определяем основные цвета для интерфейса
const COLOR_PRIMARY = 0xcccccc;
const COLOR_LIGHT = 0x7b5e57;
const COLOR_DARK = 0x444444;

// Функция для генерации случайных чисел
const Random: (min: number, max: number) => number = Phaser.Math.Between;

// Определение основного класса сцены
class Demo extends Phaser.Scene {
  constructor() {
    super({
      key: 'examples',
    });
  }

  preload(): void {
    this.load.scenePlugin(
      'rexuiplugin',
      'rexuiplugin.min.js',
      'rexUI',
      'rexUI',
    );
  }

  create(): void {
    const scrollablePanel = this.rexUI.add
      .scrollablePanel({
        x: 400,
        y: 300,
        width: 400,
        height: 400,
        scrollMode: 2,
        background: this.rexUI.add
          .roundRectangle(0, 0, 2, 2, 10, COLOR_PRIMARY)
          .setStrokeStyle(1, COLOR_DARK),
        panel: {
          child: CreatePanel(this),
          mask: {
            padding: 1,
          },
        },
        sliderX: {
          track: this.rexUI.add.roundRectangle(0, 0, 20, 10, 10, COLOR_DARK),
          thumb: this.rexUI.add.roundRectangle(0, 0, 0, 0, 13, COLOR_LIGHT),
          hideUnscrollableSlider: true,
          input: 'click',
        },
        sliderY: {
          track: this.rexUI.add.roundRectangle(0, 0, 20, 10, 10, COLOR_DARK),
          thumb: this.rexUI.add.roundRectangle(0, 0, 0, 0, 13, COLOR_LIGHT),
          hideUnscrollableSlider: true,
          input: 'click',
        },
        header: CreateHeader(this),
        space: {
          left: 10,
          right: 10,
          top: 10,
          bottom: 10,
          panel: 10,
          sliderX: 10,
          sliderY: 10,
        },
        scrollerX: false,
        scrollerY: false,
      })
      .setDraggable('header') // Draggable-header
      .layout();

    AddResizeController(scrollablePanel);

    this.add.text(0, 580, 'Drag-drop any item to any sizer');
  }

  // update(): void {}
}

const CreatePanel = (scene: Phaser.Scene): Phaser.GameObjects.Container => {
  const sizer0 = CreateVerticalPanel(scene, 12).setPosition(150, 0).layout();
  const sizer1 = CreateVerticalPanel(scene, 8).setPosition(300, 0).layout();
  const sizer2 = CreateVerticalPanel(scene, 0).setPosition(450, 0).layout();
  const sizers = [sizer0, sizer1, sizer2];
  sizers.forEach(function (sizer) {
    sizer.setInteractive({ dropZone: true });
    SetDragable(sizer.getElement('items'));
  });

  const mainSizer = scene.rexUI.add
    .sizer({
      orientation: 'x',
      space: { item: 10 },
    })
    .add(sizer0)
    .add(sizer1)
    .add(sizer2);

  return mainSizer;
};

const CreateVerticalPanel = (
  scene: Phaser.Scene,
  itemCount?: number,
): Phaser.GameObjects.Container => {
  if (itemCount === undefined) {
    itemCount = 0;
  }

  let sizer = scene.rexUI.add
    .sizer({
      width: 120,
      height: 500,
      orientation: 'y',
      space: { left: 6, right: 6, top: 6, bottom: 6, item: 6 },
    })
    .setDepth(-1)
    .addBackground(scene.rexUI.add.roundRectangle(0, 0, 0, 0, 10).setDepth(-1));

  for (let i = 0; i < itemCount; i++) {
    sizer.add(CreateLabel(scene, i.toString()), {
      expand: true,
    });
  }
  return sizer;
};

const CreateLabel = (
  scene: Phaser.Scene,
  text: string,
): Phaser.GameObjects.Container => {
  const label = scene.rexUI.add.label({
    background: scene.rexUI.add.roundRectangle(0, 0, 0, 0, 10, COLOR_LIGHT),
    text: scene.add.text(0, 0, text, {
      fontSize: 18,
    }),
    align: 'center',
    space: {
      left: 5,
      right: 5,
      top: 5,
      bottom: 5,
    },
  });
  return label;
};

const SetDragable = (items: Phaser.GameObjects.GameObject[]): void => {
  items.forEach(function (item) {
    item
      .setInteractive({ draggable: true })
      .on('dragstart', function (pointer, dragX, dragY) {
        item.setData({ startX: item.x, startY: item.y });
      })
      .on('drag', function (pointer, dragX, dragY) {
        item.setPosition(dragX, dragY);
      })
      .on('dragend', function (pointer, dragX, dragY, dropped) {
        if (dropped) {
          return;
        }
        item.moveTo({
          x: item.getData('startX'),
          y: item.getData('startY'),
          speed: 300,
        });
      })
      .on('drop', function (pointer, target) {
        var parent = item.getParentSizer();
        parent.remove(item);
        ArrangeItems(parent);

        target.insertAtPosition(pointer.x, pointer.y, item, {
          expand: true,
        });
        ArrangeItems(target);
      });
  });
};

const ArrangeItems = (panel: Phaser.GameObjects.Container): void => {
  const items = panel.getElement('items');
  items.forEach(function (item) {
    item.setData({ startX: item.x, startY: item.y });
  });
  panel.layout();
  items.forEach(function (item) {
    item.moveFrom({
      x: item.getData('startX'),
      y: item.getData('startY'),
      speed: 300,
    });
  });
};

const AddResizeController = (sizer: Phaser.GameObjects.Container): void => {
  const scene = sizer.scene;

  const bottomRighterController = scene.add.rectangle(
    sizer.right,
    sizer.bottom,
    30,
    30,
    0x333333,
  );

  bottomRighterController
    .setInteractive({ draggable: true })
    .on('drag', function (pointer, dragX, dragY) {
      const topX = sizer.left,
        topY = sizer.top;
      const width = dragX - topX,
        height = dragY - topY;

      sizer.setChildPosition(bottomRighterController, dragX, dragY);

      sizer.setMinSize(width, height).layout();

      sizer.left = topX;
      sizer.top = topY;
    });

  sizer.pin(bottomRighterController);
};

const CreateHeader = function (
  scene: Phaser.Scene,
): Phaser.GameObjects.Container {
  const sizer = scene.rexUI.add
    .sizer({
      orientation: 'x',
    })
    .addBackground(scene.rexUI.add.roundRectangle(0, 0, 20, 20, 0, COLOR_DARK));

  const headerLabel = scene.rexUI.add.label({
    text: scene.add.text(0, 0, 'Header'),
  });

  const dropDownButton = CreateDropDownList(scene);

  sizer
    .add(headerLabel, { proportion: 1, expand: true })
    .add(dropDownButton, { proportion: 0, expand: true });

  return sizer;
};

const CreateDropDownList = function (
  scene: Phaser.Scene,
): Phaser.GameObjects.Text {
  const options = ['Добавить колонку', 'Переименовать доску'];
  const maxTextSize = GetMaxTextObjectSize(scene, options);
  const label = scene.rexUI.add
    .label({
      background: scene.rexUI.add
        .roundRectangle(0, 0, 2, 2, 0, COLOR_PRIMARY)
        .setAlpha(0),
      text: CreateTextObject(scene, '...').setFixedSize(
        maxTextSize.width,
        maxTextSize.height,
      ),
      space: {
        left: 10,
        right: 10,
        top: 10,
        bottom: 10,
        icon: 10,
      },
    })
    .setData('value', '');

  let menu: Phaser.GameObjects.Container | undefined;

  scene.rexUI.add.click(label).on('click', () => {
    if (!menu || !menu.scene) {
      const menuX = label.getElement('text').getTopLeft().x;
      const menuY = label.bottom;
      menu = CreatePopupList(scene, menuX, menuY, options, function (button) {
        console.log('Click', button.text); // Добавленный console.log
        if (button.text === 'Добавить колонку') {
          // Ваш код для добавления новой колонки
        } else if (button.text === 'Переименовать доску') {
          // Ваш код для переименования доски
        }
        menu?.collapse();
        menu = undefined;
      });
    } else {
      menu.collapse();
      menu = undefined;
    }
  });

  return label;
};

const CreateModalLabel = (
  scene: Phaser.Scene,
  text: string,
): Phaser.GameObjects.Container => {
  const normalBackground = scene.rexUI.add.roundRectangle(
    0,
    0,
    0,
    0,
    10,
    0xffffff,
    0.0,
  );
  normalBackground.setStrokeStyle(2, 0x000000); // Чёрная обводка

  const hoverBackground = scene.rexUI.add.roundRectangle(
    0,
    0,
    0,
    0,
    10,
    0xffffff,
    0.0,
  );
  hoverBackground.setStrokeStyle(2, 0x000000); // Чёрная обводка

  const label = scene.rexUI.add
    .label({
      background: normalBackground,
      text: scene.add.text(0, 0, text, {
        fontSize: 18,
        color: '#000000', // Чёрный текст
      }),
      align: 'center',
      space: {
        left: 5,
        right: 5,
        top: 5,
        bottom: 5,
      },
    })
    .on('button.over', function (button, groupName, index, pointer, event) {
      button.getElement('background').destroy();
      button.setElement('background', hoverBackground);
    })
    .on('button.out', function (button, groupName, index, pointer, event) {
      button.getElement('background').destroy();
      button.setElement('background', normalBackground);
    });

  return label;
};

const CreateModalBoard = (scene: Phaser.Scene): any => {
  const content = '1';

  const textArea = scene.rexUI.add
    .textAreaInput({
      x: 400,
      y: 300,
      width: 280,
      height: 20,

      background: scene.rexUI.add.roundRectangle(0, 0, 2, 2, 0, COLOR_PRIMARY),

      text: {
        background: {
          stroke: 'black',
          // 'focus.stroke': 'red',
        },

        style: {
          fontSize: 20,
          backgroundBottomY: 1,
          backgroundHeight: 20,
          'cursor.color': 'black',
          'cursor.backgroundColor': 'white',
          color: '#000000',
        },
      },

      space: {
        left: 0,
        right: 0,
        top: 0,
        bottom: 0,
        text: 10,
        header: 0,
        footer: 0,
      },

      mouseWheelScroller: {
        focus: false,
        speed: 0.1,
      },

      content: content,
    })
    .layout()
    .on('textchange', function (text: string) {
      console.log(`Content: '${text}'`);
    });

  textArea.setDepth(2);

  const separator = scene.add.rectangle(0, 0, 280, 2, 0x000000);

  const dialog = scene.rexUI.add
    .dialog({
      background: scene.rexUI.add
        .roundRectangle(0, 0, 100, 100, 20, 0xffffff)
        .setStrokeStyle(2, 0x000000),

      title: scene.rexUI.add.label({
        text: scene.add.text(0, 0, 'Редактирование объекта', {
          fontSize: '24px',
          color: '#000000',
        }),
        space: {
          left: 15,
          right: 15,
          top: 10,
          bottom: 10,
        },
      }),

      content: textArea,

      actions: [
        CreateModalLabel(scene, 'Отменить'),
        CreateModalLabel(scene, 'Сохранить'),
      ],

      space: {
        title: 25,
        content: 25,
        action: 15,

        left: 20,
        right: 20,
        top: 20,
        bottom: 20,
      },

      align: {
        actions: 'right',
      },

      expand: {
        content: false,
      },
    })
    .on('button.over', function (button, groupName, index, pointer, event) {
      button.getElement('background').setStrokeStyle(1, 0xffffff);
    })
    .on('button.out', function (button, groupName, index, pointer, event) {
      button.getElement('background').setStrokeStyle();
    });

  return dialog;
};

const CreateModalColumn = (scene: Phaser.Scene): any => {
  const content = '1';

  const textArea = scene.rexUI.add
    .textAreaInput({
      x: 400,
      y: 300,
      width: 280,
      height: 20,

      background: scene.rexUI.add.roundRectangle(0, 0, 2, 2, 0, COLOR_PRIMARY),

      text: {
        background: {
          stroke: 'black',
          // 'focus.stroke': 'red',
        },

        style: {
          fontSize: 20,
          backgroundBottomY: 1,
          backgroundHeight: 20,
          'cursor.color': 'black',
          'cursor.backgroundColor': 'white',
          color: '#000000',
        },
      },

      space: {
        left: 0,
        right: 0,
        top: 0,
        bottom: 0,
        text: 10,
        header: 0,
        footer: 0,
      },

      mouseWheelScroller: {
        focus: false,
        speed: 0.1,
      },

      content: content,
    })
    .layout()
    .on('textchange', function (text: string) {
      console.log(`Content: '${text}'`);
    });

  textArea.setDepth(2);

  const separator = scene.add.rectangle(0, 0, 280, 2, 0x000000);

  const dialog = scene.rexUI.add
    .dialog({
      background: scene.rexUI.add
        .roundRectangle(0, 0, 100, 100, 20, 0xffffff)
        .setStrokeStyle(2, 0x000000),

      title: scene.rexUI.add.label({
        text: scene.add.text(0, 0, 'Редактирование объекта', {
          fontSize: '24px',
          color: '#000000',
        }),
        space: {
          left: 15,
          right: 15,
          top: 10,
          bottom: 10,
        },
      }),

      content: textArea,

      actions: [
        CreateModalLabel(scene, 'Отменить'),
        CreateModalLabel(scene, 'Сохранить'),
      ],

      space: {
        title: 25,
        content: 25,
        action: 15,

        left: 20,
        right: 20,
        top: 20,
        bottom: 20,
      },

      align: {
        actions: 'right',
      },

      expand: {
        content: false,
      },
    })
    .on('button.over', function (button, groupName, index, pointer, event) {
      button.getElement('background').setStrokeStyle(1, 0xffffff);
    })
    .on('button.out', function (button, groupName, index, pointer, event) {
      button.getElement('background').setStrokeStyle();
    });

  return dialog;
};

const CreatePopupList = function (
  scene: Phaser.Scene,
  x: number,
  y: number,
  options: string[],
  onClick: (button: Phaser.GameObjects.Text) => void,
): Phaser.GameObjects.Container {
  const items = options.map((option) => ({ label: option }));
  const menu = scene.rexUI.add.menu({
    x: x,
    y: y,
    orientation: 'y',
    items: items,
    createButtonCallback: (item, i, options) => {
      return scene.rexUI.add.label({
        background: scene.rexUI.add.roundRectangle(0, 0, 2, 2, 0, COLOR_DARK),
        text: CreateTextObject(scene, item.label),
        space: {
          left: 10,
          right: 10,
          top: 10,
          bottom: 10,
          icon: 10,
        },
      });
    },
    easeIn: {
      duration: 500,
      orientation: 'y',
    },
    easeOut: {
      duration: 100,
      orientation: 'y',
    },
  });

  menu.on('button.click', function (button) {
    if (button.text === 'Добавить колонку') {
      CreateModalColumn(scene)
        .setPosition(400, 300)
        .layout()
        .modalPromise({
          manaulClose: true,
          duration: {
            in: 500,
            out: 500,
          },
        })
        .then(function (data) {
          console.log(data);
        });
    } else if (button.text === 'Переименовать доску') {
      CreateModalBoard(scene)
        .setPosition(400, 300)
        .layout()
        .modalPromise({
          manaulClose: true,
          duration: {
            in: 500,
            out: 500,
          },
        })
        .then(function (data) {
          console.log(data);
        });
    }
    menu.collapse();
  });

  return menu;
};

const GetMaxTextObjectSize = function (
  scene: Phaser.Scene,
  contentArray: string[],
): { width: number; height: number } {
  const textObject = CreateTextObject(scene, '');
  let width = 0,
    height = 0;
  for (const content of contentArray) {
    textObject.text = content;
    width = Math.max(textObject.width, width);
    height = Math.max(textObject.height, height);
  }
  textObject.destroy();
  return { width, height };
};

const CreateTextObject = function (
  scene: Phaser.Scene,
  text: string,
): Phaser.GameObjects.Text {
  return scene.add.text(0, 0, text, {
    fontSize: '20px',
  });
};

const config: Phaser.Types.Core.GameConfig = {
  type: Phaser.AUTO,
  scale: {
    // parent: 'phaser-example',
    mode: Phaser.Scale.FIT,
    autoCenter: Phaser.Scale.CENTER_BOTH,
    width: 1280,
    height: 720,
    parent: 'phaser-container',
  },
  backgroundColor: '#FFFFFF',
  plugins: {
    // scene: [
    //   {
    //     key: 'rexUI',
    //     plugin: UIPlugin,
    //     mapping: 'rexUI',
    //   },
    // ],
  },
  scene: Demo,
};

export default {
  name: 'YourComponentName',
  mounted() {
    const game = new Phaser.Game(config);
  },
};
</script>

<style></style>
