'use client';

import { useRef, useState } from 'react';
import { cn } from '../utils/cn';

export interface VideoPlayerProps {
  /** Video source URL or base64 data URI. */
  src: string;
  /** MIME type for the source. */
  mimeType?: string;
  /** Alt text / accessible label. */
  alt?: string;
  /** Additional class names for the container. */
  className?: string;
  /** Aspect ratio CSS class (default: aspect-video). */
  aspectRatio?: string;
}

/**
 * VideoPlayer renders an HTML5 video with controls, loading state,
 * and error handling. Supports both URL and base64 data URIs.
 */
export function VideoPlayer({
  src,
  mimeType = 'video/mp4',
  alt = 'Generated video',
  className,
  aspectRatio = 'aspect-video',
}: VideoPlayerProps) {
  const videoRef = useRef<HTMLVideoElement>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  return (
    <div
      className={cn(
        'relative rounded-lg overflow-hidden bg-[var(--surface)]',
        aspectRatio,
        className,
      )}
    >
      {isLoading && !error && (
        <div className="absolute inset-0 flex items-center justify-center bg-[var(--surface)]">
          <div className="h-8 w-8 animate-spin rounded-full border-2 border-[var(--text-muted)] border-t-[var(--accent)]" />
        </div>
      )}

      {error && (
        <div className="absolute inset-0 flex items-center justify-center bg-[var(--surface)]">
          <p className="text-sm text-[var(--error)]">{error}</p>
        </div>
      )}

      <video
        ref={videoRef}
        className={cn('h-full w-full object-contain', isLoading && 'invisible')}
        controls
        playsInline
        aria-label={alt}
        onLoadedData={() => setIsLoading(false)}
        onError={() => {
          setIsLoading(false);
          setError('Failed to load video');
        }}
      >
        <source src={src} type={mimeType} />
      </video>
    </div>
  );
}

export interface VideoGridProps {
  /** Videos to display. */
  videos: Array<{ src: string; mimeType?: string; alt?: string }>;
  /** Additional class names. */
  className?: string;
}

/**
 * VideoGrid displays one or more videos in a responsive grid.
 */
export function VideoGrid({ videos, className }: VideoGridProps) {
  if (videos.length === 0) return null;

  return (
    <div
      className={cn(
        'grid gap-4',
        videos.length === 1 ? 'grid-cols-1' : 'grid-cols-1 md:grid-cols-2',
        className,
      )}
    >
      {videos.map((video, i) => (
        <VideoPlayer
          key={`video-${i}`}
          src={video.src}
          mimeType={video.mimeType}
          alt={video.alt}
        />
      ))}
    </div>
  );
}
