'use client'

import { useEffect, useMemo, useState } from 'react'
import { PublicInset, PublicPageHeader } from '@/components/public-surface'
import { ManualsPageShell } from '@/components/manuals-page-shell'
import { groupManuals, getCategories, getManufacturers } from '@/lib/manuals-catalog'
import { fetchPublishedManualsCatalog } from '@/lib/manuals-live-catalog'
import type { Manual } from '@/lib/manuals-types'

interface ManualsPageExperienceProps {
  initialManuals: Manual[]
}

export function ManualsPageExperience({ initialManuals }: ManualsPageExperienceProps) {
  const [manuals, setManuals] = useState(initialManuals)

  useEffect(() => {
    let cancelled = false

    void (async () => {
      const liveManuals = await fetchPublishedManualsCatalog()
      if (cancelled || liveManuals.length === 0) {
        return
      }

      setManuals((current) => {
        if (liveManuals.length === current.length) {
          return current
        }

        return liveManuals
      })
    })()

    return () => {
      cancelled = true
    }
  }, [])

  const groupedManuals = useMemo(() => groupManuals(manuals), [manuals])
  const manufacturers = useMemo(() => getManufacturers(manuals), [manuals])
  const categories = useMemo(() => getCategories(manuals), [manuals])

  return (
    <>
      <PublicPageHeader
        eyebrow="Manual Library"
        title="Vending Machine Manuals"
        description="Download manuals, service guides, and parts documentation for hundreds of vending machine models. Browse by manufacturer, machine type, or search by model details."
      >
        <PublicInset className="inline-flex w-fit items-center gap-2 rounded-full px-4 py-2 text-sm text-muted-foreground shadow-none">
          <span>
            <strong>{manuals.length}</strong> manuals available from <strong>{manufacturers.length}</strong> manufacturers
          </span>
        </PublicInset>
      </PublicPageHeader>

      <div className="mt-8 md:mt-10">
        <ManualsPageShell
          manuals={manuals}
          groupedManuals={groupedManuals}
          manufacturers={manufacturers}
          categories={categories}
        />
      </div>
    </>
  )
}
