/**
 * Encypher License Catalog (thin client)
 *
 * The license/rights templates are the server's single source of truth. This
 * module fetches the catalog once (builtin templates + the org's dashboard
 * templates) from the plugin REST proxy /encypher-provenance/v1/license-catalog
 * (which caches it in a transient and degrades to a stale copy on outage), and
 * exposes it to editor-sidebar.js and block-rights.js. The editor sends a
 * template id; the API resolves the fields at sign time.
 *
 * Local freeform authoring is intentionally not offered. A legacy `custom`
 * selection is included only when it is already saved, so opening an older
 * document cannot silently discard its existing terms.
 */
(function () {
    'use strict';

    var CACHE = { promise: null, data: null };

    function load() {
        if (CACHE.promise) {
            return CACHE.promise;
        }
        CACHE.promise = wp
            .apiFetch({ path: '/encypher-provenance/v1/license-catalog' })
            .then(function (resp) {
                CACHE.data = {
                    templates: resp && Array.isArray(resp.templates) ? resp.templates : [],
                    available: !!(resp && resp.available),
                    stale: !!(resp && resp.stale),
                };
                return CACHE.data;
            })
            .catch(function () {
                CACHE.data = { templates: [], available: false, stale: false };
                return CACHE.data;
            });
        return CACHE.promise;
    }

    function state() {
        return CACHE.data;
    }

    function getEntry(id) {
        if (!CACHE.data || !id) {
            return null;
        }
        for (var i = 0; i < CACHE.data.templates.length; i++) {
            if (CACHE.data.templates[i].id === id) {
                return CACHE.data.templates[i];
            }
        }
        return null;
    }

    /**
     * Options for a template picker. `includeInherit` swaps the empty
     * placeholder for the per-block wording. `selectedId` exists only to keep
     * an already-saved template visible when it is absent from the current
     * catalog; it never creates a new local custom-authoring path.
     */
    function comboboxOptions(includeInherit, selectedId) {
        var options = [];
        var seen = {};
        options.push(includeInherit ? { value: '', label: 'Inherit document default' } : { value: '', label: 'Select a license...' });
        if (CACHE.data && CACHE.data.templates) {
            CACHE.data.templates.forEach(function (entry) {
                if (!entry || !entry.id || seen[entry.id]) {
                    return;
                }
                seen[entry.id] = true;
                options.push({ value: entry.id, label: entry.label || entry.id });
            });
        }
        if (selectedId === 'custom') {
            options.push({ value: 'custom', label: 'Saved custom terms (read-only)', disabled: true });
        } else if (selectedId && !seen[selectedId]) {
            options.push({ value: selectedId, label: selectedId + ' (saved, read-only)', disabled: true });
        }
        return options;
    }

    window.EncypherLicenseCatalog = {
        load: load,
        state: state,
        getEntry: getEntry,
        comboboxOptions: comboboxOptions,
    };
})();
