'use client';

import { useEffect, useState, type MouseEvent } from 'react';
import type { LegalSection } from '@/types';
import { ArrowUpIcon } from '@/components/icons/common';

const pad = (n: number) => String(n).padStart(2, '0');

interface LegalContentsProps {
  sections: Pick<LegalSection, 'id' | 'title'>[];
  effectiveDate: string;
  contactEmail: string;
}

/** Contents list with scroll-spy + back-to-top button (port of privacy-policy.js). */
export default function LegalContents({ sections, effectiveDate, contactEmail }: LegalContentsProps) {
  const [activeId, setActiveId] = useState(sections[0]?.id);
  const [showTop, setShowTop] = useState(false);

  useEffect(() => {
    const elements = sections.map((s) => document.getElementById(s.id)).filter((el): el is HTMLElement => !!el);
    const observer = new IntersectionObserver(
      (entries) => entries.forEach((entry) => entry.isIntersecting && setActiveId(entry.target.id)),
      { rootMargin: '-100px 0px -70% 0px', threshold: 0 },
    );
    elements.forEach((el) => observer.observe(el));

    const onScroll = () => setShowTop(window.scrollY > 600);
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => {
      observer.disconnect();
      window.removeEventListener('scroll', onScroll);
    };
  }, [sections]);

  const goTo = (id: string) => (e: MouseEvent<HTMLAnchorElement>) => {
    const target = document.getElementById(id);
    if (!target) return;
    e.preventDefault();
    target.scrollIntoView({ behavior: 'smooth', block: 'start' });
    history.replaceState(null, '', `#${id}`);
  };

  return (
    <>
      <nav className="legal-contents">
        <span className="text-xs fw-600 text-uppercase color-golden">Contents</span>
        <ul className="legal-contents-list pt-2 mb-0">
          {sections.map((section, index) => (
            <li key={section.id}>
              <a href={`#${section.id}`} className={section.id === activeId ? 'active' : undefined} onClick={goTo(section.id)}>
                <span className="legal-contents-num text-sm fw-600">{pad(index + 1)}</span>{' '}
                <span className="legal-contents-text text-sm fw-400">{section.title}</span>
              </a>
            </li>
          ))}
        </ul>
        <div className="legal-contents-meta d-flex flex-column gap-1">
          <span className="text-xs fw-600 text-uppercase color-golden">Effective date</span>{' '}
          <span className="text-sm fw-400 color-white">{effectiveDate}</span>{' '}
          <span className="text-sm fw-400 color-content">
            Questions:{' '}
            <a href={`mailto:${contactEmail}`} className="color-golden">
              {contactEmail}
            </a>
          </span>
        </div>
      </nav>

      <button
        type="button"
        className={`back-to-top${showTop ? ' show' : ''}`}
        id="backToTop"
        aria-label="Back to top"
        onClick={() => window.scrollTo({ top: 0, behavior: 'smooth' })}
      >
        <ArrowUpIcon />
      </button>
    </>
  );
}
