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

/**
 * A title split into coloured spans the way the inner pages mark it up, e.g.
 * <span class="text-[#0056D2]">Integrating Science, AI,</span>{" "}<span class="text-ink"> and …</span>.
 * The highlight gets `hl`, the text around it `rest`. Without a highlight the whole
 * title is one `rest` span (or plain text when `rest` is omitted).
 */
export function SplitTitle({ title, hl, rest }: { title: RichTitle; hl: string; rest?: string }) {
  const { text, highlight } = title;
  const at = highlight ? text.indexOf(highlight) : -1;
  if (!highlight || at < 0) return rest ? <span className={rest}>{text}</span> : <>{text}</>;
  const parts: ReactNode[] = [];
  const before = text.slice(0, at);
  const after = text.slice(at + highlight.length);
  if (before.trim()) parts.push(<span key="b" className={rest}>{before}</span>);
  parts.push(<span key="h" className={hl}>{highlight}</span>);
  if (after.trim()) parts.push(<span key="a" className={rest}>{after}</span>);
  return <>{spaced(parts)}</>;
}

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

/** Paragraphs separated by a blank line ("\n\n"); `first` styles the first, `next` the others. */
export function paragraphs(body: string): string[] {
  return body
    .split(/\n\s*\n/)
    .map((p) => p.trim())
    .filter(Boolean);
}

export type Crumb = { label: string; href?: string };

/** The page-hero breadcrumb: Home > … > current page. */
export function Breadcrumb({ items, wrap = false }: { items: Crumb[]; wrap?: boolean }) {
  return (
    <nav className="mt-4 text-[13px] text-white/70" aria-label="Breadcrumb">
      <ol className={wrap ? "inline-flex items-center gap-2 flex-wrap justify-center" : "inline-flex items-center gap-2"}>
        {items.map((c, i) => (
          <Fragment key={i}>
            {i > 0 && (
              <li aria-hidden="true" className="text-white/40">
                &gt;
              </li>
            )}
            {c.href ? (
              <li>
                <Link href={c.href} className="hover:text-white transition-colors">
                  {c.label}
                </Link>
              </li>
            ) : (
              <li className="text-white/90" aria-current="page">
                {c.label}
              </li>
            )}
          </Fragment>
        ))}
      </ol>
    </nav>
  );
}
