import { ref, reactive, watch, onMounted } from 'vue'
import { useRoute } from 'vue-router'

// Loads a view's data + raw reviews, manages expanded-rank set + per-rank pagination.
// Usage: const { data, reviews, loading, expanded, toggle, load } = useSupporting('strengths-weaknesses')
export function useSupporting(viewName) {
  const route = useRoute()
  const data = ref(null)
  const reviews = ref(null)
  const loading = ref(false)
  const expanded = reactive(new Set())

  function hasSupport(item) {
    return Array.isArray(item?.supportingReviewIndices) && item.supportingReviewIndices.length > 0
  }
  function toggle(item) {
    if (!hasSupport(item)) return
    if (expanded.has(item.rank)) expanded.delete(item.rank)
    else expanded.add(item.rank)
  }

  async function load(sku) {
    if (!sku) return
    loading.value = true
    expanded.clear()
    reviews.value = null
    try {
      const [dRes, rRes] = await Promise.all([
        fetch(`/api/intelligence/${sku}/${viewName}`),
        fetch(`/api/reviews/${sku}`)
      ])
      data.value = dRes.ok ? await dRes.json() : null
      reviews.value = rRes.ok ? await rRes.json() : null
    } finally { loading.value = false }
  }

  onMounted(() => load(route.params.sku))
  watch(() => route.params.sku, load)

  return { data, reviews, loading, expanded, hasSupport, toggle, load }
}
