import { ref, onMounted, computed } from 'vue'
import { wordpressCategoryService, type WpCategory } from '@/services/wordpress-categories'
import { Zap, Activity, Apple, Dumbbell } from 'lucide-vue-next'

const PARENT_CATEGORY_ID = 4

function decodeHtmlEntities(text: string): string {
  if (!text) return ''
  const textarea = document.createElement('textarea')
  textarea.innerHTML = text
  return textarea.value
}

const iconMap: Record<string, any> = {
  'sportivnye-dobavki': Zap,
  cardio: Activity,
  fitness: Apple,
  bodybuilding: Dumbbell,
}

const tabMap: Record<string, string> = {
  'sportivnye-dobavki': 'supplements',
  cardio: 'cardio',
  fitness: 'fitness',
  bodybuilding: 'bodybuilding',
}

export function useUsefulInfo() {
  const categories = ref<WpCategory[]>([])
  const loading = ref(false)
  const error = ref<string | null>(null)

  const fetchSubCategories = async () => {
    loading.value = true
    error.value = null

    try {
      const subCategories = await wordpressCategoryService.getSubCategories(PARENT_CATEGORY_ID)

      categories.value = subCategories.filter(
        (cat) => cat.description && cat.description.trim() !== '',
      )
    } catch (e: any) {
      error.value = e.message || 'Error fetching categories'
      console.error('Failed to load subcategories:', e)
    } finally {
      loading.value = false
    }
  }

  const usefulInfo = computed(() => {
    return categories.value.map((cat) => ({
      title: decodeHtmlEntities(cat.name),
      description: decodeHtmlEntities(cat.description),
      icon: iconMap[cat.slug] || Zap,
      link: `/training?tab=${tabMap[cat.slug] || cat.slug}`,
    }))
  })

  onMounted(() => {
    fetchSubCategories()
  })

  return {
    usefulInfo,
    categories,
    loading,
    error,
    refresh: fetchSubCategories,
  }
}
