/**
 * MassPost Gutenberg Notices
 * Displays MassPost errors in the Block Editor
 * When target rejects post, shows error and updates UI to reflect draft status
 */
(function () {
    'use strict';

    // Wait for wp.data to be ready
    if (typeof wp === 'undefined' || typeof wp.data === 'undefined') {
        return;
    }

    var subscribe = wp.data.subscribe;
    var select = wp.data.select;
    var dispatch = wp.data.dispatch;
    var wasSaving = false;
    var hasCheckedOnLoad = false;

    // Check for errors on page load (handles redirect after publish)
    setTimeout(function () {
        if (!hasCheckedOnLoad) {
            hasCheckedOnLoad = true;
            checkMassPostErrors();
        }
    }, 500);

    // Watch for save events
    subscribe(function () {
        var editor = select('core/editor');
        if (!editor) return;

        var isSaving = editor.isSavingPost();
        var isAutosaving = editor.isAutosavingPost();

        if (isSaving && !isAutosaving) {
            wasSaving = true;
        }

        if (!isSaving && wasSaving) {
            wasSaving = false;
            setTimeout(checkMassPostErrors, 300);
        }
    });

    function checkMassPostErrors() {
        if (!window.masspostNoticesVars) {
            return;
        }

        var editor = select('core/editor');
        if (!editor) {
            return;
        }

        var postId = editor.getCurrentPostId();

        var xhr = new XMLHttpRequest();
        xhr.open('POST', window.masspostNoticesVars.ajaxUrl, true);
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4) {
                if (xhr.status === 200) {
                    try {
                        var response = JSON.parse(xhr.responseText);
                        if (response.success && response.data && response.data.errors && response.data.errors.length > 0) {
                            // MassPost errors found - handle them
                            handleMassPostErrors(response.data.errors, postId);
                        }
                    } catch (e) {
                        // Silent fail
                    }
                }
            }
        };
        xhr.send('action=masspost_get_errors&post_id=' + postId + '&nonce=' + window.masspostNoticesVars.nonce);
    }

    /**
     * Handle MassPost errors: show error in publish panel only
     */
    function handleMassPostErrors(errors, postId) {
        // Only inject error into publish panel - avoid duplicate notices
        injectErrorIntoPublishPanel(errors);

        // Aggressively remove misleading "Post published" notices
        // We check multiple times to catch any race conditions
        removeSuccessNotices();
        setTimeout(removeSuccessNotices, 100);
        setTimeout(removeSuccessNotices, 300);
        setTimeout(removeSuccessNotices, 500);

        // Add a "Draft saved" notice if not present
        dispatch('core/notices').createNotice(
            'error',
            'Post saved as draft due to MassPost error.',
            {
                isDismissible: true,
                type: 'snackbar',
                explicitDismiss: true,
                id: 'masspost-draft-saved-error' // persistent ID to avoid duplicates
            }
        );

        // Refresh the post from server to get correct status
        refreshPostFromServer(postId);
    }

    /**
     * Remove generic success notices that WP might show
     */
    function removeSuccessNotices() {
        var notices = select('core/notices').getNotices();
        notices.forEach(function (notice) {
            if (notice.content && (typeof notice.content === 'string') &&
                (notice.content.includes('Post published') ||
                    notice.content.includes('Post updated') ||
                    notice.content.includes('published.'))) {
                dispatch('core/notices').removeNotice(notice.id);
            }
        });
    }


    /**
     * Refresh post data from server to get correct status
     */
    function refreshPostFromServer(postId) {
        // Use wp.data to invalidate and refetch the post
        if (dispatch('core') && dispatch('core').invalidateResolution) {
            dispatch('core').invalidateResolution('getEntityRecord', ['postType', 'post', postId]);
        }

        // Also try to refresh the editor's internal state
        if (select('core').getEntityRecord) {
            // Force refetch
            wp.apiFetch({
                path: '/wp/v2/posts/' + postId,
                method: 'GET'
            }).then(function (post) {
                if (post && post.status === 'draft') {
                    // Update the "is now live" text to show draft message
                    updatePublishPanelStatus(post);
                }
            });
        }
    }

    /**
     * Update publish panel to show correct status
     */
    function updatePublishPanelStatus(post) {
        // Find and update the "is now live" text
        var headerText = document.querySelector('.post-publish-panel__postpublish-header');
        if (headerText) {
            headerText.innerHTML = '<strong style="color: #DC2626;">⚠️ Post NOT published due to MassPost error</strong><br>Post saved as draft. Please fix the error and try again.';
        }
    }

    /**
     * Hide "is now live" text and View Post link when there's an error
     */
    function hidePublishedIndicators() {
        setTimeout(function () {
            // Hide the "is now live" header
            var liveHeader = document.querySelector('.post-publish-panel__postpublish-header');
            if (liveHeader) {
                var originalText = liveHeader.textContent;
                if (originalText.includes('is now live')) {
                    liveHeader.innerHTML = '<div style="background: #FEF2F2; border: 1px solid #DC2626; padding: 12px; border-radius: 4px; color: #DC2626;"><strong>⚠️ Post NOT Published</strong><br>Target site rejected the post. Post saved as draft.</div>';
                }
            }

            // Change "View Post" button to indicate error
            var viewPostBtn = document.querySelector('.post-publish-panel__postpublish-buttons a.is-primary');
            if (viewPostBtn && viewPostBtn.textContent.includes('View Post')) {
                viewPostBtn.style.display = 'none';
            }
        }, 200);
    }

    /**
     * Inject error message into editor-post-publish-panel
     * This ensures mobile users can see errors in the publish confirmation dialog
     */
    function injectErrorIntoPublishPanel(errors) {
        // Remove any existing MassPost error from panel
        var existingError = document.querySelector('.masspost-publish-panel-error');
        if (existingError) {
            existingError.remove();
        }

        // Wait a bit for panel to be visible
        setTimeout(function () {
            var publishPanel = document.querySelector('.editor-post-publish-panel__content');
            if (!publishPanel) {
                // Try again shortly as panel may not be open yet
                setTimeout(function () {
                    injectErrorIntoPublishPanel(errors);
                }, 500);
                return;
            }

            // Create error container
            var errorContainer = document.createElement('div');
            errorContainer.className = 'masspost-publish-panel-error';
            errorContainer.style.cssText = 'background: #FEF2F2; border: 1px solid #EF4444; border-radius: 4px; padding: 12px; margin: 12px; color: #DC2626;';

            // Add header
            var header = document.createElement('strong');
            header.style.cssText = 'display: block; margin-bottom: 8px; font-size: 13px;';
            header.textContent = '⚠️ MassPost Error - Post NOT Published';
            errorContainer.appendChild(header);

            // Add each error
            errors.forEach(function (msg) {
                var errorItem = document.createElement('div');
                errorItem.style.cssText = 'font-size: 12px; margin-top: 4px; line-height: 1.4;';
                errorItem.textContent = msg;
                errorContainer.appendChild(errorItem);
            });

            // Add instruction
            var instruction = document.createElement('div');
            instruction.style.cssText = 'font-size: 11px; margin-top: 8px; color: #991B1B; font-style: italic;';
            instruction.textContent = 'Post has been saved as draft. Please add a featured image and publish again.';
            errorContainer.appendChild(instruction);

            // Insert at the top of the content area
            publishPanel.insertBefore(errorContainer, publishPanel.firstChild);

            // Also try to insert into the header area for maximum visibility
            var panelHeader = document.querySelector('.editor-post-publish-panel__header');
            if (panelHeader && !panelHeader.querySelector('.masspost-header-warning')) {
                var headerWarning = document.createElement('span');
                headerWarning.className = 'masspost-header-warning';
                headerWarning.style.cssText = 'color: #DC2626; font-weight: bold; margin-left: 8px;';
                panelHeader.appendChild(headerWarning);
            }
        }, 100);
    }
})();

