/**
 * Block Registry Sync Page
 * Handles diff toggle and form confirmations
 */
(function () {
    'use strict';

    // POST buttons — creates a hidden form and submits it
    document.querySelectorAll('.js-sync-post').forEach(function (btn) {
        btn.addEventListener('click', function () {
            const message = btn.dataset.confirm;
            if (message && !confirm(message)) {
                return;
            }
            const form = document.createElement('form');
            form.method = 'POST';
            form.action = btn.dataset.url;
            form.style.display = 'none';
            document.body.appendChild(form);
            form.submit();
        });
    });

    // Toggle diff rows
    document.querySelectorAll('.js-toggle-diff').forEach(function (btn) {
        btn.addEventListener('click', function (e) {
            e.preventDefault();
            const slug = btn.dataset.slug;
            const diffRow = document.querySelector('[data-diff-slug="' + slug + '"]');

            if (!diffRow) {
                return;
            }

            const isExpanded = diffRow.classList.contains('is-expanded');

            if (isExpanded) {
                diffRow.classList.remove('is-expanded');
                return;
            }

            diffRow.classList.add('is-expanded');

            const diffContent = document.getElementById('diff-' + slug);
            if (diffContent.dataset.loaded) {
                return;
            }

            // Fetch diff via AJAX
            fetch('/admin/blocks/sync/diff/' + encodeURIComponent(slug))
                .then(function (response) {
                    return response.json();
                })
                .then(function (data) {
                    diffContent.innerHTML = renderDiff(data.diff);
                    diffContent.dataset.loaded = '1';
                })
                .catch(function (err) {
                    diffContent.innerHTML = '<span class="diff-removed">Failed to load diff: ' + err.message + '</span>';
                });
        });
    });

    /**
     * Render a diff object as HTML
     */
    function renderDiff(diff) {
        if (!diff || Object.keys(diff).length === 0) {
            return '<span class="diff-added">No differences found.</span>';
        }

        let html = '';

        // Metadata changes
        if (diff.metadata) {
            html += '<div class="diff-section">';
            html += '<div class="diff-section-title">Metadata</div>';
            html += '<div class="diff-detail">';
            for (const key in diff.metadata) {
                const change = diff.metadata[key];
                const dbVal = change.db === null ? 'null' : String(change.db);
                const jsonVal = change.json === null ? 'null' : String(change.json);
                html += '<div class="diff-changed">' + escapeHtml(key) + ': ';
                html += '<span class="diff-removed">' + escapeHtml(dbVal) + '</span>';
                html += ' &rarr; ';
                html += '<span class="diff-added">' + escapeHtml(jsonVal) + '</span>';
                html += '</div>';
            }
            html += '</div></div>';
        }

        // Field changes
        if (diff.fields) {
            html += '<div class="diff-section">';
            html += '<div class="diff-section-title">Fields</div>';
            html += '<div class="diff-detail">';

            if (diff.fields.added && diff.fields.added.length) {
                diff.fields.added.forEach(function (name) {
                    html += '<div class="diff-added">+ ' + escapeHtml(name) + '</div>';
                });
            }
            if (diff.fields.removed && diff.fields.removed.length) {
                diff.fields.removed.forEach(function (name) {
                    html += '<div class="diff-removed">- ' + escapeHtml(name) + '</div>';
                });
            }
            if (diff.fields.modified) {
                for (const name in diff.fields.modified) {
                    html += '<div class="diff-changed">~ ' + escapeHtml(name) + '</div>';
                    html += renderFieldChanges(diff.fields.modified[name]);
                }
            }
            html += '</div></div>';
        }

        // Template assignment changes
        if (diff.template_assignments) {
            html += '<div class="diff-section">';
            html += '<div class="diff-section-title">Template Assignments</div>';
            html += '<div class="diff-detail">';
            if (diff.template_assignments.added && diff.template_assignments.added.length) {
                diff.template_assignments.added.forEach(function (name) {
                    html += '<div class="diff-added">+ ' + escapeHtml(name) + '</div>';
                });
            }
            if (diff.template_assignments.removed && diff.template_assignments.removed.length) {
                diff.template_assignments.removed.forEach(function (name) {
                    html += '<div class="diff-removed">- ' + escapeHtml(name) + '</div>';
                });
            }
            html += '</div></div>';
        }

        return html;
    }

    function renderFieldChanges(changes) {
        let html = '<div class="diff-detail">';
        for (const key in changes) {
            if (key === 'sub_fields') {
                html += '<div class="diff-changed">sub_fields:</div>';
                html += '<div class="diff-detail">';
                const sf = changes[key];
                if (sf.added) {
                    sf.added.forEach(function (n) { html += '<div class="diff-added">+ ' + escapeHtml(n) + '</div>'; });
                }
                if (sf.removed) {
                    sf.removed.forEach(function (n) { html += '<div class="diff-removed">- ' + escapeHtml(n) + '</div>'; });
                }
                if (sf.modified) {
                    for (const n in sf.modified) {
                        html += '<div class="diff-changed">~ ' + escapeHtml(n) + '</div>';
                        html += renderFieldChanges(sf.modified[n]);
                    }
                }
                html += '</div>';
                continue;
            }

            const change = changes[key];
            const dbVal = change.db === null ? 'null' : JSON.stringify(change.db);
            const jsonVal = change.json === null ? 'null' : JSON.stringify(change.json);
            html += '<div class="diff-changed">' + escapeHtml(key) + ': ';
            html += '<span class="diff-removed">' + escapeHtml(dbVal) + '</span>';
            html += ' &rarr; ';
            html += '<span class="diff-added">' + escapeHtml(jsonVal) + '</span>';
            html += '</div>';
        }
        html += '</div>';
        return html;
    }

    function escapeHtml(str) {
        const div = document.createElement('div');
        div.appendChild(document.createTextNode(str));
        return div.innerHTML;
    }
})();
