import useCommonAudio from '@/hooks/useCommonAudio'

interface Point {
  x: number
  y: number
}

export default function useStarAnimate() {
  const screenWidthRatio = window.innerWidth / 1920
  const starRect = ref()
  const starX = computed(() =>
    starRect.value ? starRect.value.top - 600 * screenWidthRatio + 'px' : 0,
  )
  const starY = computed(() =>
    starRect.value
      ? starRect.value.left - (300 * screenWidthRatio) / 2 + starRect.value.width / 2 + 'px'
      : 0,
  )
  const sound = useCommonAudio(true)

  // 坐标系是以左上角为原点，向下为y轴正方向，向右为x轴正方向
  const flyToRect = ref()
  const flyRotate = computed(() => {
    const angleRes = angleOfTriangle(
      {
        x: flyToRect.value?.right,
        y: flyToRect.value?.top,
      },
      {
        x: starRect.value?.left,
        y: flyToRect.value?.top,
      },
      {
        x: starRect.value?.left,
        y: starRect.value?.top,
      },
    )
    return angleRes.c * (flyToRect.value?.right > starRect.value?.left ? 1 : -1) + 'deg'
  })

  async function getRightRect() {
    const data = await document.querySelector('.progress__rate')?.getBoundingClientRect()
    flyToRect.value = data
    const dataT = await document.querySelector('.right')?.getBoundingClientRect()
    starRect.value = dataT
    if (flyToRect.value) {
      sound.play('star_answer.mp3')
    }
  }

  const distance = (p1: Point, p2: Point) => {
    return Math.sqrt((p1.x - p2.x) ** 2 + (p1.y - p2.y) ** 2)
  }

  const angleOfTriangle = (A: Point, B: Point, C: Point) => {
    const angle = (radian: number) => (180 * radian) / Math.PI
    const a = distance(B, C)
    const b = distance(A, C)
    const c = distance(A, B)
    const angleA = Math.acos((b * b + c * c - a * a) / (2 * b * c))
    const angleB = Math.acos((a * a + c * c - b * b) / (2 * a * c))
    const angleC = Math.acos((a * a + b * b - c * c) / (2 * a * b))
    return {
      a: Number.isNaN(angleA) ? 180 : angle(angleA),
      b: Number.isNaN(angleB) ? 180 : angle(angleB),
      c: Number.isNaN(angleC) ? 180 : angle(angleC),
    }
  }

  return {
    starRect,
    starX,
    starY,
    flyToRect,
    flyRotate,
    getRightRect,
  }
}
