// retoor <retoor@molodetz.nl>

import { OptimisticAction } from "./OptimisticAction.js";

export class BookmarkManager extends OptimisticAction {
    constructor() {
        super();
        document.addEventListener("click", (event) => this.onClick(event));
    }

    async onClick(event) {
        const button = event.target.closest(".bookmark-btn");
        if (!button) {
            return;
        }
        event.preventDefault();
        const type = button.dataset.bookmarkType;
        const uid = button.dataset.bookmarkUid;
        await this.submit(`/bookmarks/${type}/${uid}`, {}, null, (result) => {
            button.classList.toggle("bookmarked", result.saved);
            const label = button.querySelector(".bookmark-label");
            if (label) {
                label.textContent = result.saved ? "Saved" : "Save";
            }
        });
    }
}
