/**
 * Per-item playback bookmarks. Persisted in localStorage keyed by Jellyfin
 * itemId. Each entry has a position (in seconds) and an optional note.
 *
 * Storage shape: `jf_bookmarks_<itemId>` -> `Bookmark[]` JSON.
 */

export interface Bookmark {
  /** Unique id within this item. Random string. */
  id: string
  /** Position in seconds. */
  positionSec: number
  /** Optional user note. */
  note?: string
  /** Created at, ms since epoch. */
  createdAt: number
}

const KEY_PREFIX = 'jf_bookmarks_'

function key(itemId: string): string {
  return `${KEY_PREFIX}${itemId}`
}

export function loadBookmarks(itemId: string): Bookmark[] {
  if (!itemId) return []
  try {
    const raw = localStorage.getItem(key(itemId))
    if (!raw) return []
    const parsed = JSON.parse(raw)
    return Array.isArray(parsed) ? (parsed as Bookmark[]) : []
  } catch {
    return []
  }
}

export function saveBookmarks(itemId: string, bookmarks: Bookmark[]): void {
  if (!itemId) return
  try {
    localStorage.setItem(key(itemId), JSON.stringify(bookmarks))
  } catch {
    /* quota - drop silently */
  }
}

function genId(): string {
  return Math.random().toString(36).slice(2, 10)
}

export function addBookmark(itemId: string, positionSec: number, note?: string): Bookmark {
  const list = loadBookmarks(itemId)
  const bm: Bookmark = {
    id: genId(),
    positionSec,
    note,
    createdAt: Date.now(),
  }
  list.push(bm)
  list.sort((a, b) => a.positionSec - b.positionSec)
  saveBookmarks(itemId, list)
  return bm
}

export function removeBookmark(itemId: string, bookmarkId: string): void {
  const list = loadBookmarks(itemId).filter(b => b.id !== bookmarkId)
  saveBookmarks(itemId, list)
}

export function updateBookmark(
  itemId: string,
  bookmarkId: string,
  patch: Partial<Pick<Bookmark, 'note' | 'positionSec'>>,
): void {
  const list = loadBookmarks(itemId).map(b =>
    b.id === bookmarkId ? { ...b, ...patch } : b,
  )
  list.sort((a, b) => a.positionSec - b.positionSec)
  saveBookmarks(itemId, list)
}
