import React, { useRef, useState, useCallback, useEffect } from 'react';
import { createPortal } from 'react-dom';

var __async$1 = (__this, __arguments, generator) => {
  return new Promise((resolve, reject) => {
    var fulfilled = (value) => {
      try {
        step(generator.next(value));
      } catch (e) {
        reject(e);
      }
    };
    var rejected = (value) => {
      try {
        step(generator.throw(value));
      } catch (e) {
        reject(e);
      }
    };
    var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
    step((generator = generator.apply(__this, __arguments)).next());
  });
};
const getVideoMetadata = (url) => __async$1(void 0, null, function* () {
  var _a, _b, _c;
  try {
    const parsedUrl = new URL(url);
    const hostname = parsedUrl.hostname.replace(/^www\./, "");
    if (hostname.includes("youtube.com") || hostname === "youtu.be") {
      const match = url.match(
        /(?:youtu\.be\/|youtube\.com\/(?:watch\?v=|embed\/|v\/|shorts\/))([\w-]{11})/
      );
      const videoId = (_a = match == null ? void 0 : match[1]) != null ? _a : null;
      return {
        type: "youtube",
        videoId,
        embedUrl: videoId ? `https://www.youtube.com/embed/${videoId}` : null,
        thumbnailUrl: videoId ? `https://img.youtube.com/vi/${videoId}/maxresdefault.jpg` : null
      };
    }
    if (hostname.includes("vimeo.com")) {
      const match = url.match(/vimeo\.com\/(\d+)/);
      const videoId = (_b = match == null ? void 0 : match[1]) != null ? _b : null;
      const oembedUrl = `https://vimeo.com/api/oembed.json?url=${encodeURIComponent(url)}`;
      const res = yield fetch(oembedUrl);
      const data = yield res.json();
      return {
        type: "vimeo",
        videoId,
        embedUrl: videoId ? `https://player.vimeo.com/video/${videoId}` : null,
        thumbnailUrl: (_c = data == null ? void 0 : data.thumbnail_url) != null ? _c : null
      };
    }
    return {
      type: "unknown",
      videoId: null,
      embedUrl: null,
      thumbnailUrl: null
    };
  } catch (err) {
    console.error("Failed to extract video metadata:", err);
    return {
      type: "unknown",
      videoId: null,
      embedUrl: null,
      thumbnailUrl: null
    };
  }
});

var __async = (__this, __arguments, generator) => {
  return new Promise((resolve, reject) => {
    var fulfilled = (value) => {
      try {
        step(generator.next(value));
      } catch (e) {
        reject(e);
      }
    };
    var rejected = (value) => {
      try {
        step(generator.throw(value));
      } catch (e) {
        reject(e);
      }
    };
    var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
    step((generator = generator.apply(__this, __arguments)).next());
  });
};
const Lightbox = ({ items, currentUrl, setCurrentUrl }) => {
  const currentItem = items.find((item) => item.url === currentUrl);
  const innerRef = useRef(null);
  const [videoMetadata, setVideoMetadata] = useState(null);
  const goToNextItem = useCallback(() => {
    const currentIndex = items.findIndex((item) => item.url === currentUrl);
    const nextItem = items.at((currentIndex + 1) % items.length);
    if (nextItem)
      setCurrentUrl(nextItem.url);
  }, [currentUrl, items, setCurrentUrl]);
  const goToPreviousItem = useCallback(() => {
    const currentIndex = items.findIndex((item) => item.url === currentUrl);
    const previousItem = items.at((currentIndex - 1 + items.length) % items.length);
    if (previousItem)
      setCurrentUrl(previousItem.url);
  }, [currentUrl, items, setCurrentUrl]);
  useEffect(() => {
    const keydownListener = (e) => {
      if (!currentUrl || !currentItem)
        return;
      if (e.key === "Escape") {
        e.preventDefault();
        setCurrentUrl(void 0);
      }
      if (e.key === "ArrowRight") {
        e.preventDefault();
        goToNextItem();
      }
      if (e.key === "ArrowLeft") {
        e.preventDefault();
        goToPreviousItem();
      }
    };
    window.addEventListener("keydown", keydownListener);
    return () => window.removeEventListener("keydown", keydownListener);
  }, [currentUrl, currentItem, goToNextItem, goToPreviousItem, setCurrentUrl]);
  useEffect(() => {
    const fetchMetadata = () => __async(void 0, null, function* () {
      if ((currentItem == null ? void 0 : currentItem.type) === "video") {
        const metadata = yield getVideoMetadata(currentItem.url);
        setVideoMetadata(metadata);
      } else {
        setVideoMetadata(null);
      }
    });
    fetchMetadata();
  }, []);
  if (!currentUrl || !currentItem)
    return null;
  return createPortal(
    /* @__PURE__ */ React.createElement("div", {
      className: "absolute top-0 left-0 w-screen h-screen bg-[rgba(0,0,0,0.9)] text-white flex justify-center items-center z-[999999]",
      onClick: (e) => {
        if (e.target !== innerRef.current) {
          setCurrentUrl(void 0);
        }
      }
    }, currentItem.type === "photo" && /* @__PURE__ */ React.createElement("img", {
      className: "cursor-pointer max-w-[90vw] max-h-[90vh]",
      src: currentUrl,
      onClick: () => window.open(currentUrl, "_blank"),
      ref: innerRef,
      alt: ""
    }), currentItem.type === "video" && (videoMetadata == null ? void 0 : videoMetadata.embedUrl) && /* @__PURE__ */ React.createElement("div", {
      className: "relative w-[90vw] max-w-[800px] aspect-video"
    }, /* @__PURE__ */ React.createElement("iframe", {
      src: videoMetadata.embedUrl,
      className: "absolute top-0 left-0 w-full h-full rounded-md",
      title: "Video player",
      frameBorder: "0",
      allow: "accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",
      allowFullScreen: true
    }))),
    document.body
  );
};

export { Lightbox as L };
//# sourceMappingURL=Lightbox-f02b5b4f.js.map
