import Link from 'next/link';
import React from 'react';
import { usePublicCoachSite } from './PublicCoachSiteProvider';

type BookingLinkProps = {
  href: string;
  children: React.ReactNode;
  className?: string;
};

export default function BookingLink({
  href,
  children,
  className,
}: BookingLinkProps) {
  const site = usePublicCoachSite();
  const isPlaceholder = /your-coach|example\.(com|org|net)/i.test(href);
  const resolvedHref = href && !isPlaceholder
    ? href
    : site.calendly.assessmentUrl;

  if (!resolvedHref) {
    return null;
  }

  const isExternal = /^https:\/\//.test(resolvedHref);

  if (/^http:\/\//.test(resolvedHref)) {
    return null;
  }

  if (isExternal) {
    return (
      <a href={resolvedHref} className={className} target='_blank' rel='noreferrer'>
        {children}
      </a>
    );
  }

  return (
    <Link href={resolvedHref} className={className}>
      {children}
    </Link>
  );
}
