import { ISLANDER_CONFIG } from './config'
import type { IslanderPageMeta } from './types'

type RouteEntry = {
  pattern: RegExp
  meta: IslanderPageMeta
}

const routeEntries: RouteEntry[] = []

/** Register static page metadata (optional; DOM snapshot works without this). */
export function registerIslanderPage(pattern: RegExp, meta: IslanderPageMeta) {
  routeEntries.push({ pattern, meta })
}

export function matchRegisteredPage(pathname: string): IslanderPageMeta | null {
  for (const entry of routeEntries) {
    if (entry.pattern.test(pathname)) return entry.meta
  }
  return null
}

export function readLivePageTitle(): string | null {
  if (typeof document === 'undefined') return null
  for (const selector of ISLANDER_CONFIG.pageTitleSelectors) {
    const el = document.querySelector(selector)
    const text = el?.textContent?.replace(/\s+/g, ' ').trim()
    if (text) return text.slice(0, 80)
  }
  return null
}

export function resolveIslanderPageMeta(
  pathname: string,
  runtimeMeta?: IslanderPageMeta | null,
): IslanderPageMeta {
  const registered = matchRegisteredPage(pathname)
  const liveTitle = readLivePageTitle()

  return {
    title: runtimeMeta?.title ?? registered?.title ?? liveTitle ?? '巡樓管理台',
    purpose: runtimeMeta?.purpose ?? registered?.purpose,
    hints: runtimeMeta?.hints ?? registered?.hints,
    suggestions: runtimeMeta?.suggestions ?? registered?.suggestions ?? [...ISLANDER_CONFIG.defaultSuggestions],
  }
}