import React, { useState } from 'react';
import styled from 'styled-components';
import { VideoPlay } from '../../components/Icons';
import { respondTo } from '../../utils/responsive';

const VideoController = ({ youtubeId, className }) => {
  const [isPlaying, setIsPlaying] = useState(false);
  const thumbnailUrl = `https://img.youtube.com/vi/${youtubeId}/maxresdefault.jpg`;

  const handlePlay = () => {
    setIsPlaying(true);
  };

  return (
    <VideoWrapper className={className}>
      {!isPlaying ? (
        <ThumbnailContainer onClick={handlePlay}>
          <Thumbnail src={thumbnailUrl} alt="影片預覽" />
          <PlayButton aria-label="播放影片">
            <VideoPlay />
          </PlayButton>
        </ThumbnailContainer>
      ) : (
        <IframeContainer
          src={`https://www.youtube.com/embed/${youtubeId}?autoplay=1`}
          allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
          allowFullScreen
          title="YouTube video player"
        />
      )}
    </VideoWrapper>
  );
};

const VideoWrapper = styled.div`
    position: relative;
    width: 100%;
    padding-bottom: 56.25%; /* 16:9 比例 */

    border-radius: 32px;
    border: 4px solid var(--neutrals-700);
    overflow: hidden;
    box-shadow: 8px 9px 4px 0px rgba(0, 0, 0, 0.25);
`;

const ThumbnailContainer = styled.div`
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    cursor: pointer;
`;

const Thumbnail = styled.img`
    width: 100%;
    height: 100%;
    object-fit: cover;
`;

const PlayButton = styled.button`
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    border: none;
    cursor: pointer;

    --size: 75px;
    width: var(--size);
    height: var(--size);

    svg {
        width: 100%;
        height: 100%;
    }

    ${respondTo.sm} {
        --size: 40px;
    }
`;

const IframeContainer = styled.iframe`
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    border: none;
`;

export default VideoController;
