// Read-side selector for the local in-flight queue. Subscribes to the same
// per-instance MMKV key `emit()` writes to, so pending letters can be
// rendered as a tail on the live row before the debounced flush fires.

import { useEffect, useState } from 'react'
import { appStorage } from 'src/state/storage'
import { queueKey } from './emit'

/**
 * Live string of letters currently waiting in the local queue for `host`.
 * Empty when nothing is pending. Updates synchronously when `emit()` writes
 * a letter and when the flush clears the key.
 */
export function useTapestryQueue(host: string): string {
  const [letters, setLetters] = useState<string>(
    () => appStorage.getString(queueKey(host)) ?? ''
  )

  useEffect(() => {
    const key = queueKey(host)
    // Re-read on host change — the previous host's queue is unrelated.
    setLetters(appStorage.getString(key) ?? '')
    const sub = appStorage.addOnValueChangedListener((changed) => {
      if (changed === key) {
        setLetters(appStorage.getString(key) ?? '')
      }
    })
    return () => sub.remove()
  }, [host])

  return letters
}
