/**
 * RSS NewsSync - Form Hash Sync
 * Updates hidden fields with current hash before form submission
 * MUST run BEFORE any other scripts modify the hash!
 *
 * @package NewsSync
 * @since 1.0.1
 */

(function() {
    'use strict';

    /**
     * Get current active tab from URL hash or default to 'hub'
     */
    function getCurrentTab() {
        var hash = window.location.hash;
        if (hash && hash.length > 1) {
            // Remove the # and return the section name
            return hash.substring(1);
        }
        return 'hub';
    }

    /**
     * Update all newssync_current_tab hidden fields with current hash
     */
    function updateCurrentTabFields() {
        var currentTab = getCurrentTab();
        var tabFields = document.querySelectorAll('input[name="newssync_current_tab"]');

        tabFields.forEach(function(field) {
            field.value = currentTab;
        });
    }

    /**
     * Monitor for manual hash changes (from history.replaceState, etc.)
     * Use MutationObserver + polling to catch all changes
     */
    function monitorHashChanges() {
        var lastHash = window.location.hash;

        // Polling: Check every 100ms for hash changes
        setInterval(function() {
            var currentHash = window.location.hash;
            if (currentHash !== lastHash) {
                lastHash = currentHash;
                updateCurrentTabFields();
            }
        }, 100);

        // Also listen to hashchange event
        window.addEventListener('hashchange', function() {
            updateCurrentTabFields();
        });
    }

    /**
     * Initialize IMMEDIATELY - don't wait for DOM
     * This is the FIRST thing that runs when the script loads
     */

    monitorHashChanges();

    // Also hook into form submission
    document.addEventListener('submit', function(e) {
        if (e.target && e.target.action && e.target.action.indexOf('admin-post.php') > -1) {
            // debug removed: updating hidden tab fields before admin-post submission
            updateCurrentTabFields();
        }
    }, true); // Use capture phase to catch before other handlers
})();
