import React, { forwardRef } from 'react';
import DocusaurusLink from '@docusaurus/Link';
import useDocusaurusContext from '@docusaurus/useDocusaurusContext';

const url = require('url');

const Link = forwardRef(function Link({ href, to = href, ...props }, ref) {
  const {
    siteConfig: { url: siteUrl, baseUrl = '/' },
  } = useDocusaurusContext();

  // if to is falsy, pass it through
  if (!to) return <DocusaurusLink {...props} ref={ref} />;

  // parse out site hostname
  const siteHost = url.parse(siteUrl).hostname;

  // compensate for double slash URL bases
  to = to.replace(/^\/\//, 'https://');

  // parse url
  const { hostname: toHost, pathname: toPath } = url.parse(to) || {};

  // test for same host
  const isSameHost = toHost === siteHost;

  // test for same base
  const baseRE = new RegExp(`^/?${baseUrl.replace(/^(\/?)(.+?)(\/?)$/, `$2`)}/?`);
  const isSameBase = baseUrl == '/' || baseRE.test(toPath);

  // if to URL is same base or same host, force trailing slash
  to = isSameBase || isSameHost ? (to.endsWith('/') ? to : `${to}/`) : to;

  // if to URL is same base, strip any protocol+hostname match
  const siteRE = new RegExp(`^https?://${siteHost}/?`);
  const dest = isSameBase ? { to: to.replace(siteRE, '/') } : { href: to };
  return <DocusaurusLink {...dest} {...props} ref={ref} />;
});

export default Link;
