const HISTORY_KEY = 'myreader-file-history-v1'
const MAX_ITEMS = 80

export function loadFileHistory(): string[] {
  try {
    const raw = localStorage.getItem(HISTORY_KEY)
    if (!raw) return []
    const data = JSON.parse(raw) as { paths?: unknown }
    if (!Array.isArray(data.paths)) return []
    return data.paths.filter((p): p is string => typeof p === 'string' && p.length > 0)
  } catch {
    return []
  }
}

export function saveFileHistory(paths: string[]): void {
  localStorage.setItem(HISTORY_KEY, JSON.stringify({ v: 1, paths }))
}

export function addFileHistory(paths: string[], filePath: string): string[] {
  const next = [filePath, ...paths.filter((p) => p !== filePath)].slice(0, MAX_ITEMS)
  saveFileHistory(next)
  return next
}

export function removeFileHistory(paths: string[], filePath: string): string[] {
  const next = paths.filter((p) => p !== filePath)
  saveFileHistory(next)
  return next
}

export function historyFileName(path: string): string {
  const parts = path.split(/[/\\]/)
  return parts[parts.length - 1] || path
}
