// SPDX-License-Identifier: AGPL-3.0-or-later
// Copyright (C) 2026 Karim Gabriele Varano
import { useState, useEffect } from 'react'
import LibraryBrowser from './components/LibraryBrowser'
import { notifyReady, onMessage, send } from './lib/rhinoBridge'

export default function LibraryApp() {
  const [manifest,    setManifest]    = useState({ items: [] })
  const [importedIds, setImportedIds] = useState([])
  const [libraryRoot, setLibraryRoot] = useState('')

  useEffect(() => {
    onMessage('LIBRARY_STATE', ({ manifest, importedIds, libraryRoot }) => {
      if (manifest)    setManifest(manifest)
      if (importedIds) setImportedIds(importedIds)
      if (libraryRoot) setLibraryRoot(libraryRoot)
    })
    notifyReady()
    const blockContext = (ev) => ev.preventDefault()
    document.addEventListener('contextmenu', blockContext)
    return () => document.removeEventListener('contextmenu', blockContext)
  }, [])

  return (
    <LibraryBrowser
      manifest={manifest}
      importedIds={importedIds}
      libraryRoot={libraryRoot}
      onImport={(id) => send('IMPORT_ITEM', { id })}
      onReload={() => send('RELOAD', {})}
      onClose={() => send('CLOSE', {})}
    />
  )
}
