import {Container} from '@pixi/display';
import {Graphics} from '@pixi/graphics';
import {PixiComponent} from '@pixi/react';

import {useRadians} from '@/react/context/radians.js';

const tileSize = {x: 16, y: 16};

const TargetingGhostInternal = PixiComponent('TargetingGhost', {
  create: () => {
    // Solid target square.
    const target = new Graphics();
    target.lineStyle(1, 0xffffff);
    target.drawRect(0.5, 0.5, tileSize.x, tileSize.y);
    target.pivot = {x: tileSize.x / 2, y: tileSize.y / 2};
    // Inner spinny part.
    const targetInner = new Graphics();
    targetInner.lineStyle(3, 0x333333);
    targetInner.beginFill(0xdddddd);
    targetInner.pivot = {x: tileSize.x / 2, y: tileSize.y / 2};
    targetInner.drawRect(0, 0, tileSize.x, tileSize.y);
    targetInner.position.x = 0.5;
    targetInner.position.y = 0.5;
    // ...
    const container = new Container();
    container.alpha = 0.4;
    container.addChild(target, targetInner);
    return container;
  },
  applyProps: (container, oldProps, {x, y, radians}) => {
    container.position.set(x, y);
    container.children[1].rotation = radians / 4;
    container.children[1].scale.set(0.3 + 0.2 * (Math.cos(radians) + 1));
  },
})

export default function TargetingGhost({projected, tileLayer}) {
  const radians = useRadians();
  const ghosts = [];
  const {area} = tileLayer;
  for (const {x, y} of projected) {
    if (x < 0 || y < 0 || x >= area.x || y >= area.y) {
      continue;
    }
    ghosts.push(
      <TargetingGhostInternal
        key={JSON.stringify({x, y})}
        x={x * tileSize.x + tileSize.x * 0.5}
        y={y * tileSize.y + tileSize.y * 0.5}
        radians={radians / 2}
      />
    );
  }
  return <>{ghosts}</>;
}
