'use strict';

var React = require('react');
var reactDom = require('react-dom');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var React__default = /*#__PURE__*/_interopDefaultLegacy(React);

const X = ({ className = "", strokeWidth = "2" }) => {
  return /* @__PURE__ */ React__default["default"].createElement(
    "svg",
    {
      viewBox: "0 0 32 32",
      fill: "none",
      xmlns: "http://www.w3.org/2000/svg",
      className,
      "aria-label": "X"
    },
    /* @__PURE__ */ React__default["default"].createElement(
      "path",
      {
        d: "M25 7L7 25",
        stroke: "currentColor",
        strokeWidth,
        strokeLinecap: "round",
        strokeLinejoin: "round"
      }
    ),
    /* @__PURE__ */ React__default["default"].createElement(
      "path",
      {
        d: "M25 25L7 7",
        stroke: "currentColor",
        strokeWidth,
        strokeLinecap: "round",
        strokeLinejoin: "round"
      }
    )
  );
};

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(null, null, function* () {
  var _a, _b, _c;
  try {
    const parsed = new URL(url);
    const host = parsed.hostname.replace(/^www\./, "");
    let id = null;
    if (host === "youtu.be" || host.includes("youtube.com")) {
      if (host === "youtu.be") {
        id = parsed.pathname.slice(1);
      } else {
        id = parsed.searchParams.get("v") || parsed.pathname.split("/").filter(Boolean).pop() || null;
      }
      if (id) {
        let thumb = `https://img.youtube.com/vi/${id}/maxresdefault.jpg`;
        try {
          const res = yield fetch(thumb, { method: "HEAD" });
          if (!res.ok) thumb = `https://img.youtube.com/vi/${id}/hqdefault.jpg`;
        } catch (e) {
          thumb = `https://img.youtube.com/vi/${id}/hqdefault.jpg`;
        }
        return {
          type: "youtube",
          videoId: id,
          embedUrl: `https://www.youtube.com/embed/${id}`,
          thumbnailUrl: thumb
        };
      }
    }
    if (host.includes("vimeo.com")) {
      const match = url.match(/vimeo\.com\/(\d+)/);
      id = (_a = match == null ? void 0 : match[1]) != null ? _a : null;
      if (id) {
        try {
          const oembed = `https://vimeo.com/api/oembed.json?url=${encodeURIComponent(
            url
          )}`;
          const data = yield fetch(oembed).then((r) => r.json());
          return {
            type: "vimeo",
            videoId: id,
            embedUrl: `https://player.vimeo.com/video/${id}`,
            thumbnailUrl: data.thumbnail_url
          };
        } catch (e) {
          return {
            type: "vimeo",
            videoId: id,
            embedUrl: `https://player.vimeo.com/video/${id}`,
            thumbnailUrl: null
          };
        }
      }
    }
    if (host === "drive.google.com" || host === "docs.google.com") {
      const match = parsed.pathname.match(/\/d\/([^/]+)/);
      id = (_b = match == null ? void 0 : match[1]) != null ? _b : parsed.searchParams.get("id");
      if (id) {
        return {
          type: "drive",
          videoId: id,
          embedUrl: `https://drive.google.com/file/d/${id}/preview`,
          thumbnailUrl: `https://drive.google.com/thumbnail?sz=w320-h320&id=${id}`
        };
      }
    }
    if (host === "loom.com") {
      const match = parsed.pathname.match(/\/(?:share|embed|watch)\/([A-Za-z0-9]+)/);
      id = (_c = match == null ? void 0 : match[1]) != null ? _c : null;
      if (id) {
        const embedUrl = `https://www.loom.com/embed/${id}`;
        try {
          const oembedUrl = `https://www.loom.com/api/oembed?url=${encodeURIComponent(
            url
          )}`;
          const response = yield fetch(oembedUrl);
          if (!response.ok) {
            throw new Error(`oEmbed API returned ${response.status}`);
          }
          const data = yield response.json();
          return {
            type: "loom",
            videoId: id,
            embedUrl,
            thumbnailUrl: data.thumbnail_url
          };
        } catch (e) {
          console.warn("Loom oEmbed fetch failed:", e);
          return {
            type: "loom",
            videoId: id,
            embedUrl,
            thumbnailUrl: null
          };
        }
      }
    }
    return { type: "unknown", videoId: null, embedUrl: null, thumbnailUrl: null };
  } catch (e) {
    console.error("getVideoMetadata error:", e);
    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,
  showCloseButton = true,
  enableImageClick = false
}) => {
  const currentItem = items.find((item) => item.url === currentUrl);
  const innerRef = React.useRef(null);
  const [videoMetadata, setVideoMetadata] = React.useState(null);
  const goToNextItem = React.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 = React.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]);
  React.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]);
  React.useEffect(() => {
    const fetchMetadata = () => __async(null, null, function* () {
      if ((currentItem == null ? void 0 : currentItem.type) === "video") {
        const metadata = yield getVideoMetadata(currentItem.url);
        setVideoMetadata(metadata);
      } else {
        setVideoMetadata(null);
      }
    });
    fetchMetadata();
  }, [currentItem]);
  if (!currentUrl || !currentItem) return null;
  return reactDom.createPortal(
    /* @__PURE__ */ React__default["default"].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);
          }
        }
      },
      showCloseButton && /* @__PURE__ */ React__default["default"].createElement("button", { onClick: () => setCurrentUrl(void 0) }, /* @__PURE__ */ React__default["default"].createElement(X, { className: "absolute w-[30px] h-[30px] top-[20px] right-[20px] cursor-pointer text-white z-[999999]" })),
      currentItem.type === "photo" && /* @__PURE__ */ React__default["default"].createElement(
        "img",
        {
          className: "cursor-pointer max-w-[90vw] max-h-[90vh]",
          src: currentUrl,
          onClick: () => enableImageClick && window.open(currentUrl, "_blank"),
          ref: innerRef,
          alt: ""
        }
      ),
      currentItem.type === "video" && (videoMetadata == null ? void 0 : videoMetadata.embedUrl) && /* @__PURE__ */ React__default["default"].createElement("div", { className: "relative w-[90vw] max-w-[800px] aspect-video" }, /* @__PURE__ */ React__default["default"].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
  );
};

exports.Lightbox = Lightbox;
exports.X = X;
//# sourceMappingURL=Lightbox-d72e19ba.js.map
