(function () {
    // ---- Tab switching ----
    const tabs = document.querySelectorAll(".tls-tab");
    const panels = document.querySelectorAll(".tls-tab-panel");

    function activate(name) {
        tabs.forEach((btn) => {
            const active = btn.dataset.tab === name;
            btn.classList.toggle("is-active", active);
            btn.setAttribute("aria-selected", active ? "true" : "false");
        });
        panels.forEach((panel) => {
            panel.classList.toggle("is-active", panel.dataset.panel === name);
        });
        try {
            if (history.replaceState) {
                history.replaceState(null, "", "#" + name);
            }
        } catch (_) {}
    }

    if (tabs.length && panels.length) {
        tabs.forEach((btn) => {
            btn.addEventListener("click", () => activate(btn.dataset.tab));
        });
        const hash = (location.hash || "").replace(/^#/, "");
        const valid = ["summary", "reliability", "safety", "vulnerabilities", "compatibility", "log", "json"];
        if (valid.indexOf(hash) !== -1) {
            activate(hash);
        }
    }

    // ---- Shared copy helper (clipboard API + textarea fallback) ----
    async function copyText(text) {
        try {
            if (navigator.clipboard && navigator.clipboard.writeText) {
                await navigator.clipboard.writeText(text);
                return true;
            }
            const ta = document.createElement("textarea");
            ta.value = text;
            ta.style.position = "fixed";
            ta.style.opacity = "0";
            document.body.appendChild(ta);
            ta.select();
            try { document.execCommand("copy"); } catch (_) {}
            document.body.removeChild(ta);
            return true;
        } catch (_) {
            return false;
        }
    }

    // Swap a button's label and is-done class for 1.5s based on action result.
    function bindCopyButton(btn, getText) {
        if (!btn) return;
        const orig = btn.textContent;
        btn.addEventListener("click", async () => {
            const ok = await copyText(getText());
            btn.textContent = ok ? "コピーしました" : "コピー失敗";
            if (ok) btn.classList.add("is-done");
            setTimeout(() => {
                btn.textContent = orig;
                btn.classList.remove("is-done");
            }, 1500);
        });
    }

    // ---- JSON-copy button (inside the JSON tab) ----
    const rawJsonEl = document.getElementById("tls-raw-json");
    bindCopyButton(document.getElementById("tls-copy-json"), () => (rawJsonEl && rawJsonEl.textContent) || "");

    // ---- Copy-link button ----
    const copyLinkBtn = document.getElementById("tls-copy-link");
    bindCopyButton(copyLinkBtn, () => (copyLinkBtn && copyLinkBtn.dataset.link) || location.href);

    // ---- PDF / print button ----
    const printBtn = document.getElementById("tls-print-pdf");
    if (printBtn) {
        printBtn.addEventListener("click", () => {
            // Expand all tab panels so the printed PDF contains every finding,
            // then restore the previous state after the print dialog closes.
            const prev = [];
            panels.forEach((panel) => {
                prev.push([panel, panel.classList.contains("is-active")]);
                panel.classList.add("is-active");
            });
            const restore = () => {
                prev.forEach(([panel, wasActive]) => {
                    panel.classList.toggle("is-active", wasActive);
                });
                window.removeEventListener("afterprint", restore);
            };
            window.addEventListener("afterprint", restore);
            try {
                window.print();
            } catch (_) {
                restore();
            }
        });
    }
})();
