'use client'

import { useEffect, useMemo, useState } from 'react'
import { useTranslations } from 'next-intl'
import { ListTree, ChevronDown } from 'lucide-react'
import type { PageHeading } from '@/lib/cms/headingAnchors'

interface CmsTableOfContentsProps {
  headings: PageHeading[]
  // 'sidebar': sticky list next to the article (desktop)
  // 'inline': collapsible box above the article (mobile/tablet)
  variant: 'sidebar' | 'inline'
}

// A heading is "current" once its top has scrolled up to this line — just
// below the sticky header (headings also get scroll-margin-top: 6.5rem in
// styles.css, so a TOC click lands them right above it).
const ACTIVE_LINE_PX = 140

// Scroll-spy: the current section is the last heading whose top has passed
// ACTIVE_LINE_PX. Measured on scroll (rAF-throttled) rather than with an
// IntersectionObserver band, which misses headings that jump straight past it.
function useActiveHeading(ids: string[]): string | null {
  const [active, setActive] = useState<string | null>(ids[0] ?? null)

  useEffect(() => {
    let frame = 0
    const update = () => {
      frame = 0
      let current = ids[0] ?? null
      for (const id of ids) {
        const el = document.getElementById(id)
        if (el && el.getBoundingClientRect().top <= ACTIVE_LINE_PX) current = id
      }
      setActive(current)
    }
    const onScroll = () => {
      if (!frame) frame = requestAnimationFrame(update)
    }
    window.addEventListener('scroll', onScroll, { passive: true })
    onScroll()
    return () => {
      window.removeEventListener('scroll', onScroll)
      if (frame) cancelAnimationFrame(frame)
    }
  }, [ids])

  return active
}

export default function CmsTableOfContents({ headings, variant }: CmsTableOfContentsProps) {
  const t = useTranslations('CmsPage')
  // Stable array identity, so the scroll listener isn't re-attached every render.
  const ids = useMemo(() => headings.map((h) => h.id), [headings])
  const active = useActiveHeading(ids)

  const list = (
    <ol className="space-y-1 text-sm">
      {headings.map((h) => {
        const isActive = active === h.id
        return (
          <li key={h.id} className={h.level === 3 ? 'ps-4' : ''}>
            <a
              href={`#${h.id}`}
              className={`block rounded-lg px-3 py-1.5 border-s-2 transition ${
                isActive
                  ? 'border-primary bg-primary/10 text-primary font-medium'
                  : 'border-transparent text-gray-custom hover:text-dark hover:bg-gray-50'
              }`}
            >
              {h.text}
            </a>
          </li>
        )
      })}
    </ol>
  )

  if (variant === 'inline') {
    return (
      <details className="group mb-6 rounded-2xl border border-gray-100 bg-white shadow-sm lg:hidden">
        <summary className="flex cursor-pointer list-none items-center justify-between gap-3 px-5 py-4 font-semibold text-dark [&::-webkit-details-marker]:hidden">
          <span className="flex items-center gap-2"><ListTree size={18} className="text-primary" /> {t('onThisPage')}</span>
          <ChevronDown size={18} className="text-gray-custom transition-transform group-open:rotate-180" />
        </summary>
        <nav aria-label={t('onThisPage')} className="px-3 pb-4">{list}</nav>
      </details>
    )
  }

  return (
    <nav aria-label={t('onThisPage')} className="rounded-2xl border border-gray-100 bg-white p-4 shadow-sm">
      <p className="mb-3 flex items-center gap-2 px-3 text-xs font-semibold uppercase tracking-wider text-gray-custom">
        <ListTree size={15} className="text-primary" /> {t('onThisPage')}
      </p>
      {list}
    </nav>
  )
}
