<?php

namespace GriffinForms\Admin\App\Html\Modals\FormOptions;

trait Scripts
{
    protected function renderScripts()
    {
        $form_id   = (int) $this->utility->getFormId();
        $action_id = 'griffinforms-builder-modal-formoptions-action-btn';
        $nonce     = wp_create_nonce('wp_rest');

        echo '
(function($) {

    var $modal = $("#griffinforms-builder-modal-formoptions");

    // ── Tab switching + glide indicator ─────────────────────────────────────

    function gfOptMoveIndicator($btn) {
        var $nav = $btn.closest(".gf-formoptions-sidenav");
        var $ind = $nav.find(".gf-formoptions-tab-indicator");
        if (!$ind.length) { return; }
        $ind.css({ top: $btn[0].offsetTop + "px", height: $btn[0].offsetHeight + "px" });
    }

    function gfOptInitIndicator() {
        var $active = $modal.find(".gf-formoptions-tab-btn--active").first();
        if ($active.length) {
            var $ind = $active.closest(".gf-formoptions-sidenav").find(".gf-formoptions-tab-indicator");
            $ind.css({ transition: "none", top: $active[0].offsetTop + "px", height: $active[0].offsetHeight + "px" });
            setTimeout(function() { $ind.css("transition", ""); }, 0);
        }
    }

    function gfOptActivateTab($btn) {
        var target  = $btn.attr("data-bs-target");

        $modal.find(".gf-formoptions-tab-btn").removeClass("gf-formoptions-tab-btn--active")
            .attr("aria-selected", "false");
        $btn.addClass("gf-formoptions-tab-btn--active").attr("aria-selected", "true");

        gfOptMoveIndicator($btn);

        $modal.find(".gf-formoptions-panel").removeClass("gf-formoptions-panel--active");
        $modal.find(target).addClass("gf-formoptions-panel--active");
    }

    function gfOptEnsureDefaultTab() {
        var $activeBtn = $modal.find(".gf-formoptions-tab-btn--active").first();
        var $activePanel = $modal.find(".gf-formoptions-panel--active").first();

        if (!$activeBtn.length || !$activePanel.length) {
            $activeBtn = $modal.find(".gf-formoptions-tab-btn").first();
            if ($activeBtn.length) {
                gfOptActivateTab($activeBtn);
            }
        } else {
            gfOptMoveIndicator($activeBtn);
        }
    }

    $modal.on("click", ".gf-formoptions-tab-btn", function() {
        gfOptActivateTab($(this));
    });

    // ── Getters ──────────────────────────────────────────────────────────────

    function gfOptGet(selector) {
        var el = $(selector);
        if (!el.length) { return null; }
        var type = el.attr("type");
        if (type === "checkbox") { return el.is(":checked") ? 1 : 0; }
        return el.val();
    }

    function gfOptGetName()              { return gfOptGet("[name=\'name\']");              }
    function gfOptGetHeading()           { return gfOptGet("[name=\'heading\']");           }
    function gfOptGetDescription()       { return gfOptGet("[name=\'description\']");       }
    function gfOptGetAutofill()          { return gfOptGet("[name=\'autofill\']");          }
    function gfOptGetSaveEntries()       { return gfOptGet("[name=\'save_entries\']");      }
    function gfOptGetComplianceMode()    { return gfOptGet("[name=\'compliance_mode\']");   }
    function gfOptGetComplianceProfile() { return gfOptGet("[name=\'compliance_profile\']"); }

    function gfOptGetUserAction() {
        var type = gfOptGet("[name=\'action_type\']:checked");
        if (type === null) { return null; }
        return {
            type:    type,
            message: gfOptGet("[name=\'success_message\']") || "",
            url:     gfOptGet("[name=\'redirection_url\']") || ""
        };
    }

    function gfOptGetProgressBar() {
        var toggle = gfOptGet("[name=\'progress_bar_toggle\']");
        if (toggle === null) { return null; }
        return {
            toggle:             toggle ? 1 : 0,
            style:              gfOptGet("[name=\'progress_bar_style\']") || "stepper",
            show_page_headings: gfOptGet("[name=\'progress_bar_show_page_headings\']") ? 1 : 0
        };
    }

    function gfOptGetLimitEntries() {
        var toggle = gfOptGet("[name=\'toggle_limit_entries\']");
        if (toggle === null) { return null; }
        return {
            toggle:  toggle ? 1 : 0,
            limit:   parseInt(gfOptGet("[name=\'limit_entries_count\']") || "0", 10),
            message: gfOptGet("[name=\'limit_entries_message\']") || ""
        };
    }

    function gfOptGetAvailabilityWindow() {
        var toggle = gfOptGet("[name=\'toggle_availability_window\']");
        if (toggle === null) { return null; }
        return {
            toggle:       toggle ? 1 : 0,
            start_date:   gfOptGet("[name=\'availability_window_start_date\']") || "",
            start_time:   gfOptGet("[name=\'availability_window_start_time\']") || "",
            end_date:     gfOptGet("[name=\'availability_window_end_date\']") || "",
            end_time:     gfOptGet("[name=\'availability_window_end_time\']") || "",
            pre_message:  gfOptGet("[name=\'availability_window_pre_message\']") || "",
            post_message: gfOptGet("[name=\'availability_window_post_message\']") || ""
        };
    }

    function gfOptGetAccessLevel() {
        var $access = $("[name=\'toggle_public_access\']:checked");
        if (!$access.length) { return null; }
        var access = $access.val();
        var $rolesEl = $("[name=\'select_user_roles\']");
        var roles = $rolesEl.length ? ($rolesEl.val() || []) : [];
        return {
            access:      access,
            role_access: gfOptGet("[name=\'toggle_role_access\']") ? 1 : 0,
            roles:       roles
        };
    }

    function gfOptGetSubmissionEdit() {
        var toggle = gfOptGet("[name=\'toggle_submission_edit\']");
        if (toggle === null) { return null; }
        var $emailFields = $("[name=\'submission_edit_email_fields\']");
        var emailFields = $emailFields.length ? ($emailFields.val() || []) : [];
        var $roles = $("[name=\'submission_edit_roles\']");
        var roles = $roles.length ? ($roles.val() || []) : [];
        var users = [];
        var hiddenUsers = $("#griffinforms-submissioneditusers-hidden").val() || "";
        if (hiddenUsers) {
            hiddenUsers.split(",").forEach(function(id) {
                var uid = parseInt(id, 10);
                if (uid > 0) { users.push(uid); }
            });
        }
        return {
            toggle:              toggle ? 1 : 0,
            original_submitters: gfOptGet("[name=\'submission_edit_original_submitters\']") ? 1 : 0,
            email_owners:        gfOptGet("[name=\'submission_edit_email_owners\']") ? 1 : 0,
            role_access:         gfOptGet("[name=\'submission_edit_role_access\']") ? 1 : 0,
            user_access:         gfOptGet("[name=\'submission_edit_user_access\']") ? 1 : 0,
            email_fields:        emailFields,
            roles:               roles,
            users:               users,
            max_edits:           parseInt(gfOptGet("[name=\'submission_edit_max_edits\']") || "0", 10),
            time: {
                mode:           gfOptGet("[name=\'submission_edit_time_mode\']") || "none",
                start_date:     gfOptGet("[name=\'submission_edit_time_window_start_date\']") || "",
                start_time:     gfOptGet("[name=\'submission_edit_time_window_start_time\']") || "",
                end_date:       gfOptGet("[name=\'submission_edit_time_window_end_date\']") || "",
                end_time:       gfOptGet("[name=\'submission_edit_time_window_end_time\']") || "",
                duration_days:  parseInt(gfOptGet("[name=\'submission_edit_time_duration_days\']") || "0", 10),
                duration_hours: parseInt(gfOptGet("[name=\'submission_edit_time_duration_hours\']") || "0", 10),
                pre_message:    gfOptGet("[name=\'submission_edit_time_window_pre_message\']") || "",
                post_message:   gfOptGet("[name=\'submission_edit_time_window_post_message\']") || ""
            }
        };
    }

    function gfOptGetComplianceFlags() {
        var mode = gfOptGet("[name=\'compliance_flag_mode\']");
        if (mode === null) { return null; }
        return {
            mode:             mode || "inherit",
            store_ip:         gfOptGet("[name=\'compliance_flag_store_ip\']") ? 1 : 0,
            store_user_agent: gfOptGet("[name=\'compliance_flag_store_user_agent\']") ? 1 : 0,
            retention_days:   parseInt(gfOptGet("[name=\'compliance_flag_retention_days\']") || "0", 10)
        };
    }

    function gfGetFormOptionsData() {
        var data = {};
        var v;

        v = gfOptGetName();              if (v !== null) { data.name               = v; }
        v = gfOptGetHeading();           if (v !== null) { data.heading             = v; }
        v = gfOptGetDescription();       if (v !== null) { data.description         = v; }
        v = gfOptGetAutofill();          if (v !== null) { data.autofill            = v; }
        v = gfOptGetSaveEntries();       if (v !== null) { data.save_entries        = v; }
        v = gfOptGetUserAction();        if (v !== null) { data.user_action         = v; }
        v = gfOptGetProgressBar();       if (v !== null) { data.progress_bar        = v; }
        v = gfOptGetAvailabilityWindow();if (v !== null) { data.availability_window = v; }
        v = gfOptGetLimitEntries();      if (v !== null) { data.limit_entries       = v; }
        v = gfOptGetAccessLevel();       if (v !== null) { data.access_level        = v; }
        v = gfOptGetSubmissionEdit();    if (v !== null) { data.submission_edit     = v; }
        v = gfOptGetComplianceMode();    if (v !== null) { data.compliance_mode     = v; }
        v = gfOptGetComplianceProfile(); if (v !== null) { data.compliance_profile  = v; }
        v = gfOptGetComplianceFlags();   if (v !== null) { data.compliance_flags    = v; }

        return data;
    }

    // ── Sub-option reveal ─────────────────────────────────────────────────────

    function gfOptShowHide(selector, show) {
        if (show) {
            $(selector).show(150);
        } else {
            $(selector).hide(150);
        }
    }

    function gfOptSyncProgressBar() {
        var on = $("#griffinforms-progressbartoggle-togglecheckbox").is(":checked");
        gfOptShowHide("#griffinforms-progressbarstyle-wrap",           on);
        gfOptShowHide("#griffinforms-progressbarshowpageheadings-wrap", on);
    }

    function gfOptSyncLimitEntries() {
        var on = $("#griffinforms-togglelimitentries-togglecheckbox").is(":checked");
        gfOptShowHide("#griffinforms-limitentriescount-wrap", on);
        gfOptShowHide("#griffinforms-limitentriesmessage-wrap", on);
    }

    function gfOptSyncAvailabilityWindow() {
        var on = $("#griffinforms-toggleavailabilitywindow-togglecheckbox").is(":checked");
        gfOptShowHide("#griffinforms-availabilitywindowstart-wrap", on);
        gfOptShowHide("#griffinforms-availabilitywindowend-wrap", on);
        gfOptShowHide("#griffinforms-availabilitywindowpremessage-wrap", on);
        gfOptShowHide("#griffinforms-availabilitywindowpostmessage-wrap", on);
    }

    function gfOptSyncUserAction() {
        var type = $("[name=\'action_type\']:checked").val();
        gfOptShowHide("#griffinforms-successmessage-wrap",  type === "show_success_message");
        gfOptShowHide("#griffinforms-redirectionurl-wrap",  type === "redirect_user");
    }

    function gfOptSyncPublicAccess() {
        var val = $("[name=\'toggle_public_access\']:checked").val();
        var restricted = (val === "registered_access");
        gfOptShowHide("#griffinforms-toggleroleaccess-wrap", restricted);
        if (!restricted) {
            $("#griffinforms-toggleroleaccess-togglecheckbox").prop("checked", false);
            gfOptShowHide("#griffinforms-selectuserroles-wrap", false);
        }
    }

    function gfOptSyncRoleAccess() {
        var on = $("#griffinforms-toggleroleaccess-togglecheckbox").is(":checked");
        gfOptShowHide("#griffinforms-selectuserroles-wrap", on);
    }

    function gfOptSyncComplianceFlags() {
        var mode = $("#griffinforms-complianceflagmode-selectfield").val() || "inherit";
        var custom = (mode === "custom");
        gfOptShowHide("#griffinforms-compliance-custom-options-wrap", custom);
        if (custom) {
            var isOn = $("[name=\'compliance_mode\']").is(":checked");
            gfOptShowHide("#griffinforms-complianceprofile-wrap",      isOn);
            gfOptShowHide("#griffinforms-complianceflags-custom-wrap", isOn);
        }
    }

    function gfOptSyncComplianceMode() {
        gfOptSyncComplianceFlags();
    }

    function gfOptInitSuboptions() {
        gfOptSyncProgressBar();
        gfOptSyncLimitEntries();
        gfOptSyncAvailabilityWindow();
        gfOptSyncUserAction();
        gfOptSyncPublicAccess();
        gfOptSyncRoleAccess();
        gfOptSyncComplianceFlags();
    }

    $modal.on("change", "#griffinforms-progressbartoggle-togglecheckbox",        gfOptSyncProgressBar);
    $modal.on("change", "#griffinforms-togglelimitentries-togglecheckbox",       gfOptSyncLimitEntries);
    $modal.on("change", "#griffinforms-toggleavailabilitywindow-togglecheckbox", gfOptSyncAvailabilityWindow);
    $modal.on("change", "[name=\'action_type\']",                                gfOptSyncUserAction);
    $modal.on("change", "[name=\'toggle_public_access\']",                       gfOptSyncPublicAccess);
    $modal.on("change", "#griffinforms-toggleroleaccess-togglecheckbox",         gfOptSyncRoleAccess);
    $modal.on("change", "#griffinforms-complianceflagmode-selectfield",          gfOptSyncComplianceFlags);
    $modal.on("change", "[name=\'compliance_mode\']",                             gfOptSyncComplianceMode);

    $modal.on("show.bs.modal", function() {
        var $layout = $modal.find(".gf-formoptions-layout");
        $layout.css("opacity", 0.4);

        $.post(ajaxurl, {
            action:  "gf_get_formoptions_html",
            nonce:   ' . wp_json_encode($nonce) . ',
            form_id: ' . $form_id . '
        }, function(res) {
            if (res && res.success && res.data && res.data.html) {
                $layout.replaceWith(res.data.html);
                gfOptInitSuboptions();
                gfOptEnsureDefaultTab();
                gfOptInitIndicator();
                if (typeof $.fn.datepicker === "function") {
                    $modal.find(".griffinforms-inputdate").datepicker({
                        changeMonth: true,
                        changeYear: true,
                        yearRange: "1900:2100",
                        showButtonPanel: true,
                        prevText: "←",
                        nextText: "→",
                        dateFormat: "mm/dd/yy"
                    });
                }
            }
        }).always(function() {
            $modal.find(".gf-formoptions-layout").css("opacity", "");
        });
    });

    $modal.on("shown.bs.modal", function() {
        gfOptInitSuboptions();
        gfOptEnsureDefaultTab();
        gfOptInitIndicator();
    });

    // Command palette context: activate a specific tab and scroll to an option row.
    document.addEventListener("gf-palette-modal-context", function(e) {
        if (!e.detail || e.detail.modal_id !== "griffinforms-builder-modal-formoptions") { return; }
        var ctx = e.detail.context || {};
        $modal.one("shown.bs.modal", function() {
            if (ctx.tab) {
                var $tabBtn = $("#gf-formoptions-tab-" + ctx.tab);
                if ($tabBtn.length) { $tabBtn.trigger("click"); }
            }
            if (ctx.anchor) {
                setTimeout(function() {
                    var $target = $("#" + ctx.anchor);
                    if ($target.length) {
                        $target[0].scrollIntoView({ behavior: "smooth", block: "center" });
                        $target.addClass("gf-palette-highlight");
                        setTimeout(function() { $target.removeClass("gf-palette-highlight"); }, 1500);
                    }
                }, 80);
            }
        });
    });

    // Run once on page load in case modal is already visible (e.g. dev/debug).
    gfOptInitSuboptions();

    // ── Validation ───────────────────────────────────────────────────────────

    function gfFormOptionsValidate() {
        var errors = [];

        $(".gf-formoptions-field-error").addClass("d-none").text("");
        $(".gf-formoptions-tab-btn").removeClass("gf-tab-has-error");
        $(".gf-formoptions-tab-error-dot").addClass("d-none");

        // General: form name required
        var name = gfOptGetName();
        if (name !== null && $.trim(name) === "") {
            errors.push({ field: "name", tab: "general", msg: ' . wp_json_encode(__('Form name is required.', 'griffinforms-form-builder')) . ' });
        }

        // Behavior: redirect URL required when redirect action is selected
        var uaData = gfOptGetUserAction();
        if (uaData && uaData.type === "redirect_user" && $.trim(uaData.url) === "") {
            errors.push({ field: "user_action", tab: "behavior", msg: ' . wp_json_encode(__('A redirect URL is required.', 'griffinforms-form-builder')) . ' });
        }

        // Availability: limit entries count required and must be positive
        var limitData = gfOptGetLimitEntries();
        if (limitData && limitData.toggle) {
            if (!limitData.limit || limitData.limit < 1) {
                errors.push({ field: "limit_entries", tab: "availability", msg: ' . wp_json_encode(__('Entry limit must be a positive number.', 'griffinforms-form-builder')) . ' });
            }
        }

        // Availability: at least one date required when window is enabled
        var awData = gfOptGetAvailabilityWindow();
        if (awData && awData.toggle) {
            if (!$.trim(awData.start_date) && !$.trim(awData.end_date)) {
                errors.push({ field: "availability_window", tab: "availability", msg: ' . wp_json_encode(__('Please set at least one availability date.', 'griffinforms-form-builder')) . ' });
            }
        }

        // Submission: time window requires at least a start or end date; duration requires days or hours > 0
        var seData = gfOptGetSubmissionEdit();
        if (seData && seData.toggle && seData.time) {
            if (seData.time.mode === "window") {
                if (!$.trim(seData.time.start_date) && !$.trim(seData.time.end_date)) {
                    errors.push({ field: "submission_edit", tab: "submission", msg: ' . wp_json_encode(__('Please set at least one date for the editing time window.', 'griffinforms-form-builder')) . ' });
                }
            } else if (seData.time.mode === "duration") {
                if ((!seData.time.duration_days || seData.time.duration_days < 1) && (!seData.time.duration_hours || seData.time.duration_hours < 1)) {
                    errors.push({ field: "submission_edit", tab: "submission", msg: ' . wp_json_encode(__('Please enter a duration of at least 1 hour or 1 day.', 'griffinforms-form-builder')) . ' });
                }
            }
        }

        errors.forEach(function(e) {
            var errorEl = $("[data-gf-error-for=\'" + e.field + "\']");
            errorEl.text(e.msg).removeClass("d-none");

            var tabBtn = $("#gf-formoptions-tab-" + e.tab);
            tabBtn.addClass("gf-tab-has-error");
            tabBtn.find(".gf-formoptions-tab-error-dot").removeClass("d-none");
        });

        return errors.length === 0;
    }

    // ── Spinner helpers (scoped to this modal to avoid collision with other modals) ──

    function gfOptSpinner(show) {
        var $spinner = $("#griffinforms-builder-modal-formoptions").find(".griffinforms-modal-spinner");
        if (show) { $spinner.removeClass("d-none"); } else { $spinner.addClass("d-none"); }
    }

    // ── Save flow ─────────────────────────────────────────────────────────────

    function gfSaveFormOptions() {
        if (!gfFormOptionsValidate()) { return; }

        var formId = ' . $form_id . ';
        if (!formId) { return; }

        gfOptSpinner(true);

        wp.apiFetch({
            path: "/griffinforms/v1/forms/" + formId + "/options",
            method: "POST",
            headers: { "X-WP-Nonce": ' . wp_json_encode($nonce) . ' },
            data: { item_data: JSON.stringify(gfGetFormOptionsData()) }
        }).then(function(res) {
            gfOptSpinner(false);
            statusbarMsg("success", ' . wp_json_encode(__('Form options saved.', 'griffinforms-form-builder')) . ');
            document.dispatchEvent(new CustomEvent("form-updated", { detail: { type: "name", itemType: "form", value: gfOptGetName() } }));
            setTimeout(function() {
                var modalEl = document.getElementById("griffinforms-builder-modal-formoptions");
                if (modalEl) {
                    bootstrap.Modal.getOrCreateInstance(modalEl).hide();
                }
                document.dispatchEvent(formLayout);
            }, 1200);
        }).catch(function(err) {
            gfOptSpinner(false);
            var msg = (err && err.message) ? err.message : ' . wp_json_encode(__('Save failed. Please try again.', 'griffinforms-form-builder')) . ';
            statusbarMsg("failure", msg);
        });
    }

    // ── Reset lifetime submission count ───────────────────────────────────────

    $modal.on("click", ".gf-reset-lifetime-count", function() {
        var $btn    = $(this);
        var formId  = $btn.data("gf-form-id");
        var nonce   = $btn.data("gf-nonce");
        var confirm = $btn.data("gf-confirm");
        var success = $btn.data("gf-success");

        if (confirm && !window.confirm(confirm)) { return; }

        $btn.prop("disabled", true);

        $.post(ajaxurl, {
            action: "griffinforms_reset_lifetime_submission_count",
            form_id: formId,
            nonce: nonce
        }, function(response) {
            if (response && response.success) {
                var $badge = $modal.find("[data-gf-lifetime-count]");
                $badge.text("0").attr("data-gf-lifetime-count-value", "0");
                if (success) { statusbarMsg("success", success); }
            } else {
                var msg = (response && response.data && response.data.message) ? response.data.message : ' . wp_json_encode(__('Reset failed. Please try again.', 'griffinforms-form-builder')) . ';
                statusbarMsg("failure", msg);
            }
        }).fail(function() {
            statusbarMsg("failure", ' . wp_json_encode(__('Reset failed. Please try again.', 'griffinforms-form-builder')) . ');
        }).always(function() {
            $btn.prop("disabled", false);
        });
    });

    // ── Wire save button ──────────────────────────────────────────────────────

    $(document).on("click", "#' . esc_js($action_id) . '", function() {
        gfSaveFormOptions();
    });

})(jQuery);
        ';
    }
}
