// retoor <retoor@molodetz.nl>

import { Http } from "./Http.js";
import { Toast } from "./Toast.js";

class CustomizationToggle {
    constructor() {
        this.card = document.querySelector("[data-customization]");
        if (!this.card) return;
        this.card
            .querySelectorAll("[data-customization-form]")
            .forEach((form) => this.bind(form));
    }

    bind(form) {
        form.addEventListener("submit", async (event) => {
            event.preventDefault();
            const button = form.querySelector("[data-customization-toggle]");
            const field = form.querySelector("input[name='value']");
            const category = button.dataset.customizationToggle;
            button.disabled = true;
            try {
                const result = await Http.send(form.action, { value: field.value });
                this.render(button, field, category, result);
            } catch (error) {
                console.error("customization toggle failed", error);
                Toast.flash(button, "Error", 1500);
            } finally {
                button.disabled = false;
                button.classList.remove("is-loading");
            }
        });
    }

    render(button, field, category, result) {
        const column =
            category === "global" ? "cust_disable_global" : "cust_disable_pagetype";
        const disabled = Boolean(result.data && result.data[column]);
        field.value = disabled ? "1" : "0";
        button.textContent = disabled ? "Enable" : "Disable";
        button.classList.toggle("btn-primary", disabled);
    }
}

window.CustomizationToggle = CustomizationToggle;
export { CustomizationToggle };
