export class DomUtils {
    constructor() {
        this.initClipboardCopy();
        this.initShareButtons();
        this.initTogglers();
        this.initStopPropagation();
        this.initCardLinks();
    }

    initClipboardCopy() {
        document.querySelectorAll("[data-copy]").forEach((btn) => {
            btn.addEventListener("click", async () => {
                const source = document.getElementById(btn.dataset.copy);
                if (!source) return;
                try {
                    await navigator.clipboard.writeText(source.textContent);
                    const original = btn.textContent;
                    btn.textContent = "Copied!";
                    setTimeout(() => { btn.textContent = original; }, 2000);
                } catch {
                    // silently fail
                }
            });
        });
    }

    initShareButtons() {
        document.querySelectorAll("[data-share]").forEach((btn) => {
            btn.addEventListener("click", async (e) => {
                e.preventDefault();
                e.stopPropagation();
                const url = new URL(btn.dataset.share || window.location.href, window.location.href).href;
                try {
                    await navigator.clipboard.writeText(url);
                    const original = btn.textContent;
                    btn.textContent = "Copied!";
                    setTimeout(() => { btn.textContent = original; }, 1000);
                } catch {
                    // silently fail
                }
            });
        });
    }

    initTogglers() {
        document.querySelectorAll("[data-toggle]").forEach((btn) => {
            btn.addEventListener("click", () => {
                const target = document.getElementById(btn.dataset.toggle);
                if (target) target.classList.toggle("hidden");
            });
        });
    }

    initStopPropagation() {
        document.querySelectorAll("[data-stop-propagation]").forEach((el) => {
            el.addEventListener("click", (e) => e.stopPropagation());
        });
    }

    initCardLinks() {
        document.querySelectorAll("[data-href]").forEach((el) => {
            el.addEventListener("click", (e) => {
                if (e.target.closest("[data-stop-propagation]")) return;
                const href = el.dataset.href;
                if (href) window.location.href = href;
            });
        });
    }
}
