import { useRef, useMemo } from 'react';
import { Template } from '../../store/types';
import './index.css';

interface TemplateCardProps {
  template: Template;
  onClick: (template: Template) => void;
}

export default function TemplateCard({ template, onClick }: TemplateCardProps) {
  const containerRef = useRef<any>(null);
  const containerId = `container-${template.code}`; // 为每个容器创建唯一ID

  // 检测output是否为视频
  const isOutputVideo = useMemo(() => {
    return /\.(mp4|webm|ogg|mov|avi|mkv|flv)$/i.test(template.outputExampleUrl || '');
  }, [template.outputExampleUrl]);

  const handleClick = () => {
    onClick(template);
  };

  return (
    <div className="template-card" onClick={handleClick}>
      {isOutputVideo ? (
        <div className="single-video-container">
          <img className="video-poster" src={template.inputExampleUrl || ``} alt="poster" />
          <video
            className="single-video"
            src={template.outputExampleUrl || ``}
            autoPlay
            muted
            loop
            playsInline
            webkit-playsinline="true"
            style={{ objectFit: 'cover' }}
            controls={false}
          />
        </div>
      ) : (
        <div className="image-comparison">
          <div id={containerId} className="merged-image-container" ref={containerRef}>
            <div className="image-layer overlay-layer">
              <img className="full-image" src={template.outputExampleUrl || ``} alt="output" loading="lazy" />
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
