"use client"

import { useState, useRef, useEffect, memo } from "react"
import { formatTime } from "./timeline-helpers"
import { TimelineSectionCard } from "./timeline-section-card"
import type { TimelineSection } from "./timeline-types"

interface TimelinePageViewProps {
  sections: TimelineSection[]
  totalDuration: number
  functionName?: string | null
  filePath?: string | null
}

export const TimelinePageView = memo(function TimelinePageView({
  sections,
  totalDuration,
  functionName,
  filePath,
}: TimelinePageViewProps) {
  const [activeIndex, setActiveIndex] = useState(0)
  const sectionRefs = useRef<(HTMLDivElement | null)[]>([])
  const refCallbacks = useRef(new Map<number, (el: HTMLDivElement | null) => void>())

  function getSectionRef(index: number) {
    let cb = refCallbacks.current.get(index)
    if (!cb) {
      cb = (el: HTMLDivElement | null) => { sectionRefs.current[index] = el }
      refCallbacks.current.set(index, cb)
    }
    return cb
  }

  useEffect(() => {
    const observer = new IntersectionObserver(
      (entries) => {
        let bestIndex = -1
        let bestDistance = Infinity

        for (const entry of entries) {
          if (!entry.isIntersecting) continue

          const index = Number(entry.target.getAttribute("data-section-index"))
          if (isNaN(index)) continue

          // Find section closest to 35% from top of viewport
          const rect = entry.boundingClientRect
          const sectionMiddle = rect.top + rect.height / 2
          const distance = Math.abs(sectionMiddle - window.innerHeight * 0.35)

          if (distance < bestDistance) {
            bestDistance = distance
            bestIndex = index
          }
        }

        if (bestIndex >= 0) {
          setActiveIndex(bestIndex)
        }
      },
      {
        threshold: [0, 0.1, 0.25, 0.5, 0.75, 1.0],
        rootMargin: "-10% 0px -55% 0px",
      }
    )

    sectionRefs.current.forEach((ref, index) => {
      if (ref) {
        ref.setAttribute("data-section-index", String(index))
        observer.observe(ref)
      }
    })

    return () => observer.disconnect()
  }, [sections.length])

  if (sections.length === 0) {
    return (
      <div className="flex items-center justify-center py-20 text-zinc-400">
        No timeline data available
      </div>
    )
  }

  const activeSection = sections[activeIndex]
  const shouldExpandContainer =
    activeSection?.content.type === "candidate" ||
    activeSection?.content.type === "refinement"

  return (
    <div className="relative">
      <div className="sticky top-0 z-30 bg-white/80 dark:bg-zinc-900/80 backdrop-blur-sm border-b border-zinc-200 dark:border-zinc-700 mb-6">
        <div className="max-w-6xl mx-auto px-4 py-3">
          <div className="flex items-center justify-between mb-2">
            <div>
              <h2 className="text-sm font-medium text-zinc-900 dark:text-white">
                Optimization Timeline
              </h2>
              {functionName && (
                <p className="text-xs text-zinc-500 dark:text-zinc-400">
                  {functionName}
                  {filePath && <span className="ml-1 opacity-60">in {filePath}</span>}
                </p>
              )}
            </div>
            <div className="text-right">
              <span className="text-xs text-zinc-500 dark:text-zinc-400">
                {activeIndex + 1} of {sections.length} {"\u00b7"} {formatTime(totalDuration)}
              </span>
            </div>
          </div>

          <div className="h-1 bg-zinc-200 dark:bg-zinc-700 rounded-full overflow-hidden">
            <div
              className="h-full bg-zinc-400 dark:bg-zinc-500 transition-all duration-200"
              style={{ width: `${((activeIndex + 1) / sections.length) * 100}%` }}
            />
          </div>
        </div>
      </div>

      <div
        className={`mx-auto px-4 pb-20 relative transition-all duration-300 ${
          shouldExpandContainer ? "max-w-[95vw]" : "max-w-6xl"
        }`}
      >
        <div className="sticky top-1/2 -translate-y-1/2 z-20 pointer-events-none h-0">
          <div className="absolute right-4 -top-2">
            <div className="w-4 h-4 rounded-full bg-zinc-400 dark:bg-zinc-500 border-2 border-white dark:border-zinc-900" />
          </div>
        </div>

        {sections.map((section, index) => (
          <div
            key={section.id}
            ref={getSectionRef(index)}
            className="scroll-mt-24"
          >
            <TimelineSectionCard
              section={section}
              isActive={index === activeIndex}
              index={index}
              totalSections={sections.length}
            />
          </div>
        ))}

        <div className="relative">
          <div className="absolute right-6 top-0 h-6 w-px bg-zinc-200 dark:bg-zinc-700" />
          <div className="absolute right-4 top-6 w-4 h-4 rounded-full bg-zinc-300 dark:bg-zinc-600 border-2 border-white dark:border-zinc-900 z-10" />
          <div className="mr-14 py-4 text-right">
            <span className="text-xs text-zinc-500 dark:text-zinc-400">
              End
            </span>
          </div>
        </div>
      </div>
    </div>
  )
})
