"use client";

import { useEffect, useRef } from "react";

type VideoTileProps = {
  stream: MediaStream | null;
  name: string;
  isLocal?: boolean;
  isHost?: boolean;
  muted?: boolean;
  videoOff?: boolean;
};

export function VideoTile({ stream, name, isLocal, isHost, muted, videoOff }: VideoTileProps) {
  const videoRef = useRef<HTMLVideoElement>(null);

  useEffect(() => {
    if (videoRef.current) videoRef.current.srcObject = stream;
  }, [stream]);

  return (
    <div className="relative aspect-video overflow-hidden rounded-2xl bg-neutral-800">
      {stream && !videoOff ? (
        <video
          ref={videoRef}
          autoPlay
          playsInline
          muted={isLocal}
          className="h-full w-full object-cover [transform:scaleX(var(--flip,1))]"
          style={isLocal ? ({ "--flip": -1 } as React.CSSProperties) : undefined}
        />
      ) : (
        <div className="flex h-full w-full items-center justify-center bg-neutral-800">
          <div className="flex h-16 w-16 items-center justify-center rounded-full bg-neutral-700 font-serif text-2xl text-white">
            {name.charAt(0).toUpperCase()}
          </div>
        </div>
      )}
      <div className="absolute inset-x-0 bottom-0 flex items-center justify-between gap-2 bg-gradient-to-t from-black/70 to-transparent px-3 py-2">
        <span className="truncate text-sm font-medium text-white">
          {name}
          {isLocal && " (du)"}
        </span>
        <div className="flex items-center gap-1.5">
          {isHost && (
            <span className="rounded-full bg-anouma-mauve-dark/90 px-2 py-0.5 text-[10px] font-medium uppercase tracking-wide text-white">
              Host
            </span>
          )}
          {muted && (
            <span aria-label="Mikrofon stumm" className="text-white/80">
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" aria-hidden="true">
                <path
                  d="M1 1l22 22M9 9v3a3 3 0 0 0 4.6 2.55M15 9.34V5a3 3 0 0 0-5.94-.6M5 10v1a7 7 0 0 0 10.54 6.02M12 18v3m-4 0h8"
                  stroke="currentColor"
                  strokeWidth="1.8"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                />
              </svg>
            </span>
          )}
        </div>
      </div>
    </div>
  );
}
