import _extends from "@babel/runtime/helpers/esm/extends";
import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
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 _ref2 = /*#__PURE__*/React.createElement(IconInsertLink, {
  size: 22
});

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

var getLink = function getLink(href) {
  if (typeof window === 'undefined') {
    return '';
  }

  var _document$location = document.location,
      origin = _document$location.origin,
      search = _document$location.search,
      pathname = _document$location.pathname;
  return "".concat(origin + pathname + search, "#").concat(href);
};

var HeadingAnchor = /*#__PURE__*/forwardRef(function (_ref3, ref) {
  var children = _ref3.children,
      id = _ref3.id,
      copyLink = _ref3.copyLink,
      rest = _objectWithoutProperties(_ref3, ["children", "id", "copyLink"]);

  var _useState = useState(false),
      _useState2 = _slicedToArray(_useState, 2),
      inHover = _useState2[0],
      setHover = _useState2[1];

  var to = copyLink || getLink(id);
  return /*#__PURE__*/React.createElement(Heading, _extends({
    onMouseEnter: function onMouseEnter() {
      return setHover(true);
    },
    onMouseLeave: function onMouseLeave() {
      return 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;