// packages/block-library/src/post-date/edit.js
import clsx from "clsx";
import { store as coreStore } from "@wordpress/core-data";
import { useEffect, useMemo, useState } from "@wordpress/element";
import {
  dateI18n,
  humanTimeDiff,
  getSettings as getDateSettings
} from "@wordpress/date";
import {
  AlignmentControl,
  BlockControls,
  InspectorControls,
  store as blockEditorStore,
  useBlockProps,
  useBlockEditingMode,
  __experimentalDateFormatPicker as DateFormatPicker,
  __experimentalPublishDateTimePicker as PublishDateTimePicker
} from "@wordpress/block-editor";
import {
  Dropdown,
  ToolbarGroup,
  ToolbarButton,
  ToggleControl,
  __experimentalToolsPanel as ToolsPanel,
  __experimentalToolsPanelItem as ToolsPanelItem
} from "@wordpress/components";
import { __, _x, sprintf } from "@wordpress/i18n";
import { pencil } from "@wordpress/icons";
import { DOWN } from "@wordpress/keycodes";
import { useSelect, useDispatch } from "@wordpress/data";
import { store as blocksStore } from "@wordpress/blocks";
import { useToolsPanelDropdownMenuProps } from "../utils/hooks";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
function PostDateEdit({
  attributes,
  context: { postType: postTypeSlug, queryId },
  setAttributes,
  name
}) {
  const { datetime, textAlign, format, isLink } = attributes;
  const blockProps = useBlockProps({
    className: clsx({
      [`has-text-align-${textAlign}`]: textAlign
    })
  });
  const dropdownMenuProps = useToolsPanelDropdownMenuProps();
  const [popoverAnchor, setPopoverAnchor] = useState(null);
  const popoverProps = useMemo(
    () => ({ anchor: popoverAnchor }),
    [popoverAnchor]
  );
  const { __unstableMarkNextChangeAsNotPersistent } = useDispatch(blockEditorStore);
  useEffect(() => {
    if (datetime === void 0) {
      __unstableMarkNextChangeAsNotPersistent();
      setAttributes({ datetime: /* @__PURE__ */ new Date() });
    }
  }, [datetime]);
  const isDescendentOfQueryLoop = Number.isFinite(queryId);
  const dateSettings = getDateSettings();
  const {
    postType,
    siteFormat = dateSettings.formats.date,
    siteTimeFormat = dateSettings.formats.time
  } = useSelect(
    (select) => {
      const { getPostType, getEntityRecord } = select(coreStore);
      const siteSettings = getEntityRecord("root", "site");
      return {
        siteFormat: siteSettings?.date_format,
        siteTimeFormat: siteSettings?.time_format,
        postType: postTypeSlug ? getPostType(postTypeSlug) : null
      };
    },
    [postTypeSlug]
  );
  const activeBlockVariationName = useSelect(
    (select) => select(blocksStore).getActiveBlockVariation(name, attributes)?.name,
    [name, attributes]
  );
  const blockEditingMode = useBlockEditingMode();
  let postDate = /* @__PURE__ */ jsx("time", { dateTime: dateI18n("c", datetime), ref: setPopoverAnchor, children: format === "human-diff" ? humanTimeDiff(datetime) : dateI18n(format || siteFormat, datetime) });
  if (isLink && datetime) {
    postDate = /* @__PURE__ */ jsx(
      "a",
      {
        href: "#post-date-pseudo-link",
        onClick: (event) => event.preventDefault(),
        children: postDate
      }
    );
  }
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    (blockEditingMode === "default" || !isDescendentOfQueryLoop) && /* @__PURE__ */ jsxs(BlockControls, { group: "block", children: [
      /* @__PURE__ */ jsx(
        AlignmentControl,
        {
          value: textAlign,
          onChange: (nextAlign) => {
            setAttributes({ textAlign: nextAlign });
          }
        }
      ),
      activeBlockVariationName !== "post-date-modified" && (!isDescendentOfQueryLoop || !activeBlockVariationName) && /* @__PURE__ */ jsx(ToolbarGroup, { children: /* @__PURE__ */ jsx(
        Dropdown,
        {
          popoverProps,
          renderContent: ({ onClose }) => /* @__PURE__ */ jsx(
            PublishDateTimePicker,
            {
              title: activeBlockVariationName === "post-date" ? __("Publish Date") : __("Date"),
              currentDate: datetime,
              onChange: (newDatetime) => setAttributes({
                datetime: newDatetime
              }),
              is12Hour: is12HourFormat(
                siteTimeFormat
              ),
              onClose,
              dateOrder: (
                /* translators: Order of day, month, and year. Available formats are 'dmy', 'mdy', and 'ymd'. */
                _x("dmy", "date order")
              )
            }
          ),
          renderToggle: ({ isOpen, onToggle }) => {
            const openOnArrowDown = (event) => {
              if (!isOpen && event.keyCode === DOWN) {
                event.preventDefault();
                onToggle();
              }
            };
            return /* @__PURE__ */ jsx(
              ToolbarButton,
              {
                "aria-expanded": isOpen,
                icon: pencil,
                title: __("Change Date"),
                onClick: onToggle,
                onKeyDown: openOnArrowDown
              }
            );
          }
        }
      ) })
    ] }),
    /* @__PURE__ */ jsx(InspectorControls, { children: /* @__PURE__ */ jsxs(
      ToolsPanel,
      {
        label: __("Settings"),
        resetAll: () => {
          setAttributes({
            datetime: void 0,
            format: void 0,
            isLink: false
          });
        },
        dropdownMenuProps,
        children: [
          /* @__PURE__ */ jsx(
            ToolsPanelItem,
            {
              hasValue: () => !!format,
              label: __("Date Format"),
              onDeselect: () => setAttributes({ format: void 0 }),
              isShownByDefault: true,
              children: /* @__PURE__ */ jsx(
                DateFormatPicker,
                {
                  format,
                  defaultFormat: siteFormat,
                  onChange: (nextFormat) => setAttributes({ format: nextFormat })
                }
              )
            }
          ),
          /* @__PURE__ */ jsx(
            ToolsPanelItem,
            {
              hasValue: () => isLink !== false,
              label: postType?.labels.singular_name ? sprintf(
                // translators: %s: Name of the post type e.g: "post".
                __("Link to %s"),
                postType.labels.singular_name.toLowerCase()
              ) : __("Link to post"),
              onDeselect: () => setAttributes({ isLink: false }),
              isShownByDefault: true,
              children: /* @__PURE__ */ jsx(
                ToggleControl,
                {
                  __nextHasNoMarginBottom: true,
                  label: postType?.labels.singular_name ? sprintf(
                    // translators: %s: Name of the post type e.g: "post".
                    __("Link to %s"),
                    postType.labels.singular_name.toLowerCase()
                  ) : __("Link to post"),
                  onChange: () => setAttributes({ isLink: !isLink }),
                  checked: isLink
                }
              )
            }
          )
        ]
      }
    ) }),
    /* @__PURE__ */ jsx("div", { ...blockProps, children: postDate })
  ] });
}
function is12HourFormat(format) {
  return /(?:^|[^\\])[aAgh]/.test(format);
}
export {
  PostDateEdit as default,
  is12HourFormat
};
//# sourceMappingURL=edit.js.map
