window.WBPopups = (() => {
    const cache = new Map();
    const docs = {
        cli: { title: "CLI Guide", template: "cli" },
        faq: { title: "Help & FAQ", template: "faq" },
        dailyQuota: { title: "Upload limits", template: "upload-limits" },
        about: { title: "About WarpBox", template: "about", about: true },
        examples: { title: "Examples", template: "examples" },
    };

    async function loadTemplate(name) {
        if (cache.has(name)) return cache.get(name);
        const response = await fetch(`/static/popups/${name}.html`, { credentials: "same-origin" });
        if (!response.ok) throw new Error(`Could not load popup template: ${name}`);
        const template = await response.text();
        cache.set(name, template);
        return template;
    }

    async function renderTemplate(name, data = {}) {
        const template = await loadTemplate(name);
        return window.WBUtils.renderTemplate(template, data);
    }

    async function renderDoc(name, data = {}) {
        const doc = docs[name];
        if (!doc) return null;
        return {
            title: doc.title,
            about: Boolean(doc.about),
            html: await renderTemplate(doc.template, data),
        };
    }

    return { renderTemplate, renderDoc };
})();
