import {
  memo,
  RefObject,
} from 'react'

import styled from 'styled-components/macro'

import { Icon } from 'features/Icon'

const PipWrapper = styled.div`
  cursor: pointer;
  margin-left: 25px;
  margin-right: 25px;
  margin-top: 4px;
`

type PipProps = {
  videoRef: RefObject<HTMLVideoElement>,
}

export const PiP = memo(({ videoRef }: PipProps) => {
  const togglePip = async () => {
    try {
      if (
        document.pictureInPictureEnabled && videoRef.current !== document.pictureInPictureElement
      ) {
        await videoRef.current?.requestPictureInPicture()
      } else {
        await document.exitPictureInPicture()
      }
    } catch (err) {
      await document.exitPictureInPicture()
    }
  }

  return (
    <PipWrapper>
      <Icon refIcon='PiP' onClick={togglePip} />
    </PipWrapper>
  )
})
