'use client' import { useState, useCallback, useEffect } from 'react' import { getNoteById } from '@/app/actions/notes' import type { Note } from '@/lib/types' import { NOTE_PEEK_OPEN_EVENT, NOTE_PEEK_CLOSE_EVENT, type NotePeekOpenDetail, } from '@/lib/note-peek-sync' interface UseNotePeekOptions { selfNoteId?: string } export function useNotePeek(opts: UseNotePeekOptions = {}) { const { selfNoteId } = opts const [note, setNote] = useState(null) const [blockId, setBlockId] = useState(undefined) const [loading, setLoading] = useState(false) const [isOpen, setIsOpen] = useState(false) const open = useCallback(async (targetNoteId: string, targetBlockId?: string) => { if (selfNoteId && targetNoteId === selfNoteId) return setLoading(true) setIsOpen(true) setBlockId(targetBlockId) try { const fetched = await getNoteById(targetNoteId) if (fetched) setNote(fetched) } catch { // silent } finally { setLoading(false) } }, [selfNoteId]) const close = useCallback(() => { setIsOpen(false) setNote(null) setBlockId(undefined) }, []) useEffect(() => { const onOpen = (e: Event) => { const detail = (e as CustomEvent).detail if (!detail) return void open(detail.noteId, detail.blockId) } const onClose = () => close() window.addEventListener(NOTE_PEEK_OPEN_EVENT, onOpen) window.addEventListener(NOTE_PEEK_CLOSE_EVENT, onClose) return () => { window.removeEventListener(NOTE_PEEK_OPEN_EVENT, onOpen) window.removeEventListener(NOTE_PEEK_CLOSE_EVENT, onClose) } }, [open, close]) return { note, blockId, loading, isOpen, open, close } }