import { defineStore } from 'pinia'
import { ref } from 'vue'
import { useApi } from '../composables/useApi.js'
import { useAsyncAction } from '../composables/useAsyncAction.js'

// IR reader.js "viewport-center-in-third" rule, pure for unit tests.
// metrics: [{page_number, top, height}] in page order.
export function currentPageFromScroll(metrics, scrollTop, viewportH) {
  if (!metrics.length) return 1
  const target = scrollTop + viewportH / 3
  let cur = metrics[0].page_number
  for (const m of metrics) {
    if (target >= m.top) cur = m.page_number
  }
  return cur
}

export function progressPct(scrollTop, scrollHeight, clientHeight) {
  const denom = scrollHeight - clientHeight
  if (denom <= 0) return 0
  const pct = (scrollTop / denom) * 100
  return Math.min(100, Math.max(0, pct))
}

export function clampPage(n, total) {
  if (!total || total < 1) return 1
  if (!Number.isFinite(n) || n < 1) return 1
  if (n > total) return total
  return Math.floor(n)
}

export const useSeriesReaderStore = defineStore('seriesReader', () => {
  const api = useApi()

  const series = ref(null)
  const pages = ref([])
  const { loading, error, run } = useAsyncAction({ errorAs: 'message' })

  async function load(tagId) {
    series.value = null  // cleared upfront so they stay reset on error
    pages.value = []
    await run(async () => {
      const body = await api.get(`/api/series/${tagId}/pages`)
      series.value = body.series
      // FC-6.x: page_number is already the series-global reading order, so it
      // anchors scroll/jump directly (seq = page_number). Chapters are cosmetic
      // dividers anchored to a page; mark the page each divider begins on so the
      // reader can render a chapter heading there.
      const dividers = body.dividers || []
      const anchorIds = new Set(dividers.map(d => d.anchor_image_id))
      const labelByAnchor = {}
      for (const d of dividers) {
        labelByAnchor[d.anchor_image_id] =
          d.title || (d.stated_part != null ? `Part ${d.stated_part}` : 'Chapter')
      }
      pages.value = (body.pages || []).map((p) => ({
        ...p,
        seq: p.page_number,
        isChapterStart: anchorIds.has(p.image_id),
        chapterLabel: labelByAnchor[p.image_id] || 'Chapter'
      }))
    })
  }

  return { series, pages, loading, error, load }
})
