import Link from "next/link";
import { LEGAL_NAV_LINKS } from "@/lib/legal/nav";
import type { LegalSection } from "@/lib/legal/types";

type LegalDocumentProps = {
  kicker: string;
  title: string;
  lastUpdated: string;
  intro?: string;
  sections: LegalSection[];
};

const linkClass =
  "font-medium text-primary underline decoration-line underline-offset-2 hover:text-accent";

function renderInlineLinks(text: string) {
  const parts = text.split(/(\[[^\]]+\]\([^)]+\))/g);

  return parts.map((part, index) => {
    const match = part.match(/^\[([^\]]+)\]\(([^)]+)\)$/);
    if (!match) {
      return part;
    }

    const [, label, href] = match;
    const isExternal = href.startsWith("http");

    if (isExternal) {
      return (
        <a key={index} className={linkClass} href={href} rel="noopener noreferrer" target="_blank">
          {label}
        </a>
      );
    }

    return (
      <Link key={index} className={linkClass} href={href}>
        {label}
      </Link>
    );
  });
}

export function LegalDocument({ kicker, title, lastUpdated, intro, sections }: LegalDocumentProps) {
  return (
    <main id="main-content" className="flex-1">
      <section className="pt-[72px] pb-10" aria-labelledby="legal-document-heading">
        <div className="mx-auto w-full max-w-page px-4 md:px-6">
          <p className="text-[0.72rem] font-medium tracking-[0.16em] text-ink-40 uppercase">{kicker}</p>
          <h1 className="mt-2 max-w-[20ch]" id="legal-document-heading">
            {title}
          </h1>
          <p className="mt-4 text-[0.92rem] text-ink-60">
            Last updated: <time>{lastUpdated}</time>
          </p>
          {intro ? <p className="mt-5 max-w-[62ch] text-[1.02rem] leading-relaxed text-ink-60">{intro}</p> : null}
          <p className="mt-4 max-w-[72ch] rounded-pv border border-line bg-surface px-4 py-3 text-[0.88rem] leading-relaxed text-ink-60">
            This document is provided for informational purposes and is subject to final legal review. It
            does not constitute legal advice.
          </p>
        </div>
      </section>

      <section className="pb-[88px]">
        <div className="mx-auto w-full max-w-page px-4 md:px-6">
          <div className="grid grid-cols-1 items-start gap-10 lg:grid-cols-[minmax(0,240px)_minmax(0,1fr)] lg:gap-14">
            <nav
              aria-label="Table of contents"
              className="rounded-pv border border-line bg-surface p-5 lg:sticky lg:top-[calc(var(--spacing-header)+24px)]"
            >
              <h2 className="font-display text-[0.7rem] font-medium tracking-[0.14em] text-ink-40 uppercase">
                On this page
              </h2>
              <ol className="mt-3 flex list-none flex-col gap-2 p-0">
                {sections.map((section) => (
                  <li key={section.id}>
                    <a
                      className="block text-[0.88rem] leading-snug text-ink-60 hover:text-primary"
                      href={`#${section.id}`}
                    >
                      {section.title.replace(/^\d+\.\s*/, "")}
                    </a>
                  </li>
                ))}
              </ol>
            </nav>

            <article className="min-w-0 max-w-[760px]">
              {sections.map((section) => (
                <section
                  key={section.id}
                  id={section.id}
                  className="scroll-mt-[calc(var(--spacing-header)+24px)] border-b border-line py-9 last:border-b-0"
                  aria-labelledby={`${section.id}-heading`}
                >
                  <h2 className="font-display text-[1.35rem] leading-snug text-primary" id={`${section.id}-heading`}>
                    {section.title}
                  </h2>
                  <div className="mt-4 space-y-4 text-[0.96rem] leading-relaxed text-ink-60">
                    {section.paragraphs.map((paragraph, index) => (
                      <p key={index} className="whitespace-pre-line">
                        {renderInlineLinks(paragraph)}
                      </p>
                    ))}
                    {section.lists?.map((list, listIndex) => {
                      const ListTag = list.type === "ol" ? "ol" : "ul";
                      const listClass =
                        list.type === "ol"
                          ? "list-decimal space-y-2 pl-5"
                          : "list-disc space-y-2 pl-5";

                      return (
                        <ListTag key={listIndex} className={listClass}>
                          {list.items.map((item, itemIndex) => (
                            <li key={itemIndex}>{renderInlineLinks(item)}</li>
                          ))}
                        </ListTag>
                      );
                    })}
                  </div>
                </section>
              ))}

              <nav
                aria-label="Related legal pages"
                className="mt-10 flex flex-wrap gap-x-4 gap-y-2 border-t border-line pt-6 text-[0.9rem] text-ink-60"
              >
                {LEGAL_NAV_LINKS.map((link) => (
                  <Link key={link.href} className={linkClass} href={link.href}>
                    {link.label}
                  </Link>
                ))}
              </nav>
            </article>
          </div>
        </div>
      </section>
    </main>
  );
}
