import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import { setActivePinia, createPinia } from 'pinia'
import {
  useSeriesReaderStore,
  currentPageFromScroll,
  progressPct,
  clampPage
} from '../src/stores/seriesReader.js'

function stubFetch(handler) {
  globalThis.fetch = vi.fn(async (url, init) => {
    const { status, body } = handler(url, init)
    return {
      ok: status >= 200 && status < 300,
      status, statusText: String(status),
      text: async () => (body == null ? '' : JSON.stringify(body))
    }
  })
}

const M = [
  { page_number: 1, top: 0, height: 100 },
  { page_number: 2, top: 100, height: 100 },
  { page_number: 3, top: 200, height: 100 }
]

describe('seriesReader pure helpers', () => {
  it('currentPageFromScroll: top of doc → page 1', () => {
    expect(currentPageFromScroll(M, 0, 90)).toBe(1)   // target 30
  })
  it('currentPageFromScroll: boundary crosses into page 2', () => {
    expect(currentPageFromScroll(M, 80, 90)).toBe(2)  // target 110
  })
  it('currentPageFromScroll: scrolled past last → last page', () => {
    expect(currentPageFromScroll(M, 5000, 300)).toBe(3)
  })
  it('currentPageFromScroll: empty metrics → 1', () => {
    expect(currentPageFromScroll([], 0, 90)).toBe(1)
  })
  it('progressPct: 0 at top, ~50 mid, clamped 100, zero-guard', () => {
    expect(progressPct(0, 1000, 500)).toBe(0)
    expect(progressPct(250, 1000, 500)).toBe(50)
    expect(progressPct(9999, 1000, 500)).toBe(100)
    expect(progressPct(0, 100, 100)).toBe(0)   // denom 0 → 0
  })
  it('clampPage: below→1, above→total, valid passthrough, NaN→1', () => {
    expect(clampPage(0, 5)).toBe(1)
    expect(clampPage(99, 5)).toBe(5)
    expect(clampPage(3, 5)).toBe(3)
    expect(clampPage(NaN, 5)).toBe(1)
    expect(clampPage(2, 0)).toBe(1)
  })
})

describe('seriesReader store', () => {
  beforeEach(() => setActivePinia(createPinia()))
  afterEach(() => vi.restoreAllMocks())

  it('load() stores series + pages', async () => {
    const s = useSeriesReaderStore()
    stubFetch(() => ({
      status: 200,
      body: {
        series: { id: 7, name: 'V' },
        pages: [{ image_id: 1, page_number: 1, thumbnail_url: 't', image_url: 'i' }]
      }
    }))
    await s.load(7)
    expect(s.series).toEqual({ id: 7, name: 'V' })
    expect(s.pages[0].image_url).toBe('i')
    expect(s.error).toBe(null)
  })

  it('load() on 404 sets error, no throw', async () => {
    const s = useSeriesReaderStore()
    stubFetch(() => ({ status: 404, body: { error: 'not a series' } }))
    await s.load(9)
    expect(s.error).toBe('not a series')
    expect(s.pages).toEqual([])
  })
})
