import type { Song } from './playlist'

interface PersistedState {
  playlist: Song[]
}

const KEY = 'karaoke:v1'

function isBrowser(): boolean {
  return typeof window !== 'undefined' && typeof window.localStorage !== 'undefined'
}

export function loadState(): PersistedState {
  if (!isBrowser()) return { playlist: [] }
  try {
    const raw = window.localStorage.getItem(KEY)
    if (!raw) return { playlist: [] }
    const parsed = JSON.parse(raw) as Partial<PersistedState>
    return { playlist: parsed.playlist ?? [] }
  } catch {
    return { playlist: [] }
  }
}

export function saveState(state: PersistedState): void {
  if (!isBrowser()) return
  try {
    window.localStorage.setItem(KEY, JSON.stringify(state))
  } catch {
    // ignore
  }
}
