import { useState, useEffect, useCallback } from 'react'

export interface RecentRepo {
  ownerName: string
  name: string
  visitedAt: number
}

const KEY = 'fb_recent_repos'
const MAX = 5
const EVENT = 'fb:recent-repos-changed'

function read(): RecentRepo[] {
  try {
    return JSON.parse(localStorage.getItem(KEY) ?? '[]')
  } catch {
    return []
  }
}

function write(repos: RecentRepo[]) {
  localStorage.setItem(KEY, JSON.stringify(repos))
  window.dispatchEvent(new Event(EVENT))
}

export function useRecentRepos() {
  const [repos, setRepos] = useState<RecentRepo[]>(read)

  useEffect(() => {
    const handler = () => setRepos(read())
    window.addEventListener(EVENT, handler)
    return () => window.removeEventListener(EVENT, handler)
  }, [])

  const track = useCallback((ownerName: string, name: string) => {
    const existing = read().filter(r => !(r.ownerName === ownerName && r.name === name))
    write([{ ownerName, name, visitedAt: Date.now() }, ...existing].slice(0, MAX))
  }, [])

  const remove = useCallback((ownerName: string, name: string) => {
    write(read().filter(r => !(r.ownerName === ownerName && r.name === name)))
  }, [])

  return { repos, track, remove }
}
