'use client'

import { useEffect } from 'react'
import { addToRecentlyViewed, getRecentlyViewedIds } from '@/lib/usage'

export function TrackNoteView({ noteId }: { noteId: string }) {
  useEffect(() => {
    addToRecentlyViewed(noteId)

    // Track co-usage with previously viewed notes
    const recentIds = getRecentlyViewedIds()
    // Track co-usage with up to 3 most recent notes (excluding current)
    const previousNotes = recentIds.filter(id => id !== noteId).slice(0, 3)

    for (const prevNoteId of previousNotes) {
      fetch('/api/usage/co-usage', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ fromNoteId: prevNoteId, toNoteId: noteId }),
      }).catch(() => {}) // Silently fail
    }
  }, [noteId])

  return null
}
