/**
 * Shared "Create Page" handler for every preview screen — single author,
 * authors directory, and group. Each page defines only the globals it has;
 * the rest fall back to harmless defaults and the backend ignores them.
 *
 *   window.scholarSyncAjaxUrl          admin-ajax.php URL (required)
 *   window.scholarSyncCreatePageNonce  nonce for the scholar_sync_create_page action
 *   window.scholarSyncAuthorId         author id, or 0
 *   window.scholarSyncGroupId          group id, or 0/undefined
 *   window.scholarSyncViewType         group view type, or ''
 *
 * The shortcode is read from whichever shortcode field the page rendered.
 */
(function () {
    var btn    = document.getElementById('wps-create-page-btn');
    var result = document.getElementById('wps-create-page-result');
    if ( ! btn ) { return; }

    function showResult(success, links, errorMsg) {
        if ( ! result ) { return; }
        result.classList.add('is-visible');
        result.textContent = '';
        if (success) {
            result.appendChild( document.createTextNode('✓ Draft created! ') );
            var viewLink = document.createElement('a');
            viewLink.className = 'wps-create-page-link';
            viewLink.href = links.preview_url;
            viewLink.target = '_blank';
            viewLink.rel = 'noopener';
            viewLink.textContent = 'View Page';
            result.appendChild(viewLink);
            var editLink = document.createElement('a');
            editLink.className = 'wps-create-page-link';
            editLink.href = links.edit_url;
            editLink.target = '_blank';
            editLink.rel = 'noopener';
            editLink.textContent = 'Edit in WP';
            result.appendChild(editLink);
        } else {
            var errSpan = document.createElement('span');
            errSpan.style.color = '#d63638';
            errSpan.textContent = errorMsg || 'Error.';
            result.appendChild(errSpan);
        }
        result.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
    }

    btn.addEventListener('click', function () {
        var titleEl = document.getElementById('wps-page-title');
        var scEl    = document.getElementById('author-shortcode-display')
                   || document.getElementById('group-shortcode-display');
        var title     = titleEl ? titleEl.value : '';
        var shortcode = scEl    ? scEl.value    : '';

        if ( ! title.trim() ) {
            showResult(false, null, 'Please enter a page title.');
            return;
        }

        btn.disabled    = true;
        btn.textContent = 'Creating…';

        var data = new FormData();
        data.append('action',     'scholar_sync_create_page');
        data.append('nonce',      window.scholarSyncCreatePageNonce || '');
        data.append('page_title', title);
        data.append('shortcode',  shortcode);
        data.append('author_id',  window.scholarSyncAuthorId || 0);
        data.append('group_id',   window.scholarSyncGroupId  || 0);
        data.append('view_type',  window.scholarSyncViewType || '');

        fetch(window.scholarSyncAjaxUrl || '', { method: 'POST', body: data })
            .then(function (r) { return r.json(); })
            .then(function (json) {
                btn.textContent = '+ Create Page';
                btn.disabled = false;
                if (json.success) {
                    showResult(true, json.data, null);
                } else {
                    var msg = (json.data && json.data.message) ? json.data.message : 'Error creating page.';
                    showResult(false, null, msg);
                }
            })
            .catch(function () {
                btn.textContent = '+ Create Page';
                btn.disabled = false;
                showResult(false, null, 'Network error.');
            });
    });
}());
