import { Fragment } from "react";

import { Prose } from "@/components/docs/prose";
import { Container } from "@/components/ui/container";
import type { Locale } from "@/lib/i18n";
import type { LegalBlock, LegalDocument } from "@/lib/legal/types";

// Matches https URLs and bare email addresses so legal copy can stay as plain
// strings while emails/links render as clickable anchors.
const LINK_RE = /(https?:\/\/[^\s)]+|[\w.+-]+@[\w-]+\.[\w.-]+)/g;

function linkify(text: string) {
  return text.split(LINK_RE).map((part, i) => {
    // Capturing-group split puts matches at odd indices.
    if (i % 2 === 0) return <Fragment key={i}>{part}</Fragment>;
    const trailing = part.match(/[.,;:]+$/)?.[0] ?? "";
    const token = trailing ? part.slice(0, -trailing.length) : part;
    const isEmail = !token.startsWith("http") && token.includes("@");
    return (
      <Fragment key={i}>
        <a
          href={isEmail ? `mailto:${token}` : token}
          {...(isEmail ? {} : { target: "_blank", rel: "noreferrer" })}
        >
          {token}
        </a>
        {trailing}
      </Fragment>
    );
  });
}

function renderBlock(block: LegalBlock, i: number) {
  switch (block.type) {
    case "subheading":
      return <h3 key={i}>{block.text}</h3>;
    case "list":
      return (
        <ul key={i}>
          {block.items.map((item, j) => (
            <li key={j}>{linkify(item)}</li>
          ))}
        </ul>
      );
    default:
      return <p key={i}>{linkify(block.text)}</p>;
  }
}

export function LegalPage({ doc, lang }: { doc: LegalDocument; lang: Locale }) {
  const updatedLabel = lang === "fr" ? "Dernière mise à jour" : "Last updated";
  const formatted = new Intl.DateTimeFormat(lang === "fr" ? "fr-FR" : "en-GB", {
    dateStyle: "long",
  }).format(new Date(`${doc.updated}T00:00:00Z`));

  return (
    <Container className="py-20 lg:py-28">
      <Prose as="article" className="mx-auto">
        <h1>{doc.title}</h1>
        <p className="text-ink-3 text-sm">
          {updatedLabel}: {formatted}
        </p>
        <p>{doc.intro}</p>
        {doc.sections.map((section) => (
          <section key={section.id}>
            <h2 id={section.id}>{section.heading}</h2>
            {section.blocks.map(renderBlock)}
          </section>
        ))}
      </Prose>
    </Container>
  );
}
