import React, { useMemo } from "react";
import { VideoEmbedProps } from "./types";

import { cx } from "@shared/utils";

const extractVimeoIdandHash = (href: string) => {
  // Strip query parameters and fragments
  const cleanHref = href.split(/[?#]/)[0].replace(/\/+$/, "");
  const match =
    cleanHref.match(/vimeo\.com\/(?:.*\/)?(\d{6,})/) ||
    cleanHref.match(/player\.vimeo\.com\/video\/(\d{6,})/);

  const parts = cleanHref.split("/");
  const hash = parts[parts.length - 1];

  if (!match?.[1]) return "";
  if (match[1] === hash) return match[1];
  return `${match[1]}/${hash}`;
};

export const VimeoEmbed: React.FC<VideoEmbedProps> = props => {
  const { link, containerClassName, autoplay = false, debug = false } = props;

  const { href, embedId } = useMemo(() => {
    if (!link) return { href: "", embedId: "" };
    const resolved = link.toString();
    const id = extractVimeoIdandHash(resolved);
    return { href: resolved, embedId: id };
  }, [link]);

  if (debug) {
    // eslint-disable-next-line no-console
    console.log("[VimeoEmbed] href:", href, "id:", embedId);
  }

  if (!embedId) {
    return null;
  }

  const params = new URLSearchParams({
    autoplay: autoplay ? "1" : "0",
    muted: "0",
    playsinline: "1",
    dnt: "1",
    title: "0",
    byline: "0",
    portrait: "0",
    autopause: "1",
  });

  const o_src = `https://player.vimeo.com/video/${embedId}?${params.toString()}`;
  const src = normalizeVimeoPlayerSrc(o_src);

  return (
    <div
      className={cx(
        "relative h-0 w-full overflow-hidden pb-[56.25%]",
        containerClassName
      )}
    >
      <iframe
        className="absolute left-0 top-0 h-full w-full"
        src={src}
        allow="autoplay; fullscreen; picture-in-picture"
        allowFullScreen={true}
        referrerPolicy="strict-origin-when-cross-origin"
        title="Embedded vimeo"
      />
    </div>
  );
};

function normalizeVimeoPlayerSrc(src: string): string {
  try {
    const u = new URL(src);
    // Expect path like /video/{id}
    const parts = u.pathname.split("/").filter(Boolean);
    // Handle /video/{id}/{hash} -> move {hash} to ?h=...
    if (parts[0] === "video" && parts.length >= 2) {
      const id = parts[1];
      const maybeHash = parts[2];
      // Rebuild base
      const base = `https://player.vimeo.com/video/${id}`;
      if (maybeHash && /^[a-f0-9]+$/i.test(maybeHash)) {
        u.searchParams.set("h", maybeHash);
      }
      return `${base}?${u.searchParams.toString()}`;
    }
    return src;
  } catch {
    return src;
  }
}
