<?php

namespace GriffinForms\Admin\Js\Local;

class FormThemes extends \GriffinForms\Admin\Js\Local\Lists
{
    protected function listJs()
    {
        return $this->exportThemeJs();
    }

    protected function exportThemeJs()
    {
        $js = '
        $(".griffinforms-formtheme-download-btn").click(function(){
            let themeId = $(this).data("gf-id");
            const data = {
                "action": "exportTheme",
                "item_id": themeId,
                "nonce": "' . esc_js(wp_create_nonce('export_theme')) . '"
            };

            $.post(ajaxurl, data, function(response) {
                // Parse response if it\'s a string
                if (typeof response === "string") {
                    try {
                        response = JSON.parse(response);
                    } catch (e) {
                        console.error("Failed to parse AJAX response", e);
                        alert("Error: Invalid response from server");
                        return;
                    }
                }

                if (response.success === false) {
                    alert(response.msg || response.data || "Unknown error occurred");
                    return;
                }

                // Get the actual export data
                const themeData = response.data;

                if (!themeData) {
                    alert("Error: No theme data received");
                    return;
                }

                // Create blob with proper theme name
                const blob = new Blob([JSON.stringify(themeData, null, 2)], { type: "application/json" });
                const link = document.createElement("a");
                link.href = window.URL.createObjectURL(blob);
                link.download = response.filename ? response.filename : `theme_${themeId}_export.json`;
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);

                // Clean up the URL object
                setTimeout(function() {
                    window.URL.revokeObjectURL(link.href);
                }, 100);
            }, "json");
        });' . PHP_EOL;
        return $js;
    }
}