import { createContext, useContext, useEffect, useMemo, useState, type ReactNode } from 'react'
import { useLocation } from 'react-router-dom'
import type { IslanderPageMeta } from './types'

type IslanderPageContextValue = {
  runtimeMeta: IslanderPageMeta | null
  setRuntimeMeta: (meta: IslanderPageMeta | null) => void
}

const IslanderPageContext = createContext<IslanderPageContextValue | null>(null)

export function IslanderPageProvider({ children }: { children: ReactNode }) {
  const { pathname } = useLocation()
  const [runtimeMeta, setRuntimeMeta] = useState<IslanderPageMeta | null>(null)

  useEffect(() => {
    setRuntimeMeta(null)
  }, [pathname])

  const value = useMemo(
    () => ({
      runtimeMeta,
      setRuntimeMeta,
    }),
    [runtimeMeta],
  )

  return <IslanderPageContext.Provider value={value}>{children}</IslanderPageContext.Provider>
}

export function useIslanderPageContext() {
  return useContext(IslanderPageContext)
}

/**
 * Optional per-page metadata for islander context & suggestions.
 * New pages under Layout work without this — DOM snapshot is automatic.
 */
export function useIslanderPage(meta?: IslanderPageMeta) {
  const ctx = useIslanderPageContext()
  const setRuntimeMeta = ctx?.setRuntimeMeta
  const hintKey = meta?.hints?.join('\u0001') ?? ''
  const suggestionKey = meta?.suggestions?.join('\u0001') ?? ''

  useEffect(() => {
    if (!setRuntimeMeta) return
    if (!meta) {
      setRuntimeMeta(null)
      return
    }
    setRuntimeMeta(meta)
    return () => setRuntimeMeta(null)
  }, [setRuntimeMeta, meta?.title, meta?.purpose, hintKey, suggestionKey])
}