function checkPwd() {
    const ls = window.localStorage;
    const id = document.getElementById("public_id").dataset.content;
    const pwd = ls.getItem(`ecoffee-pwd:${id}`);
    if (pwd) {
        const to_show = document.querySelectorAll(".needs_pwd");
        to_show.forEach(el => {
            el.classList.add("shown");
        });

        const to_hide = document.querySelectorAll(".no_pwd");
        to_hide.forEach(el => {
            el.classList.add("hidden");
        });

        const buttons = document.querySelectorAll(".action");
        buttons.forEach(btn => {
          const oldUrl= btn.getAttribute("hx-post");
          btn.setAttribute("hx-post", `${oldUrl}&pwd=${pwd}`);
        });

        const forms = document.querySelectorAll(".action-form");
        forms.forEach(form => {
           const oldUrl = form.getAttribute("action");
           form.setAttribute("action", `${oldUrl}&pwd=${pwd}`);
        });

        const pwd_el = document.getElementById("password");
        pwd_el.innerHTML = pwd;
    }

    const copy_els = document.querySelectorAll(".copyable");
    const cb = window.navigator.clipboard;
    copy_els.forEach(el => {
        el.addEventListener("click", evt => {
            evt.preventDefault();
            let content = el.dataset.copyContent;
            if (content.includes("???")) {
                content = content.replace("???", pwd);
            }
            cb.writeText(content).then(() => {
                const curText = el.innerHTML;
                el.innerHTML = "copied!";
                setTimeout(() => {
                    el.innerHTML = curText;
                }, 2000);
            });
        });
    });
}

checkPwd();

document.addEventListener("htmx:afterRequest", evt => {
    if (evt.target.tagName === "FORM") {
        evt.target.reset();
    }
    checkPwd();
})
