import { useMemo } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import { widont } from 'journalize';
import { usePagesManifest, usePagePathPrefix, useRouterPath } from "../../../hooks/election/index.js";
import { resolveElectionLink } from "../../../utils/election/index.js";
import IfActive from "../../application/IfActive/index.js";
import ElectionIcon from "../ElectionIcon/index.js";
import ElectionLink from "../ElectionLink/index.js";
import classes from './styles.module.scss';
const ElectionCaretLink = function ElectionCaretLink(props) {
  const {
    to,
    text,
    red,
    unstyled,
    tracking,
    ...restProps
  } = props;
  const pagePathPrefix = usePagePathPrefix();
  const manifest = usePagesManifest();
  const routerPath = useRouterPath();
  const words = text.split(' ');
  const first = words.slice(0, Math.max(0, words.length - 2));
  const last = words.slice(words.length - 2);
  const {
    url
  } = useMemo(() => resolveElectionLink({
    manifest,
    pagePathPrefix,
    link: to,
    currentUrl: routerPath
  }), [manifest, pagePathPrefix, to, routerPath]);
  const linkClass = red ? classes.red : classes.link;
  return <ElectionLink to={to} tracking={tracking} {...restProps}>
      <span className={classnames({
      [linkClass]: !unstyled && url
    })}>
        <IfActive active={!!url}>
          {first.join(' ')}
          {' '}
          <span className={classes.nobreak}>
            {last.join(' ')}
            {' '}
            <ElectionIcon type="LinkCaret" size="2" />
          </span>
        </IfActive>

        <IfActive active={!url}>
          {widont(text)}
        </IfActive>
      </span>
    </ElectionLink>;
};
ElectionCaretLink.defaultProps = {
  to: undefined,
  text: '',
  red: false,
  unstyled: false,
  tracking: {}
};
ElectionCaretLink.propTypes = {
  to: PropTypes.string,
  text: PropTypes.string,
  red: PropTypes.bool,
  unstyled: PropTypes.bool,
  tracking: PropTypes.shape({
    context: PropTypes.string
  })
};
export default ElectionCaretLink;