import { WebSocketClient } from './client' import { BibleHighlight } from '@/types' import { addHighlight, updateHighlight, deleteHighlight } from '../highlight-manager' export class RealtimeSyncManager { private client: WebSocketClient private userId: string | null = null constructor(wsUrl: string) { this.client = new WebSocketClient(wsUrl) this.setupListeners() } private setupListeners(): void { this.client.on('highlight:create', (data) => this.handleHighlightCreate(data)) this.client.on('highlight:update', (data) => this.handleHighlightUpdate(data)) this.client.on('highlight:delete', (data) => this.handleHighlightDelete(data)) this.client.on('disconnected', () => this.handleDisconnect()) this.client.on('connected', () => this.handleConnect()) } async connect(userId: string): Promise { this.userId = userId await this.client.connect(userId) } async sendHighlightCreate(highlight: BibleHighlight): Promise { this.client.send('highlight:create', highlight) } async sendHighlightUpdate(highlight: BibleHighlight): Promise { this.client.send('highlight:update', highlight) } async sendHighlightDelete(highlightId: string): Promise { this.client.send('highlight:delete', { highlightId }) } private async handleHighlightCreate(data: BibleHighlight): Promise { try { await addHighlight(data) this.client.emit('local-update', { type: 'create', highlight: data }) } catch (error) { console.error('Failed to create highlight from remote:', error) } } private async handleHighlightUpdate(data: BibleHighlight): Promise { try { await updateHighlight(data) this.client.emit('local-update', { type: 'update', highlight: data }) } catch (error) { console.error('Failed to update highlight from remote:', error) } } private async handleHighlightDelete(data: { highlightId: string }): Promise { try { await deleteHighlight(data.highlightId) this.client.emit('local-update', { type: 'delete', highlightId: data.highlightId }) } catch (error) { console.error('Failed to delete highlight from remote:', error) } } private handleConnect(): void { console.log('WebSocket connected - real-time sync active') } private handleDisconnect(): void { console.log('WebSocket disconnected - falling back to polling') } disconnect(): void { this.client.disconnect() } isConnected(): boolean { return this.client.isConnected() } // Export client for direct event listening if needed get publicClient() { return this.client } }