import { ref, onMounted } from 'vue'
import { wordpressService, type WpPost } from '@/services/wordpress'

const SLIDER_CATEGORY_ID = 3

export interface Slide {
  id: number
  title: string
  description: string
  image: string
  post: WpPost
}

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

export function useHeaderSlider() {
  const slides = ref<Slide[]>([])
  const loading = ref(false)
  const error = ref<string | null>(null)

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

    try {
      const posts = await wordpressService.getPostsByCategory(SLIDER_CATEGORY_ID, {
        per_page: 5,
        orderby: 'date',
        order: 'asc'
      })

      slides.value = posts.map(post => {
        const title = post.title?.rendered ? decodeHtmlEntities(post.title.rendered) : 'Без названия'

        let description = post.excerpt?.rendered || ''
        description = description.replace(/<[^>]*>/g, '').trim()
        description = decodeHtmlEntities(description)

        if (!description && post.content?.rendered) {
          description = post.content.rendered.replace(/<[^>]*>/g, '').trim().substring(0, 150) + '...'
          description = decodeHtmlEntities(description)
        }

        let image = ''
        if (post._embedded?.['wp:featuredmedia']?.[0]?.source_url) {
          image = post._embedded['wp:featuredmedia'][0].source_url
        }

        return {
          id: post.id,
          title,
          description,
          image,
          post
        }
      })

    } catch (e: any) {
      error.value = e.message || 'Error fetching slider posts'
      console.error('Failed to load slider:', e)

    } finally {
      loading.value = false
    }
  }

  onMounted(() => {
    fetchSliderPosts()
  })

  return {
    slides,
    loading,
    error,
    refreshSlides: fetchSliderPosts
  }
}
