$(document).ready(() => {
    // Définir la dernière position de défilement
    let lastScrollTop = 0;

    window.addEventListener(
        "scroll",
        function () {
            let currentScroll = window.scrollY || document.documentElement.scrollTop;

            // Vérifier si l'utilisateur a défilé vers le bas
            if (currentScroll > lastScrollTop) {
                // Défiler vers le bas, cacher le header
                document.querySelector(".page-header").classList.add("hide");
            } else {
                // Défiler vers le haut, montrer le header
                document.querySelector(".page-header").classList.remove("hide");
            }
            // Mettre à jour la dernière position de défilement
            lastScrollTop = currentScroll <= 0 ? 0 : currentScroll; // Pour les navigateurs mobiles
        },
        false
    );

    const actions = {
        removeUser: {
            attributes: ["user-id"],
            call: (userID) => {
                $.ajax(`./sharing/user/${userID}`, {
                    method: "delete",
                }).done(() => {
                    window.location.reload();
                });
            },
        },
    };

    const initAction = (elt) => {
        const actionName = $(elt).attr("data-action");
        const action = actions[actionName];
        if (!action) {
            return () => {};
        }

        const attributes = action.attributes.map((attrName) => {
            return $(elt).attr("data-" + attrName);
        });
        return () => {
            action.call(...attributes);
        };
    };

    $("output[onforminput]").each((i, elt) => {
        const strFunction = $(elt).attr("onforminput") + ";return value;";
        const inputNames = $(elt).attr("for").split(/\s+/);
        const calcFunction = Function(...inputNames, strFunction);
        const inputs = inputNames.map((eltName) => {
            return $(`[name="${eltName}"]`)[0];
        });
        const refresh = () => {
            $(elt).val(calcFunction(...inputs));
        };

        inputNames.forEach((name) => {
            $(`[name="${name}"]`).on("input", refresh);
        });
        refresh();
    });

    $("[range-slider]").each((i, elt) => {
        const thumb = $(elt).find("[range-slider-thumb]")[0];
        const input = $(elt).find("[range-slider-input]");
        const refresh = () => {
            const max = input.prop("max") || 100;
            const val = input.val();
            $(thumb).css("transform", "translateX(-" + 100 * ((max - val) / max) + "%)");
        };

        input.on("input", refresh);
        refresh();
    });

    $(".sidebar details.active").prop("open", true);

    $("input[password-checker]").keyup(function () {
        const password = $(this).val();
        const userInputs = [];
        $("input[password-checker-user-input]").each((i, elt) => {
            userInputs.push($(elt).val());
        });
        const result = zxcvbn(password, userInputs);
        const score = result.score;

        $("[password-checker-value]").each((i, elt) => {
            if ($(elt).hasClass("password-strength-linear")) {
                const percent = 100 - (score + 1) * 20 + "%";
                $(elt).find(".progress").css("width", percent);
            }
            if ($(elt).hasClass("password-strength-circle")) {
                $(elt).removeClass("password-danger");
                $(elt).removeClass("password-warning");
                $(elt).removeClass("password-success");

                if (score <= 4 / 3) {
                    $(elt).addClass("password-danger");
                } else if (score < 8 / 3) {
                    $(elt).addClass("password-warning");
                } else {
                    $(elt).addClass("password-success");
                }

                $(elt)
                    .find(".circle")
                    .css("transform", `rotate(${(score + 1) * 0.2 * 180}deg)`);
                $(elt)
                    .find(".value span")
                    .text(score + 1);
            }
        });
    });

    $("[popover-confirmation]").each((i, elt) => {
        const content = $($("#" + $(elt).attr("popover-content"))[0].innerHTML);
        const onConfirm = initAction(elt);

        const popover = new bootstrap.Popover(elt, {
            placement: "auto",
            html: true,
            trigger: "focus",
            content: content,
        });
        $(content)
            .find("[popover-confirm]")
            .on("click", () => {
                popover.hide();
                onConfirm();
            });
        $(content)
            .find("[popover-cancel]")
            .on("click", () => {
                popover.hide();
            });
    });

    $("[table-row-appender]").each((i, elt) => {
        const table = $("#" + $(elt).attr("table-row-appender"));
        const template = $("#" + $(elt).attr("data-table-row-template"))[0].innerHTML;
        const tableBody = table.find("tbody");

        let rows = 0;

        const addRow = () => {
            const newRow = $(template.replace(/\$i/g, rows));
            rows++;
            tableBody.append(newRow);
            newRow.find("[table-row-remover]").each((i, elt) => {
                if (rows <= 1) {
                    $(elt).css("visibility", "hidden");
                }
                $(elt).on("click", () => {
                    if (rows > 1) {
                        rows--;
                        newRow.remove();
                    }
                });
            });
        };
        addRow();

        $(elt).on("click", () => {
            addRow();
        });
    });

    const metaPageID = $('meta[property="page_id"]')[0];
    if (metaPageID) {
        const pageID = metaPageID.content;
        setInterval(() => {
            $.ajax(`./stats/page/${pageID}/reading`, {
                method: "post",
            }).done(() => {});
        }, 1000 * 60);
    }

    $("#button-top").click(function () {
        $("html, body, .drawer-content").animate({ scrollTop: 0 }, 800);
    });
    $(document).scroll(function () {
        if ($(this).scrollTop() > 800) {
            if (!$("#button-top").hasClass("appear")) {
                $("#button-top").addClass("appear");
            }
        } else {
            $("#button-top").removeClass("appear");
        }
    });
    $(".drawer-content").scroll(function () {
        if ($(this).scrollTop() > 800) {
            if (!$("#button-top").hasClass("appear")) {
                $("#button-top").addClass("appear");
            }
        } else {
            $("#button-top").removeClass("appear");
        }
    });

    if (typeof SignaturePad === "function") {
        $("[signature-pad]").each((i, elt) => {
            $(elt)
                .find("input")
                .on("keydown", (e) => {
                    $(elt).click();
                    e.preventDefault();
                    e.stopPropagation();
                });
        });
        $("[signature-pad]").on("click", (e) => {
            const target = e.currentTarget;
            const input = $(target).find("input[name]")[0];
            const img = $(target).find("img")[0];
            const clearLabel = $(target).attr("data-clear-label") || "clear";
            const cancelLabel = $(target).attr("data-cancel-label") || "cancel";
            const saveLabel = $(target).attr("data-save-label") || "save";
            const signatureModal = $(`<div class='signature_pad'>
<div class="body">
    <canvas></canvas>
    <div class="action">
        <button type="reset" class="btn btn-light btn-signature-reset">${clearLabel}</button>
        <span class="spacer"></span>
        <button type="button" class="btn btn-light btn-signature-cancel">${cancelLabel}</button>
        <button type="submit" class="btn btn-primary btn-signature-save">${saveLabel}</button>
    </div>
</div>
</div>`);
            $("body").append(signatureModal);

            const canvas = $(signatureModal).find("canvas")[0];
            const signaturePad = new SignaturePad(canvas);

            function resizeCanvas() {
                const ratio = Math.max(window.devicePixelRatio || 1, 1);
                canvas.width = canvas.offsetWidth * ratio;
                canvas.height = canvas.offsetHeight * ratio;
                canvas.getContext("2d").scale(ratio, ratio);
                signaturePad.clear(); // otherwise isEmpty() might return incorrect value
            }

            $(signatureModal)
                .find(".btn-signature-reset")
                .on("click", (e) => {
                    e.preventDefault();
                    signaturePad.clear();
                });
            $(signatureModal)
                .find(".btn-signature-cancel")
                .on("click", (e) => {
                    e.preventDefault();
                    signatureModal.remove();
                });
            $(signatureModal)
                .find(".btn-signature-save")
                .on("click", (e) => {
                    e.preventDefault();
                    $(img).attr("src", signaturePad.toDataURL());
                    $(input).val(signaturePad.toDataURL());
                    signatureModal.remove();
                });
            window.addEventListener("resize", resizeCanvas);
            resizeCanvas();
        });
    }

    $("[captcha-form]").each((i, elt) => {
        const url = $(elt).attr("captcha-form");
        const img = $(elt).find("[captcha-img]")[0];
        const inputKey = $(elt).find("[captcha-key]")[0];
        let key = "";

        function refreshCaptcha() {
            $.ajax(url, {
                method: "post",
                data: {
                    key: key,
                },
            }).done((res) => {
                $(img).attr("src", res.image);
                key = res.key;
                $(inputKey).val(key);
            });
        }

        $(elt).find("[captcha-refresh]").on("click", refreshCaptcha);

        refreshCaptcha();
    });

    $("[random-content-order]").each((i, elt) => {
        const template = $("<div>");
        $(elt)
            .children()
            .each((i, elt) => {
                if (!$(elt).prop("selected")) {
                    template.append($(elt));
                }
            });
        let children;
        while ((children = $(template).children()).length > 0) {
            const i = Math.floor(Math.random() * children.length);
            $(elt).append($(children[i]));
        }
    });

    $("input[type=file][maxfilesize]").each((i, elt) => {
        const maxFileSize = $(elt).attr("maxfilesize");
        const sizeError = $(elt).attr("sizeerror") || "File too large error:";

        $(elt).on("change", () => {
            for (let file of elt.files) {
                if (file.size > maxFileSize) {
                    alert(sizeError);
                    elt.value = "";
                }
            }
        });
    });

    $("[checkbox-multiple][required]").each((i, elt) => {
        const checkbox = $(elt).find("input[type='checkbox']");
        checkbox.prop("required", true);
        checkbox.change(function () {
            if (this.checked) {
                checkbox.prop("required", false);
            } else {
                checkbox.prop("required", !$(elt).find("input[type='checkbox']:checked").length);
            }
        });
    });

    const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
    $("form").each((i, elt) => {
        $(elt).prepend($(`<input type="hidden" value="${timezone}" name="timezone">`));
    });

    setTimeout(() => {
        $("form[data-form]").each((i, elt) => {
            $(elt).attr("action", $(elt).attr("data-form"));
        });
    }, 3000);
});
