/**
 * Encypher per-asset license selector (media screens).
 *
 * Enhances the attachment-details license field rendered by MediaLibraryUi:
 * populates the template <select> from the shared server catalog
 * (EncypherLicenseCatalog, the same source the block editor uses). New choices
 * are dashboard-owned templates only. A historical missing template id or
 * legacy custom selection remains visible as a selected, disabled read-only
 * option so opening attachment details cannot silently discard saved rights.
 */
(function () {
    'use strict';


    // Rebuild a template <select>'s options from the catalog, preserving the
    // currently selected value (even a stored id the catalog no longer lists).
    function populateSelect(select, templates, currentValue) {
        if (!select) {
            return;
        }
        var value = currentValue !== undefined ? currentValue : select.value;
        var options = [{ value: '', label: 'Use site default', disabled: false }];
        var seen = {};
        (templates || []).forEach(function (tpl) {
            if (!tpl || !tpl.id || seen[tpl.id]) {
                return;
            }
            seen[tpl.id] = true;
            options.push({ value: tpl.id, label: tpl.label || tpl.id, disabled: false });
        });
        if (value && !seen[value]) {
            options.push({
                value: value,
                label: value === 'custom' ? 'Saved custom terms (read-only)' : value + ' (saved, read-only)',
                disabled: true,
            });
        }

        select.innerHTML = '';
        options.forEach(function (opt) {
            var el = document.createElement('option');
            el.value = opt.value;
            el.textContent = opt.label;
            el.disabled = !!opt.disabled;
            if (opt.value === value) {
                el.selected = true;
            }
            select.appendChild(el);
        });
        select.value = value;
    }


    // Resolve the stored template id into the catalog's plain-language label.
    // The signed value stays read-only; this changes display text only.
    function enhanceSigned(container, state) {
        var summary = container.querySelector('[data-encypher-signed-rights-summary]');
        if (!summary) {
            return false;
        }
        var templateId = container.getAttribute('data-encypher-signed-template') || '';
        var templates = state && state.templates ? state.templates : [];
        for (var i = 0; i < templates.length; i++) {
            if (templates[i] && templates[i].id === templateId) {
                summary.textContent = templates[i].label || templateId;
                break;
            }
        }
        return true;
    }

    function enhance(container, state) {
        if (!container || container.getAttribute('data-encypher-enhanced') === '1') {
            return;
        }
        if (enhanceSigned(container, state)) {
            container.setAttribute('data-encypher-enhanced', '1');
            return;
        }
        var select = container.querySelector('.encypher-attachment-rights__template');
        if (!select) {
            return;
        }
        container.setAttribute('data-encypher-enhanced', '1');
        if (state && state.templates && state.templates.length) {
            populateSelect(select, state.templates, select.value);
        }
    }

    function enhanceAll(state) {
        var containers = document.querySelectorAll('[data-encypher-attachment-rights]');
        for (var i = 0; i < containers.length; i++) {
            enhance(containers[i], state);
        }
    }

    function boot() {
        var catalog = window.EncypherLicenseCatalog;
        var apply = function (state) {
            enhanceAll(state || (catalog && catalog.state ? catalog.state() : null));
        };
        if (catalog && typeof catalog.load === 'function') {
            catalog.load().then(apply).catch(function () { apply(null); });
        } else {
            apply(null);
        }
        // The media modal renders compat fields lazily; re-enhance on DOM
        // additions so newly opened attachment details get the picker.
        if (typeof MutationObserver === 'function' && document.body) {
            var observer = new MutationObserver(function () {
                enhanceAll(catalog && catalog.state ? catalog.state() : null);
            });
            observer.observe(document.body, { childList: true, subtree: true });
        }
    }

    window.EncypherMediaRights = {
        populateSelect: populateSelect,
        enhanceSigned: enhanceSigned,
        enhance: enhance,
        enhanceAll: enhanceAll,
    };

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', boot);
    } else {
        boot();
    }
})();
