import Link from "next/link";
import { breadcrumbSchema, type Crumb, type JsonLdObject } from "@/lib/schema";
import { cn } from "@/lib/cn";

/** JSON-LD data block. `<` is escaped so content can never close the script tag. */
export function JsonLd({ data }: { data: JsonLdObject | JsonLdObject[] }) {
  return (
    <script
      type="application/ld+json"
      dangerouslySetInnerHTML={{ __html: JSON.stringify(data).replace(/</g, "\\u003c") }}
    />
  );
}

export function Breadcrumbs({ items, tone = "light", className }: { items: Crumb[]; tone?: "light" | "dark"; className?: string }) {
  return (
    <>
      <nav aria-label="Breadcrumb" className={className}>
        <ol className={cn("flex flex-wrap items-center gap-x-2 gap-y-1 text-sm", tone === "dark" ? "text-night-muted" : "text-muted")}>
          {items.map((item, index) => {
            const last = index === items.length - 1;
            return (
              <li key={item.href} className="flex items-center gap-2">
                {last ? (
                  <span aria-current="page" className={tone === "dark" ? "text-night-text" : "text-ink-soft"}>
                    {item.name}
                  </span>
                ) : (
                  <Link href={item.href} className="link-underline-hover transition-colors hover:text-ink">
                    {item.name}
                  </Link>
                )}
                {last ? null : <span aria-hidden="true">/</span>}
              </li>
            );
          })}
        </ol>
      </nav>
      <JsonLd data={breadcrumbSchema(items)} />
    </>
  );
}

export function IllustrativeTag({ tone = "light", className }: { tone?: "light" | "dark"; className?: string }) {
  return (
    <span
      className={cn(
        "inline-flex items-center gap-2 rounded-sm border px-2 py-1 font-mono text-data uppercase tracking-[0.1em]",
        tone === "dark" ? "border-night-line text-night-muted" : "border-line text-muted",
        className,
      )}
    >
      <span aria-hidden="true" className={cn("size-1.5 rounded-full", tone === "dark" ? "bg-signal-bright" : "bg-signal")} />
      Illustrative data
    </span>
  );
}
