<?php

namespace GriffinForms\Admin\Js\Local;

class Forms extends \GriffinForms\Admin\Js\Local\Lists
{
    protected function listJs()
    {
        return $this->copyShortcodeJs() . $this->exportFormJs() . $this->openCreateFormModalJs() . $this->createWithAiDraftJs() . $this->openAiModalTabJs();
    }

    protected function copyShortcodeJs()
    {
        $js = '
        // Scrolling animation for shortcode on hover
        $(".gf-shortcode-group").on("mouseenter", function() {
            $(this).find(".gf-shortcode-display").addClass("scrolling");
        }).on("mouseleave", function() {
            $(this).find(".gf-shortcode-display").removeClass("scrolling");
        });

        $(".gf-shortcode-copy-btn").on("click", function(e) {
            e.preventDefault();
            const shortcode = $(this).attr("data-shortcode");
            const btn = $(this);
            const originalTitle = btn.attr("title");
            const iconElement = btn.find("i, span");

            function showSuccess() {
                iconElement.text("check");
                btn.attr("title", "' . esc_js($this->lang->getText('copiedLabel')) . '");
                setTimeout(function() {
                    iconElement.text("content_copy");
                    btn.attr("title", originalTitle);
                }, 2000);
            }

            function performCopy() {
                const textarea = document.createElement("textarea");
                textarea.value = shortcode;
                textarea.style.position = "fixed";
                textarea.style.opacity = "0";
                document.body.appendChild(textarea);
                textarea.select();
                try {
                    document.execCommand("copy");
                    showSuccess();
                } catch (err) {
                    console.error("Copy failed:", err);
                }
                document.body.removeChild(textarea);
            }

            if (navigator.clipboard && navigator.clipboard.writeText) {
                navigator.clipboard.writeText(shortcode).then(showSuccess).catch(performCopy);
            } else {
                performCopy();
            }
        });' . PHP_EOL;
        return $js;
    }

    protected function exportFormJs()
    {
        $js = '
        $(".griffinforms-formslist-export-btn").click(function(){
            let formId = $(this).attr("data-gf-formid");
            const data = {
                "action": "exportForm",
                "form_id": formId,
                "nonce": "' . esc_js(wp_create_nonce('export_form')) . '"
            };

            $.post(ajaxurl, data, function(response) {

                if (response.success === false) {
                    alert(response.data);
                    return;
                }

                const blob = new Blob([response], { type: "application/json" });
                const link = document.createElement("a");
                link.href = window.URL.createObjectURL(blob);
                link.download = `form_${formId}_export.json`;
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
            });
        });' . PHP_EOL;
        return $js;
    }

    protected function openCreateFormModalJs()
    {
        return '
        (function() {
            const urlParams = new URLSearchParams(window.location.search);
            if (urlParams.get("gf_onboarding_open_create") !== "1") {
                return;
            }

            const createFormModalElement = document.getElementById("griffinforms-createform-modal");
            if (!createFormModalElement || typeof bootstrap === "undefined" || !bootstrap.Modal) {
                return;
            }

            const createFormModal = bootstrap.Modal.getOrCreateInstance(createFormModalElement);
            createFormModal.show();
            urlParams.delete("gf_onboarding_open_create");
            const cleanQuery = urlParams.toString();
            const cleanUrl = window.location.pathname + (cleanQuery ? "?" + cleanQuery : "");
            window.history.replaceState({}, document.title, cleanUrl);
        })();
        ' . PHP_EOL;
    }

    protected function createWithAiDraftJs()
    {
        return '
        let gfCreateAiDraftInFlight = false;

        $(document).on("click", ".gf-create-ai-draft-btn", function(e) {
            e.preventDefault();

            if (gfCreateAiDraftInFlight) {
                return;
            }

            const btn = $(this);
            const nonce = btn.attr("data-gf-ai-nonce") || "";
            if (!nonce) {
                return;
            }

            gfCreateAiDraftInFlight = true;
            btn.prop("disabled", true).addClass("gf-loading");

            $.post(ajaxurl, {
                action: "initialize_ai_draft",
                prompt: "",
                nonce: nonce
            }, function(response) {
                if (response && response.success && response.data && response.data.redirect_url) {
                    window.location.href = response.data.redirect_url;
                    return;
                }

                const message = response && response.data
                    ? (typeof response.data === "string" ? response.data : (response.data.message || "Failed to start AI draft."))
                    : "Failed to start AI draft.";
                alert(message);
            }).fail(function() {
                alert("Failed to start AI draft.");
            }).always(function() {
                gfCreateAiDraftInFlight = false;
                btn.prop("disabled", false).removeClass("gf-loading");
            });
        });
        ' . PHP_EOL;
    }

    protected function openAiModalTabJs()
    {
        return '
        $(document).on("click", ".gf-create-ai-modal-btn", function() {
            var tabId = $(this).attr("data-gf-open-tab");
            if (!tabId) return;
            var $modal = $($(this).attr("data-bs-target"));
            $modal.one("shown.bs.modal", function() {
                var $tab = $("#" + tabId);
                if ($tab.length) {
                    $tab.tab("show");
                    $modal.find("#griffinforms-butler-initial-prompt").trigger("focus");
                }
            });
        });
        ' . PHP_EOL;
    }
}
