// packages/block-library/src/post-comments-count/edit.js
import clsx from "clsx";
import {
  AlignmentControl,
  BlockControls,
  useBlockProps
} from "@wordpress/block-editor";
import { useState, useEffect } from "@wordpress/element";
import apiFetch from "@wordpress/api-fetch";
import { addQueryArgs } from "@wordpress/url";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
function PostCommentsCountEdit({
  attributes,
  context,
  setAttributes
}) {
  const { textAlign } = attributes;
  const { postId } = context;
  const [commentsCount, setCommentsCount] = useState();
  const blockProps = useBlockProps({
    className: clsx({
      [`has-text-align-${textAlign}`]: textAlign
    })
  });
  useEffect(() => {
    if (!postId) {
      return;
    }
    const currentPostId = postId;
    apiFetch({
      path: addQueryArgs("/wp/v2/comments", {
        post: postId
      }),
      parse: false
    }).then((res) => {
      if (currentPostId === postId) {
        setCommentsCount(res.headers.get("X-WP-Total"));
      }
    });
  }, [postId]);
  const hasPostAndComments = postId && commentsCount !== void 0;
  const blockStyles = {
    ...blockProps.style,
    textDecoration: hasPostAndComments ? blockProps.style?.textDecoration : void 0
  };
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsx(BlockControls, { group: "block", children: /* @__PURE__ */ jsx(
      AlignmentControl,
      {
        value: textAlign,
        onChange: (nextAlign) => {
          setAttributes({ textAlign: nextAlign });
        }
      }
    ) }),
    /* @__PURE__ */ jsx("div", { ...blockProps, style: blockStyles, children: hasPostAndComments ? commentsCount : "0" })
  ] });
}
export {
  PostCommentsCountEdit as default
};
//# sourceMappingURL=edit.js.map
