'use client'

import { useMemo, useSyncExternalStore } from 'react'

/**
 * Tiny per-browser store for the pilot car replica (Phase 1). The pilot
 * dispatch dashboard and the pilot trip workspace preview are different pages,
 * so "did the company upload its documents?" has to survive navigation — but
 * it must never reach a server. sessionStorage + a window event, read through
 * useSyncExternalStore so server render and hydration agree.
 */
const EVENT = 'hha-pilot-preview-store'

function read(key: string): string | null {
  try {
    return sessionStorage.getItem(key)
  } catch {
    return null
  }
}

export function writePreviewValue(key: string, value: unknown) {
  try {
    sessionStorage.setItem(key, JSON.stringify(value))
    window.dispatchEvent(new Event(EVENT))
  } catch {
    // storage unavailable — the page keeps its in-memory state only
  }
}

function subscribe(cb: () => void) {
  window.addEventListener(EVENT, cb)
  window.addEventListener('storage', cb)
  return () => {
    window.removeEventListener(EVENT, cb)
    window.removeEventListener('storage', cb)
  }
}

/** Parsed value from sessionStorage, or `fallback` on the server / when unset. */
export function usePreviewValue<T>(key: string, fallback: T): T {
  const raw = useSyncExternalStore(subscribe, () => read(key), () => null)
  return useMemo(() => {
    if (raw === null) return fallback
    try {
      return JSON.parse(raw) as T
    } catch {
      return fallback
    }
  }, [raw, fallback])
}

export const PILOT_COMPANY_DOCS_KEY = 'hha-pilot-preview-company-docs'
