import { jsx, jsxs } from "react/jsx-runtime";
import { CanvasIcon } from "../../index.js";
import { createContext, createElement, useContext, useState } from "react";
import { useSafeLingui } from "../../../i18n/index.js";
import { parseStickyNoteMediaMarker, parseStickyNoteMediaSource } from "./StickyNoteMedia.js";
const StickyNoteMediaMarkdownContext = /*#__PURE__*/ createContext({
    editable: false
});
function StickyNoteMediaMarkdownProvider({ value, children }) {
    return /*#__PURE__*/ jsx(StickyNoteMediaMarkdownContext.Provider, {
        value: value,
        children: children
    });
}
function sourceRange(node) {
    const start = node?.position?.start?.offset;
    const end = node?.position?.end?.offset;
    return 'number' == typeof start && 'number' == typeof end ? {
        start,
        end
    } : null;
}
function stopNodeDrag(event) {
    event.stopPropagation();
}
function MediaContainer({ fullWidth, children }) {
    return /*#__PURE__*/ jsx("span", {
        className: "relative my-2 block max-w-full overflow-hidden rounded-md",
        style: {
            width: fullWidth ? '100%' : 'min(320px, 100%)'
        },
        "data-sticky-media": true,
        "data-sticky-full-width": fullWidth,
        children: children
    });
}
function MediaEditButton({ onClick }) {
    const { _ } = useSafeLingui();
    const label = _({
        id: 'sticky-note.media.edit',
        message: 'Edit media'
    });
    return /*#__PURE__*/ jsx("button", {
        type: "button",
        "data-sticky-media-control": true,
        "aria-label": label,
        title: label,
        className: "nodrag nopan absolute right-1 top-1 z-10 inline-flex h-7 w-7 items-center justify-center rounded bg-surface-raised/95 text-foreground opacity-80 shadow-sm transition-opacity hover:bg-surface-hover hover:opacity-100 focus-visible:opacity-100",
        onClick: (event)=>{
            event.preventDefault();
            event.stopPropagation();
            onClick();
        },
        onDoubleClick: (event)=>event.stopPropagation(),
        onPointerDown: stopNodeDrag,
        onMouseDown: stopNodeDrag,
        children: /*#__PURE__*/ jsx(CanvasIcon, {
            icon: "pencil",
            size: 14
        })
    });
}
function StickyNoteMediaImage({ src, alt = '', title, node, fallbackImage, ...imageProps }) {
    const { _ } = useSafeLingui();
    const { editable, onEditMedia } = useContext(StickyNoteMediaMarkdownContext);
    const [failedImageUrl, setFailedImageUrl] = useState(null);
    const [loadedYouTubeId, setLoadedYouTubeId] = useState(null);
    const mediaMarker = parseStickyNoteMediaMarker(title);
    const media = 'string' == typeof src ? parseStickyNoteMediaSource(src, alt, title) : null;
    const range = sourceRange(node);
    if (!media) {
        if (mediaMarker) {
            const unavailableLabel = _({
                id: 'sticky-note.media.unavailable',
                message: 'Media unavailable'
            });
            return /*#__PURE__*/ jsx(MediaContainer, {
                fullWidth: mediaMarker.fullWidth,
                children: /*#__PURE__*/ jsx("span", {
                    role: "img",
                    "aria-label": alt || unavailableLabel,
                    className: "flex min-h-20 items-center justify-center bg-black/10 px-3 text-center text-xs text-foreground-muted",
                    children: unavailableLabel
                })
            });
        }
        if (fallbackImage) {
            const fallbackProps = {
                ...imageProps,
                src,
                alt,
                title
            };
            return 'string' == typeof fallbackImage ? /*#__PURE__*/ createElement(fallbackImage, fallbackProps) : /*#__PURE__*/ createElement(fallbackImage, {
                ...fallbackProps,
                node
            });
        }
        return /*#__PURE__*/ jsx("img", {
            ...imageProps,
            src: src,
            alt: alt,
            title: title
        });
    }
    const editButton = editable && range && onEditMedia && /*#__PURE__*/ jsx(MediaEditButton, {
        onClick: ()=>onEditMedia(media, range)
    });
    if ('youtube' === media.kind) {
        const playLabel = _({
            id: 'sticky-note.media.play-video',
            message: 'Play video'
        });
        const youtubeLoaded = loadedYouTubeId === media.videoId;
        return /*#__PURE__*/ jsxs(MediaContainer, {
            fullWidth: media.fullWidth,
            children: [
                youtubeLoaded ? /*#__PURE__*/ jsx("iframe", {
                    src: `https://www.youtube-nocookie.com/embed/${media.videoId}?autoplay=1`,
                    title: _({
                        id: 'sticky-note.media.youtube-title',
                        message: 'YouTube video'
                    }),
                    loading: "lazy",
                    referrerPolicy: "strict-origin-when-cross-origin",
                    sandbox: "allow-scripts allow-same-origin allow-presentation",
                    allow: "autoplay; encrypted-media; fullscreen; picture-in-picture",
                    allowFullScreen: true,
                    className: "nodrag nopan block aspect-video w-full border-0",
                    onPointerDown: stopNodeDrag,
                    onMouseDown: stopNodeDrag
                }) : /*#__PURE__*/ jsxs("button", {
                    type: "button",
                    "data-sticky-media-control": true,
                    "aria-label": playLabel,
                    className: "nodrag nopan group relative flex aspect-video w-full items-center justify-center overflow-hidden bg-black text-sm font-medium text-white focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-[-2px] focus-visible:outline-white",
                    onClick: (event)=>{
                        event.preventDefault();
                        event.stopPropagation();
                        setLoadedYouTubeId(media.videoId);
                    },
                    onDoubleClick: (event)=>event.stopPropagation(),
                    onPointerDown: stopNodeDrag,
                    onMouseDown: stopNodeDrag,
                    children: [
                        /*#__PURE__*/ jsx("img", {
                            src: `https://i.ytimg.com/vi/${media.videoId}/hqdefault.jpg`,
                            alt: "",
                            draggable: false,
                            loading: "lazy",
                            decoding: "async",
                            referrerPolicy: "no-referrer",
                            className: "absolute inset-0 h-full w-full object-cover opacity-80 transition-opacity group-hover:opacity-70"
                        }),
                        /*#__PURE__*/ jsxs("span", {
                            className: "relative z-10 inline-flex items-center gap-2 rounded-full bg-black/70 px-4 py-2 shadow-sm",
                            children: [
                                /*#__PURE__*/ jsx(CanvasIcon, {
                                    icon: "play",
                                    size: 18
                                }),
                                playLabel
                            ]
                        })
                    ]
                }),
                editButton
            ]
        });
    }
    if ('publicVideo' === media.kind) {
        const videoLabel = alt || _({
            id: 'sticky-note.media.video-label',
            message: 'Embedded video'
        });
        return /*#__PURE__*/ jsxs(MediaContainer, {
            fullWidth: media.fullWidth,
            children: [
                /*#__PURE__*/ jsx("video", {
                    src: media.url,
                    "aria-label": videoLabel,
                    controls: true,
                    preload: "metadata",
                    playsInline: true,
                    className: "nodrag nopan block h-auto w-full bg-black",
                    onClick: (event)=>event.stopPropagation(),
                    onDoubleClick: (event)=>event.stopPropagation(),
                    onPointerDown: stopNodeDrag,
                    onMouseDown: stopNodeDrag,
                    children: _({
                        id: 'sticky-note.media.video-unavailable',
                        message: 'Video playback is unavailable.'
                    })
                }),
                editButton
            ]
        });
    }
    const imageFailed = failedImageUrl === media.url;
    return /*#__PURE__*/ jsxs(MediaContainer, {
        fullWidth: media.fullWidth,
        children: [
            imageFailed ? /*#__PURE__*/ jsx("span", {
                role: "img",
                "aria-label": alt || _({
                    id: 'sticky-note.media.image-unavailable-label',
                    message: 'Image unavailable'
                }),
                className: "flex min-h-20 items-center justify-center bg-black/10 px-3 text-center text-xs text-foreground-muted",
                children: _({
                    id: 'sticky-note.media.image-unavailable',
                    message: 'Image unavailable'
                })
            }) : /*#__PURE__*/ jsx("img", {
                ...imageProps,
                src: media.url,
                alt: alt,
                draggable: false,
                loading: "lazy",
                decoding: "async",
                referrerPolicy: "no-referrer",
                style: {
                    display: 'block',
                    maxWidth: '100%',
                    width: media.fullWidth ? '100%' : 'auto',
                    height: 'auto'
                },
                onError: ()=>setFailedImageUrl(media.url)
            }),
            editButton
        ]
    });
}
function createStickyNoteMediaMarkdownComponents(fallbackImage) {
    return {
        img: (props)=>/*#__PURE__*/ jsx(StickyNoteMediaImage, {
                ...props,
                fallbackImage: fallbackImage
            })
    };
}
export { StickyNoteMediaMarkdownProvider, createStickyNoteMediaMarkdownComponents };
