jQuery(document).ready(function ($) {
    function downloadInstagramMedia(type, videoUrl) {
        return new Promise((resolve, reject) => {
            $.ajax({
                url: ajax_object.ajax_url,
                method: 'POST',
                data: {
                    action: `download_instagram_${type}`,
                    post_url: videoUrl
                },
                success: function (html) {
                    $('#modal-container').html(html).modal('show');
                    resolve()
                },
                error: function (response) {
                    const error = new Error(JSON.parse(response.responseText).message)
                    reject(error)
                }
            });
        })
    }

    $('#downloadVideoForm').on('submit', function (e) {
        e.preventDefault()
        const form = new FormData(e.currentTarget)

        const $button = $(this).find('button[type="submit"]')
        const $spinner = $button.find('.spinner-border')
        $button.prop('disabled', true)
        $spinner.show()

        downloadInstagramMedia('video', form.get('link')).catch(error => alert(error.message)).finally(() => {
            $button.prop('disabled', false)
            $spinner.hide()
        })
    })
    $('#downloadAudioForm').on('submit', function (e) {
        e.preventDefault()
        const form = new FormData(e.currentTarget)

        const $button = $(this).find('button[type="submit"]')
        const $spinner = $button.find('.spinner-border')
        $button.prop('disabled', true)
        $spinner.show()

        downloadInstagramMedia('audio', form.get('link')).catch(error => alert(error.message)).finally(() => {
            $button.prop('disabled', false)
            $spinner.hide()
        })
    })
    $('#downloadImageForm').on('submit', function (e) {
        e.preventDefault()
        const form = new FormData(e.currentTarget)

        const $button = $(this).find('button[type="submit"]')
        const $spinner = $button.find('.spinner-border')
        $button.prop('disabled', true)
        $spinner.show()

        downloadInstagramMedia('image', form.get('link')).catch(error => alert(error.message)).finally(() => {
            $button.prop('disabled', false)
            $spinner.hide()
        })
    })


});
