// packages/block-library/src/video/tracks-editor.js
import { __, _x, sprintf } from "@wordpress/i18n";
import {
  NavigableMenu,
  MenuItem,
  FormFileUpload,
  MenuGroup,
  ToolbarGroup,
  ToolbarButton,
  Dropdown,
  Button,
  TextControl,
  SelectControl,
  ToggleControl,
  __experimentalGrid as Grid,
  __experimentalHStack as HStack,
  __experimentalVStack as VStack,
  privateApis as componentsPrivateApis
} from "@wordpress/components";
import {
  MediaUpload,
  MediaUploadCheck,
  store as blockEditorStore
} from "@wordpress/block-editor";
import { upload, media } from "@wordpress/icons";
import { useSelect } from "@wordpress/data";
import { useState, useRef, useEffect } from "@wordpress/element";
import { getFilename } from "@wordpress/url";
import { unlock } from "../lock-unlock";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
var { Badge } = unlock(componentsPrivateApis);
var ALLOWED_TYPES = ["text/vtt"];
var DEFAULT_KIND = "subtitles";
var KIND_OPTIONS = [
  { label: __("Subtitles"), value: "subtitles" },
  { label: __("Captions"), value: "captions" },
  { label: __("Descriptions"), value: "descriptions" },
  { label: __("Chapters"), value: "chapters" },
  { label: __("Metadata"), value: "metadata" }
];
var DEFAULT_TRACK = {
  src: "",
  label: "",
  srcLang: "en",
  kind: DEFAULT_KIND,
  default: false
};
function TrackList({ tracks, onEditPress }) {
  const content = tracks.map((track, index) => {
    return /* @__PURE__ */ jsxs(
      HStack,
      {
        className: "block-library-video-tracks-editor__track-list-track",
        children: [
          /* @__PURE__ */ jsx("span", { children: track.label }),
          /* @__PURE__ */ jsxs(HStack, { justify: "flex-end", children: [
            track.default && /* @__PURE__ */ jsx(Badge, { children: __("Default") }),
            /* @__PURE__ */ jsx(
              Button,
              {
                __next40pxDefaultSize: true,
                variant: "tertiary",
                onClick: () => onEditPress(index),
                "aria-label": sprintf(
                  /* translators: %s: Label of the video text track e.g: "French subtitles". */
                  _x("Edit %s", "text tracks"),
                  track.label
                ),
                children: __("Edit")
              }
            )
          ] })
        ]
      },
      track.id ?? track.src
    );
  });
  return /* @__PURE__ */ jsx(
    MenuGroup,
    {
      label: __("Text tracks"),
      className: "block-library-video-tracks-editor__track-list",
      children: content
    }
  );
}
function SingleTrackEditor({
  track,
  onChange,
  onClose,
  onRemove,
  allowSettingDefault
}) {
  const [trackState, setTrackState] = useState({
    ...DEFAULT_TRACK,
    ...track
  });
  const { src, label, srcLang, kind, default: isDefaultTrack } = trackState;
  const fileName = src.startsWith("blob:") ? "" : getFilename(src) || "";
  return /* @__PURE__ */ jsxs(
    VStack,
    {
      className: "block-library-video-tracks-editor__single-track-editor",
      spacing: "4",
      children: [
        /* @__PURE__ */ jsx("span", { className: "block-library-video-tracks-editor__single-track-editor-edit-track-label", children: __("Edit track") }),
        /* @__PURE__ */ jsxs("span", { children: [
          __("File"),
          ": ",
          /* @__PURE__ */ jsx("b", { children: fileName })
        ] }),
        /* @__PURE__ */ jsxs(Grid, { columns: 2, gap: 4, children: [
          /* @__PURE__ */ jsx(
            TextControl,
            {
              __next40pxDefaultSize: true,
              __nextHasNoMarginBottom: true,
              onChange: (newLabel) => setTrackState((prevTrackState) => ({
                ...prevTrackState,
                label: newLabel
              })),
              label: __("Label"),
              value: label,
              help: __("Title of track")
            }
          ),
          /* @__PURE__ */ jsx(
            TextControl,
            {
              __next40pxDefaultSize: true,
              __nextHasNoMarginBottom: true,
              onChange: (newSrcLang) => setTrackState((prevTrackState) => ({
                ...prevTrackState,
                srcLang: newSrcLang
              })),
              label: __("Source language"),
              value: srcLang,
              help: __("Language tag (en, fr, etc.)")
            }
          )
        ] }),
        /* @__PURE__ */ jsxs(VStack, { spacing: "4", children: [
          /* @__PURE__ */ jsx(
            SelectControl,
            {
              __next40pxDefaultSize: true,
              __nextHasNoMarginBottom: true,
              className: "block-library-video-tracks-editor__single-track-editor-kind-select",
              options: KIND_OPTIONS,
              value: kind,
              label: __("Kind"),
              onChange: (newKind) => setTrackState((prevTrackState) => ({
                ...prevTrackState,
                kind: newKind
              }))
            }
          ),
          /* @__PURE__ */ jsx(
            ToggleControl,
            {
              __next40pxDefaultSize: true,
              __nextHasNoMarginBottom: true,
              label: __("Set as default track"),
              checked: isDefaultTrack,
              disabled: !allowSettingDefault,
              onChange: (defaultTrack) => setTrackState((prevTrackState) => ({
                ...prevTrackState,
                default: defaultTrack
              }))
            }
          ),
          /* @__PURE__ */ jsxs(HStack, { className: "block-library-video-tracks-editor__single-track-editor-buttons-container", children: [
            /* @__PURE__ */ jsx(
              Button,
              {
                __next40pxDefaultSize: true,
                isDestructive: true,
                variant: "link",
                onClick: onRemove,
                children: __("Remove track")
              }
            ),
            /* @__PURE__ */ jsx(
              Button,
              {
                __next40pxDefaultSize: true,
                variant: "primary",
                onClick: () => {
                  onChange(trackState);
                  onClose();
                },
                children: __("Apply")
              }
            )
          ] })
        ] })
      ]
    }
  );
}
function TracksEditor({ tracks = [], onChange }) {
  const mediaUpload = useSelect((select) => {
    return select(blockEditorStore).getSettings().mediaUpload;
  }, []);
  const [trackBeingEdited, setTrackBeingEdited] = useState(null);
  const dropdownPopoverRef = useRef();
  const handleTrackSelect = (selectedTracks = [], appendTracks = false) => {
    const existingTracksMap = new Map(
      tracks.map((track) => [track.id, track])
    );
    const tracksToAdd = selectedTracks.map(({ id, title, url }) => {
      if (existingTracksMap.has(id)) {
        return existingTracksMap.get(id);
      }
      return {
        ...DEFAULT_TRACK,
        id,
        label: title || "",
        src: url
      };
    });
    if (tracksToAdd.length === 0) {
      return;
    }
    onChange([...appendTracks ? tracks : [], ...tracksToAdd]);
  };
  function uploadFiles(event) {
    const files = event.target.files;
    mediaUpload({
      allowedTypes: ALLOWED_TYPES,
      filesList: files,
      onFileChange: (selectedTracks) => {
        if (!Array.isArray(selectedTracks)) {
          return;
        }
        const uploadedTracks = selectedTracks.filter(
          (track) => !!track?.id
        );
        if (!uploadedTracks.length) {
          return;
        }
        handleTrackSelect(uploadedTracks, true);
      }
    });
  }
  useEffect(() => {
    dropdownPopoverRef.current?.focus();
  }, [trackBeingEdited]);
  if (!mediaUpload) {
    return null;
  }
  return /* @__PURE__ */ jsx(
    Dropdown,
    {
      contentClassName: "block-library-video-tracks-editor",
      focusOnMount: true,
      popoverProps: {
        ref: dropdownPopoverRef
      },
      renderToggle: ({ isOpen, onToggle }) => {
        const handleOnToggle = () => {
          if (!isOpen) {
            setTrackBeingEdited(null);
          }
          onToggle();
        };
        return /* @__PURE__ */ jsx(ToolbarGroup, { children: /* @__PURE__ */ jsx(
          ToolbarButton,
          {
            "aria-expanded": isOpen,
            "aria-haspopup": "true",
            onClick: handleOnToggle,
            children: __("Text tracks")
          }
        ) });
      },
      renderContent: () => {
        if (trackBeingEdited !== null) {
          return /* @__PURE__ */ jsx(
            SingleTrackEditor,
            {
              track: tracks[trackBeingEdited],
              onChange: (newTrack) => {
                const newTracks = [...tracks];
                newTracks[trackBeingEdited] = newTrack;
                onChange(newTracks);
              },
              onClose: () => setTrackBeingEdited(null),
              onRemove: () => {
                onChange(
                  tracks.filter(
                    (_track, index) => index !== trackBeingEdited
                  )
                );
                setTrackBeingEdited(null);
              },
              allowSettingDefault: !tracks.some((track) => track.default) || tracks[trackBeingEdited].default
            }
          );
        }
        return /* @__PURE__ */ jsxs(Fragment, { children: [
          tracks.length === 0 && /* @__PURE__ */ jsxs("div", { className: "block-library-video-tracks-editor__tracks-informative-message", children: [
            /* @__PURE__ */ jsx("h2", { className: "block-library-video-tracks-editor__tracks-informative-message-title", children: __("Text tracks") }),
            /* @__PURE__ */ jsx("p", { className: "block-library-video-tracks-editor__tracks-informative-message-description", children: __(
              "Tracks can be subtitles, captions, chapters, or descriptions. They help make your content more accessible to a wider range of users."
            ) })
          ] }),
          /* @__PURE__ */ jsxs(NavigableMenu, { children: [
            /* @__PURE__ */ jsx(
              TrackList,
              {
                tracks,
                onEditPress: setTrackBeingEdited
              }
            ),
            /* @__PURE__ */ jsx(
              MenuGroup,
              {
                className: "block-library-video-tracks-editor__add-tracks-container",
                label: __("Add tracks"),
                children: /* @__PURE__ */ jsxs(MediaUploadCheck, { children: [
                  /* @__PURE__ */ jsx(
                    MediaUpload,
                    {
                      onSelect: handleTrackSelect,
                      allowedTypes: ALLOWED_TYPES,
                      value: tracks.map(({ id }) => id),
                      multiple: true,
                      render: ({ open }) => /* @__PURE__ */ jsx(
                        MenuItem,
                        {
                          icon: media,
                          onClick: open,
                          children: __("Open Media Library")
                        }
                      )
                    }
                  ),
                  /* @__PURE__ */ jsx(
                    FormFileUpload,
                    {
                      onChange: uploadFiles,
                      accept: ".vtt,text/vtt",
                      multiple: true,
                      render: ({ openFileDialog }) => {
                        return /* @__PURE__ */ jsx(
                          MenuItem,
                          {
                            icon: upload,
                            onClick: openFileDialog,
                            children: _x("Upload", "verb")
                          }
                        );
                      }
                    }
                  )
                ] })
              }
            )
          ] })
        ] });
      }
    }
  );
}
export {
  TracksEditor as default
};
//# sourceMappingURL=tracks-editor.js.map
