import _extends from "@babel/runtime/helpers/esm/extends";
import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties";
import React, { forwardRef, useState } from 'react';
import PropTypes from 'prop-types';
import Heading from '../Heading';
import IconButton from '../IconButton';
import IconInsertLink from '../IconInsertLink';

var _ref = /*#__PURE__*/React.createElement(IconInsertLink, {
  size: 22
});

const Anchor = /*#__PURE__*/forwardRef(({
  to
}, ref) => /*#__PURE__*/React.createElement(IconButton, {
  as: "a",
  ref: ref,
  href: to,
  size: 22,
  sx: {
    m: 0,
    p: 0,
    ml: 2,
    verticalAlign: 'middle',
    cursor: 'pointer'
  }
}, _ref));
Anchor.displayName = 'Anchor';
Anchor.propTypes = {
  to: PropTypes.string
};

const getLink = href => {
  if (typeof window === 'undefined') {
    return '';
  }

  const {
    origin,
    search,
    pathname
  } = document.location;
  return `${origin + pathname + search}#${href}`;
};

const HeadingAnchor = /*#__PURE__*/forwardRef((_ref2, ref) => {
  let {
    children,
    id,
    copyLink
  } = _ref2,
      rest = _objectWithoutProperties(_ref2, ["children", "id", "copyLink"]);

  const [inHover, setHover] = useState(false);
  const to = copyLink || getLink(id);
  return /*#__PURE__*/React.createElement(Heading, _extends({
    onMouseEnter: () => setHover(true),
    onMouseLeave: () => setHover(false),
    id: id,
    ref: ref
  }, rest), children, (id || copyLink) && inHover && /*#__PURE__*/React.createElement(Anchor, {
    to: to
  }));
});
HeadingAnchor.displayName = 'HeadingAnchor';
process.env.NODE_ENV !== "production" ? HeadingAnchor.propTypes = {
  /** Children to be rendered in the main container. */
  children: PropTypes.node,

  /** You can override the whole link. If not set the current location with
   * `id` as the hash is used. */
  copyLink: PropTypes.string,
  id: PropTypes.string
} : void 0;
export default HeadingAnchor;