'use client';

import { AnimatePresence, motion, useReducedMotion } from 'framer-motion';
import { AlertTriangle, ArrowUp, CalendarDays } from 'lucide-react';
import { useEffect, useState } from 'react';

import { cn } from '@/lib/utils';

export function LegalDocument({
  title,
  updated,
  sections,
}: {
  title: string;
  updated: string;
  sections: ReadonlyArray<{ id: string; heading: string; paragraphs: readonly string[] }>;
}) {
  const reduce = useReducedMotion();
  const [active, setActive] = useState(sections[0]?.id ?? '');
  const [showTop, setShowTop] = useState(false);

  useEffect(() => {
    const onScroll = () => {
      setShowTop(window.scrollY > 600);
      // The active heading is the last one that has scrolled above the reading line.
      let current = sections[0]?.id ?? '';
      for (const section of sections) {
        const element = document.getElementById(section.id);
        if (element !== null && element.getBoundingClientRect().top <= 140) current = section.id;
      }
      if (window.innerHeight + window.scrollY >= document.documentElement.scrollHeight - 4) {
        current = sections[sections.length - 1]?.id ?? current;
      }
      setActive(current);
    };
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, [sections]);

  return (
    <section className="relative pb-16 pt-28 md:pb-24 md:pt-36">
      <div className="mx-auto grid max-w-marketing gap-12 px-5 md:px-8 lg:grid-cols-[14rem_minmax(0,1fr)] xl:gap-20">
        <aside className="hidden lg:block">
          <nav aria-label="On this page" className="sticky top-28">
            <p className="text-caption font-semibold uppercase tracking-[0.14em] text-subtle-foreground">On this page</p>
            <ul className="mt-4 grid gap-0.5 border-l border-border">
              {sections.map((section) => {
                const isActive = active === section.id;
                return (
                  <li key={section.id}>
                    <a
                      href={`#${section.id}`}
                      aria-current={isActive ? 'location' : undefined}
                      className={cn(
                        '-ml-px block border-l-2 py-1.5 pl-4 text-small transition-colors duration-180',
                        isActive ? 'border-primary font-semibold text-primary' : 'border-transparent text-muted-foreground hover:border-border-strong hover:text-foreground',
                      )}
                    >
                      {section.heading}
                    </a>
                  </li>
                );
              })}
            </ul>
          </nav>
        </aside>

        <article className="w-full max-w-[720px]">
          <header className="border-b border-border pb-8">
            <p className="inline-flex rounded-pill bg-primary-soft px-3 py-1 text-caption font-semibold uppercase tracking-[0.14em] text-primary">Legal</p>
            <h1 className="mt-4 font-display text-[2.25rem] font-extrabold leading-[2.75rem] tracking-[-0.03em] md:text-display-lg">{title}</h1>
            <p className="mt-3 inline-flex items-center gap-1.5 text-small text-muted-foreground">
              <CalendarDays className="h-4 w-4" aria-hidden="true" />
              Last updated <time>{updated}</time>
            </p>
            <div className="mt-6 flex gap-3 rounded-lg border border-warning/30 bg-warning-soft px-4 py-3 text-body text-foreground" role="note">
              <AlertTriangle className="mt-0.5 h-5 w-5 shrink-0 text-warning" aria-hidden="true" />
              <p>These documents are templates. Have them reviewed by a legal professional before launch.</p>
            </div>
          </header>

          <div className="[&_a]:text-primary [&_a]:underline [&_a]:underline-offset-4 [&_li]:mt-2 [&_ul]:mt-4 [&_ul]:list-disc [&_ul]:pl-6">
            {sections.map((section) => (
              <section key={section.id} id={section.id} className="scroll-mt-28" aria-labelledby={`${section.id}-heading`}>
                <h2 id={`${section.id}-heading`} className="mt-12 font-display text-[24px] font-bold leading-8 tracking-[-0.01em] text-foreground">
                  {section.heading}
                </h2>
                {section.paragraphs.map((paragraph) => (
                  <p key={paragraph} className="mt-4 text-[16px] leading-7 text-muted-foreground">
                    {paragraph}
                  </p>
                ))}
              </section>
            ))}
          </div>
        </article>
      </div>

      <AnimatePresence>
        {showTop ? (
          <motion.button
            type="button"
            initial={reduce ? { opacity: 0 } : { opacity: 0, y: 8 }}
            animate={{ opacity: 1, y: 0 }}
            exit={reduce ? { opacity: 0 } : { opacity: 0, y: 8 }}
            transition={{ duration: 0.18 }}
            className="fixed bottom-6 right-6 z-30 inline-flex min-h-11 items-center gap-2 rounded-pill border border-border bg-surface/90 px-4 text-small font-semibold shadow-md backdrop-blur transition-colors hover:bg-surface-muted"
            onClick={() => window.scrollTo({ top: 0, behavior: reduce ? 'auto' : 'smooth' })}
          >
            <ArrowUp className="h-4 w-4" aria-hidden="true" />
            Back to top
          </motion.button>
        ) : null}
      </AnimatePresence>
    </section>
  );
}
