import { useState, useEffect } from 'react'

/**
 * Upload a template kit ZIP file
 * @param {Object} options - Upload options
 * @param {File} options.file - The ZIP file to upload
 * @returns {Object} - { loading, data, error }
 */
const uploadTemplateKitZipFile = ({ file }) => {
  const [loading, setLoading] = useState(true)
  const [data, setData] = useState(null)
  const [error, setError] = useState(null)

  useEffect(() => {
    if (!file) {
      setLoading(false)
      return
    }

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

        // Create FormData to send the file
        const formData = new FormData()
        formData.append('file', file)

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

        const result = await response.json()

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

        setData(result)
        setLoading(false)
      } catch (err) {
        setError(err.message || 'Upload failed')
        setLoading(false)
      }
    }

    uploadFile()
  }, [file])

  return { loading, data, error }
}

export default uploadTemplateKitZipFile




