import { describe, it, expect, beforeEach } from 'vitest'
import { renderHook, act } from '@testing-library/react'
import { useStarred } from './useStarred'

describe('useStarred', () => {
  beforeEach(() => {
    localStorage.clear()
  })

  it('starts with empty set when no localStorage data', () => {
    const { result } = renderHook(() => useStarred())
    expect(result.current.starredIds.size).toBe(0)
  })

  it('toggleStar adds an item', () => {
    const { result } = renderHook(() => useStarred())
    act(() => { result.current.toggleStar('app-1') })
    expect(result.current.isStarred('app-1')).toBe(true)
    expect(result.current.starredIds.size).toBe(1)
  })

  it('toggleStar removes a starred item', () => {
    const { result } = renderHook(() => useStarred())
    act(() => { result.current.toggleStar('app-1') })
    act(() => { result.current.toggleStar('app-1') })
    expect(result.current.isStarred('app-1')).toBe(false)
  })

  it('persists to localStorage', () => {
    const { result } = renderHook(() => useStarred())
    act(() => { result.current.toggleStar('route-1') })
    const stored = JSON.parse(localStorage.getItem('cameleer:starred') ?? '[]')
    expect(stored).toContain('route-1')
  })

  it('reads from localStorage on mount', () => {
    localStorage.setItem('cameleer:starred', JSON.stringify(['agent-1', 'route-2']))
    const { result } = renderHook(() => useStarred())
    expect(result.current.isStarred('agent-1')).toBe(true)
    expect(result.current.isStarred('route-2')).toBe(true)
  })

  it('handles corrupted localStorage gracefully', () => {
    localStorage.setItem('cameleer:starred', 'not-valid-json')
    const { result } = renderHook(() => useStarred())
    expect(result.current.starredIds.size).toBe(0)
  })
})
