import { documentationSections } from '~/data/documentation-content'
import type { DocAccessLevel, DocSection } from '~/types/documentation'

const LEVEL_HIERARCHY: Record<DocAccessLevel, number> = {
  employee: 0,
  site_manager: 1,
  admin: 2,
}

function getUserLevel(roles: string[]): number {
  if (roles.includes('ROLE_ADMIN') || roles.includes('ROLE_SUPER_ADMIN')) return 2
  if (roles.includes('ROLE_USER')) return 1
  return 0
}

export function useDocumentation() {
  const auth = useAuthStore()
  const userLevel = computed(() => getUserLevel(auth.user?.roles ?? []))

  const visibleSections = computed<DocSection[]>(() => {
    return documentationSections
      .filter(s => LEVEL_HIERARCHY[s.requiredLevel] <= userLevel.value)
      .map(s => ({
        ...s,
        articles: s.articles.filter(a => LEVEL_HIERARCHY[a.requiredLevel] <= userLevel.value),
      }))
      .filter(s => s.articles.length > 0)
  })

  const activeArticleId = ref<string | null>(null)

  const scrollToArticle = (articleId: string) => {
    activeArticleId.value = articleId
    const el = document.getElementById(`doc-${articleId}`)
    el?.scrollIntoView({ behavior: 'smooth', block: 'start' })
  }

  return { visibleSections, activeArticleId, scrollToArticle }
}
