import Image from "next/image";
import React from "react";

type MediaKind = "image" | "video";

export type MediaProps = {
  src?: string | null;
  mimeType?: string | null;
  kind?: MediaKind;

  alt?: string;
  className?: string;

  /** next/image */
  priority?: boolean;
  sizes?: string;

  /** video */
  poster?: string | null;
  autoPlay?: boolean;
  muted?: boolean;
  loop?: boolean;
  controls?: boolean;
  playsInline?: boolean;
};

const VIDEO_EXT = new Set(["mp4", "webm", "ogg", "mov", "m4v", "m3u8"]);
const IMAGE_EXT = new Set(["jpg", "jpeg", "png", "webp", "avif", "gif", "svg"]);

function getExtension(url: string): string | null {
  const clean = url.split("?")[0].split("#")[0];
  const idx = clean.lastIndexOf(".");
  if (idx === -1) return null;
  return clean.slice(idx + 1).toLowerCase();
}

function detectKind(src: string, mimeType?: string | null): MediaKind {
  if (mimeType) {
    if (mimeType.startsWith("video/")) return "video";
    if (mimeType.startsWith("image/")) return "image";
  }
  const ext = getExtension(src);
  if (ext && VIDEO_EXT.has(ext)) return "video";
  if (ext && IMAGE_EXT.has(ext)) return "image";
  // Fallback: image is safer for layout
  return "image";
}

/**
 * Media component that renders either <video> or next/image based on src/mimeType.
 * Never renders with empty src, preventing cases where build output includes src="".
 */
export function Media({
  src,
  mimeType,
  kind,
  alt = "",
  className,
  priority,
  sizes = "100vw",
  poster,
  autoPlay = true,
  muted = true,
  loop = true,
  controls = false,
  playsInline = true,
}: MediaProps) {
  const normalizedSrc = (src ?? "").trim();
  if (!normalizedSrc) return null;

  const resolvedKind = kind ?? detectKind(normalizedSrc, mimeType);

  if (resolvedKind === "video") {
    return (
      <video
        className={className}
        src={normalizedSrc}
        poster={poster ?? undefined}
        autoPlay={autoPlay}
        muted={muted}
        loop={loop}
        controls={controls}
        playsInline={playsInline}
        preload="metadata"
      />
    );
  }

  return (
    <Image
      className={className}
      src={normalizedSrc}
      alt={alt}
      fill
      priority={priority}
      sizes={sizes}
    />
  );
}
