import Link from "next/link";
import { Fragment, type ReactNode } from "react";
import type { Cta, RichTitle } from "@/app/(site)/_lib/content";

/** Title with its `highlight` words in brand blue, as the static pages marked them up. Text is always escaped. */
export function Title({ title }: { title: RichTitle }) {
  const { text, highlight } = title;
  const at = highlight ? text.indexOf(highlight) : -1;
  if (!highlight || at < 0) return <>{text}</>;
  return (
    <>
      {text.slice(0, at)}
      <span className="text-[#1f63d6]">{highlight}</span>
      {text.slice(at + highlight.length)}
    </>
  );
}

/** Plain text with "\n" line breaks as <br />. */
export function Lines({ text }: { text: string }) {
  const lines = text.split("\n");
  return (
    <>
      {lines.map((line, i) => (
        <Fragment key={i}>
          {i > 0 && <br />}
          {line}
        </Fragment>
      ))}
    </>
  );
}

const isInternal = (href: string) => href.startsWith("/") && !href.startsWith("//");

/** A CMS link: next/link for site routes, <a> for anchors, mail/tel and external URLs. */
export function CtaLink({ cta, className, children }: { cta: Cta; className?: string; children?: ReactNode }) {
  const external = cta.openInNewTab ? { target: "_blank", rel: "noopener noreferrer" } : {};
  const content = children ?? cta.label;
  if (isInternal(cta.href) && !cta.openInNewTab)
    return (
      <Link href={cta.href} className={className}>
        {content}
      </Link>
    );
  return (
    <a href={cta.href} className={className} {...external}>
      {content}
    </a>
  );
}

/** Puts `sep` (the static markup's {" "}) between items. */
export function joined(nodes: ReactNode[], sep: ReactNode = " "): ReactNode[] {
  return nodes.flatMap((n, i) => (i === 0 ? [n] : [<Fragment key={`s${i}`}>{sep}</Fragment>, n]));
}
