/**
 * Modern AJAX loader using Fetch API
 * Call it with a single config object (or array that gets converted)
 * used in older code Search "biFetch"
 */
function biFetch(config) {
    // Accept array or object (for easy fallback with old callers)
    if (Array.isArray(config)) {
        config = Object.fromEntries(config); // if someone passes [["key", value], ...]
    }
    if (!config || typeof config !== 'object') {
        alert('biFetch: calling error! config must be an object');
        return;
    }

    // Defaults
    const options = {
        loadDiv: 'ajax-load',           // target div id
        script: '/',                    // everything goes through index.php
        href: window.location.href,
        loadingMessage: '',             // optional
        toggle: false,
        show: false,
        loadContainer: null,
        callback: null,
        ...config                        // override with whatever you pass
    };

    const targetDiv = document.getElementById(options.loadDiv);
    if (!targetDiv) {
        console.error(`biFetch: Target div #${options.loadDiv} does not exist`);
        return;
    }

    // Determine container (used for .loading class and show/hide)
    let container = options.loadContainer 
        ? document.getElementById(options.loadContainer)
        : (options.loadDiv === 'ajax-load' 
            ? document.getElementById('ajax-load-container') 
            : targetDiv);

    // Toggle behavior
    if (options.toggle) {
        if (targetDiv.innerHTML.trim() !== '') {
            targetDiv.innerHTML = '';
            return;
        }
    }

    // Show loading state
    if (options.show && container) {
        container.classList.remove('hidden');
        container.classList.add('loading');
    }

    if (options.loadingMessage) {
        targetDiv.innerHTML = options.loadingMessage;
    }

    // Add the ajax flag so your backend knows it's an AJAX request
    options.ajax = true;

    // Perform the fetch (POST with form data, just like old jQuery .load did)
    fetch(options.script, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: new URLSearchParams(options)
    })
    .then(response => {
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        return response.text();
    })
    .then(html => {
        targetDiv.innerHTML = html;

        // Run callback if provided
        if (typeof options.callback === 'function') {
            options.callback();
        }

        // Final cleanup
        if (options.show && container) {
            container.classList.remove('loading');
        }

        document.querySelectorAll('.ajax-complete').forEach(el => el.classList.remove('hidden'));
        document.querySelectorAll('.ajax-loading').forEach(el => el.classList.add('hidden'));
    })
    .catch(error => {
        console.error('biFetch error:', error);
        targetDiv.innerHTML = `
            <p style="color:red;">Error loading content from ${options.script}</p>
            <p>${error.message}</p>
        `;
        if (options.show && container) {
            container.classList.remove('loading');
        }
    });
}