import { useState, useEffect, useCallback } from 'react'

/**
 * Fetch installed template kits
 * @returns {Object} - { loading, data, error, refetch }
 */
const fetchInstalledTemplateKits = () => {
  const [loading, setLoading] = useState(true)
  const [data, setData] = useState(null)
  const [error, setError] = useState(null)
  const [refetchTrigger, setRefetchTrigger] = useState(0)

  const fetchKits = useCallback(async () => {
    try {
      setLoading(true)
      setError(null)

      // WordPress REST API endpoint
      const response = await fetch(
        `/wp-json/${window.envatoElements?.api_namespace || 'envato-elements/v2'}/fetchInstalledTemplateKits`,
        {
          method: 'POST',
          credentials: 'same-origin',
          headers: {
            'Content-Type': 'application/json',
            'X-WP-Nonce': window.envatoElements?.nonce || ''
          }
        }
      )

      const result = await response.json()

      if (!response.ok || result.code === 'error') {
        throw new Error(result.message || 'Failed to fetch installed template kits')
      }

      setData(result)
      setLoading(false)
    } catch (err) {
      setError(err.message || 'Fetch failed')
      setLoading(false)
    }
  }, [])

  useEffect(() => {
    fetchKits()
  }, [fetchKits, refetchTrigger])

  const refetch = useCallback(() => {
    setRefetchTrigger(prev => prev + 1)
  }, [])

  return { loading, data, error, refetch }
}

export default fetchInstalledTemplateKits




