import './style.css';
import { Application, Assets, Container, Graphics, Sprite } from 'pixi.js';
import {
  BALL_INITIAL_ANGLE,
  BALL_RADIUS,
  BALL_SPEED,
  BRICK_COLUMN_AMOUNT,
  BRICK_HEIGHT,
  BRICK_ROW_AMOUNT,
  BRICK_WIDTH,
  CONTAINER_HEIGHT,
  CONTAINER_WIDTH,
  PADDLE_HEIGHT,
  PADDLE_WIDTH,
} from './config';
import { LEVELS } from './const/levels';
import { Game } from './game';
import { createGameView, managePerkViewsLifetime, rebuildBrickViews, syncronizeViewsWithGame } from './view';

(async () => {
  // Create a new application
  const app = new Application();

  // Initialize the application
  await app.init({ background: '#1099bb', width: CONTAINER_WIDTH, height: CONTAINER_HEIGHT });

  // Append the application canvas to the document body
  document.body.appendChild(app.canvas);

  // Create and add a container to the stage
  const container = new Container({
    eventMode: 'static',
    hitArea: app.screen,
  });

  container.x = 0;
  container.y = 0;

  app.stage.addChild(container);

  const textures = await Assets.load([
    '/sprites/fire_ball_1.png',
    '/sprites/background_1.png',
    '/sprites/paddle.png',
    '/sprites/block_1.png',
    '/sprites/block_2.png',
    '/sprites/block_3.png',
    '/sprites/perk_1.png',
    '/sprites/perk_2.png',
    '/sprites/perk_3.png',
    '/sprites/perk_4.png',
  ]);

  const game = new Game(LEVELS);
  const views = createGameView(game, container, textures);
  let currentLevel = game.currentLevel;

  container.on('pointermove', (event) => {
    const localPosition = container.toLocal(event.global);
    game.paddle.moveTo(localPosition.x, 0, CONTAINER_WIDTH);
  });

  container.on('pointerdown', () => {
    game.ball.launch();
  });

  app.ticker.add((time) => {
    game.update(time.deltaTime);

    if (game.currentLevel !== currentLevel) {
      rebuildBrickViews(views, game, container, textures);
      currentLevel = game.currentLevel;
    }
    managePerkViewsLifetime(views, game, container, textures);
    syncronizeViewsWithGame(views, game);
  });
})();
