
import { useState, useRef } from 'react';
import { Button } from './ui/button';
import { X } from 'lucide-react';

export const TikTokEmbed = ({ 
  red, 
  index, 
  removeTikTokKey 
}: { 
  red: { key: string }, 
  index: number, 
  removeTikTokKey: (index: number) => void 
}) => {
  const [isPaused, setIsPaused] = useState(false);
  const iframeRef = useRef<HTMLIFrameElement>(null);
  const overlayImage = "https://example.com/your-poster-image.jpg";

  return (
    <div
      key={index}
      className="relative group flex-shrink-0"
      style={{ minWidth: "300px", maxWidth: "400px" }}
    >
      <div className="relative w-full h-[500px]">
        <iframe
          ref={iframeRef}
          src={`https://www.tiktok.com/embed/v2/${red.key}?referer=no-referrer&rel=0&hide_cover=1&disable_ads=1`}
          width="100%"
          height="500"
          frameBorder="0"
          allowFullScreen
          title={`Video de TikTok ${index + 1}`}
          className="rounded-lg shadow-md absolute inset-0 w-full h-full"
          allow="autoplay; encrypted-media; picture-in-picture"
          onLoad={() => {
            window.addEventListener('message', (e) => {
              if (e.data === "tiktok-paused") setIsPaused(true);
              if (e.data === "tiktok-playing") setIsPaused(false);
            });
          }}
        />
        {isPaused && (
          <div 
            className="absolute inset-0 bg-black/30 flex items-center justify-center cursor-pointer"
            onClick={() => {
              iframeRef.current?.contentWindow?.postMessage("play", "*");
            }}
          >
            <img 
              src={overlayImage} 
              alt="Paused overlay" 
              className="max-w-full max-h-full object-contain"
            />
            <div className="absolute inset-0 flex items-center justify-center">
              <div className="w-16 h-16 bg-white/80 rounded-full flex items-center justify-center">
                <svg className="w-8 h-8 text-black" fill="currentColor" viewBox="0 0 20 20">
                  <path d="M6.3 2.8L17 10 6.3 17.2V2.8z"/>
                </svg>
              </div>
            </div>
          </div>
        )}
      </div>
      <Button
        type="button"
        variant="ghost"
        size="icon"
        className="absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity bg-white/80 hover:bg-white"
        onClick={() => removeTikTokKey(index)}
      >
        <X className="h-4 w-4 text-destructive" />
      </Button>
    </div>
  );
};
