import { useMemo } from 'react'

import { API_ROOT } from 'config'

import type { MatchInfo } from 'requests/getMatchInfo'

import { usePageParams } from 'hooks/usePageParams'

import { useMatchPopupStore } from 'features/MatchPopup'

import { usePlayerProgressReporter } from './usePlayerProgressReporter'
import { useLastPlayPosition } from './useLastPlayPosition'
import { useUrlParam } from './useUrlParam'

export const useLiveMatch = (profile: MatchInfo) => {
  const {
    handlePlaylistClick,
    matchPlaylists,
    selectedPlaylist,
  } = useMatchPopupStore()

  const { profileId: matchId, sportType } = usePageParams()
  const resume = useUrlParam()

  const fromStartIfStreamPaused = useMemo(
    () => (profile && !profile.live ? 0 : undefined),
    // deps намеренно оставляем пустым,
    // не нужно реагировать на изменение live когда пользователь смотрит матч
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [],
  )

  return {
    matchPlaylists,
    onPlaylistSelect: handlePlaylistClick,
    resume: resume ?? fromStartIfStreamPaused,
    selectedPlaylist,
    streamUrl: `${API_ROOT}/video/stream/${sportType}/${matchId}.m3u8`,
    ...usePlayerProgressReporter(),
    ...useLastPlayPosition(),
  }
}
