import {memo, useEffect, useState} from 'react';

import {DamageTypes} from '@/ecs/components/vulnerable.js';

import styles from './damage.module.css';

const damageTypeMap = {
  [DamageTypes.PAIN]: styles.pain,
  [DamageTypes.HEALING]: styles.healing,
  [DamageTypes.MANA]: styles.mana,
};

function Damage({
  camera,
  damage,
  scale,
  zIndex,
}) {
  const [randomness] = useState({
    radians: Math.random() * (Math.PI / 16) - (Math.PI / 32),
    x: 1 * (Math.random() - 0.5),
    y: Math.random(),
  })
  useEffect(() => {
    const handle = setTimeout(() => {
      damage.onClose();
    }, 1_500);
    return () => {
      clearTimeout(handle);
    };
  }, [damage]);
  const {amount, position} = damage;
  return (
    <div
      className={styles.damage}
      style={{
        '--magnitude': Math.max(1, Math.floor(Math.log10(amount))),
        '--positionX': `${position.x * scale - camera.x}px`,
        '--positionY': `${position.y * scale - camera.y}px`,
        '--randomnessX': randomness.x,
        '--randomnessY': randomness.y,
        '--shimmer': damageTypeMap[damage.type],
        rotate: `${randomness.radians}rad`,
        zIndex,
      }}
    >
      <p>{amount}</p>
    </div>
  );
}

export default memo(Damage);
