document.addEventListener('DOMContentLoaded', function () {
    async function getLatestVersionsInBatches(slugs, batchSize = 20) {
        const versions = {};
        for (let i = 0; i < slugs.length; i += batchSize) {
            const batch = slugs.slice(i, i + batchSize);
            try {
                const versionRequests = batch.map(slug =>
                    fetch(`https://api.wordpress.org/plugins/info/1.0/${slug}.json`)
                        .then(res => res.ok ? res.json() : null)
                        .catch(() => null)
                );
                const responses = await Promise.all(versionRequests);
                responses.forEach((data, index) => {
                    const slug = batch[index];
                    versions[slug] = data?.version || 'N/A';
                    const versionCell = document.querySelector(`#plugin-version-${slug}`);
                    if (versionCell) versionCell.textContent = versions[slug];
                });
            } catch (error) {
                console.error("Batch error fetching plugin versions:", error);
            }
            // hold
            await new Promise(r => setTimeout(r, 100));
        }
        return versions;
    }

    const apiEndpoint = fleximp_ajax_object.apiEndpoint;
    let isFetching = false;
    let allPlugins = [];

    async function fetchPlugins() {
        if (isFetching) return;
        isFetching = true;

        try {
            const response = await fetch(apiEndpoint, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ action: 'getPlugins' })
            });

            const data = await response.json();
            if (data.success && Array.isArray(data.data)) {
                allPlugins = data.data;
                await displayPlugins(allPlugins);

                // Collect slugs
                const slugs = allPlugins.map(plugin =>
                    plugin.text_domain || plugin.name.toLowerCase().replace(/ /g, '-')
                );

                getLatestVersionsInBatches(slugs, 30).then(versions => {
                    allPlugins.forEach(plugin => {
                        const slug = plugin.text_domain || plugin.name.toLowerCase().replace(/ /g, '-');
                        plugin.latest_version = versions[slug] || 'N/A';
                    });
                });
                const plugins = allPlugins.map(plugin => ({
                    slug: plugin.text_domain || plugin.name.toLowerCase().replace(/ /g, '-'),
                    main_file: plugin.main_file,
                }));
                fetchPluginStatuses(plugins);
            } else {
                console.error('Error fetching plugins:', data);
            }
        } catch (error) {
            console.error('Error:', error);
        } finally {
            isFetching = false;
        }
    }

    async function displayPlugins(plugins) {
        const pluginsListContainer = document.getElementById('plugins-list');
        pluginsListContainer.innerHTML = '';

        let tableHTML = `
        <div class="col plugin-tbl">
            <table class="table table-striped table-responsive-1">
                <thead class="plugin-table-head">
                    <tr class="text-center">
                        <th>Select</th>
                        <th>Image</th>
                        <th>Plugin Name</th>
                        <th>Version</th>
                        <th class="flex-plugin-main-file">Main File</th>
                        <th>Status</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody>
        `;

        for (const plugin of plugins) {
            const pluginSlug = plugin.text_domain || plugin.name.toLowerCase().replace(/ /g, '-');
            const pluginUrl = `https://downloads.wordpress.org/plugin/${pluginSlug}.latest-stable.zip`;

            tableHTML += `
                <tr class="text-center">
                    <td class="plugin-input flex-align">
                        <input type="checkbox" class="plugin-checkbox" 
                            data-plugin-name="${plugin.name}" 
                            data-plugin-url="${pluginUrl}" 
                            data-plugin-main-file="${plugin.main_file}">
                    </td>
                    <td class="flex-align"><img src="${plugin.image}" alt="${plugin.name}" style="width: 50px; height: 50px;"></td>
                    <td><p class="flex-plugin-title">${plugin.name}</p></td>
                    <td id="plugin-version-${pluginSlug}">
                    <p class="flex-plugin-title">${plugin.latest_version || "Loading…"}</p>
                </td>
                    <td class="flex-plugin-main-file"><p class="flex-plugin-title">${plugin.main_file}</p></td>
                    <td id="plugin-status-${pluginSlug}" class="flex-plugin-title-1"><p class="flex-plugin-title">Checking status...</p></td>
                    <td class="flex-align">
                        <a class="download-btn"
                            href="#"
                            data-plugin-name="${plugin.name}"
                            data-plugin-url="${pluginUrl}"
                            data-plugin-main-file="${plugin.main_file}">
                            <i class="fa fa-download" aria-hidden="true"></i>
                        </a>
                    </td>
                </tr>
            `;
        }

        tableHTML += `
                </tbody>
            </table>
        </div>
        `;

        pluginsListContainer.innerHTML = tableHTML;
    }

    function fetchPluginStatuses(plugins) {
        fetch(fleximp_ajax_object.ajax_url, {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: `action=fleximp_get_plugin_statuses&security=${fleximp_ajax_object.fleximp_nonce}&plugins=${encodeURIComponent(JSON.stringify(plugins))}`,
        })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    const statuses = data.data;
                    Object.keys(statuses).forEach(slug => {
                        const statusElement = document.getElementById(`plugin-status-${slug}`);
                        const buttonElement = document.querySelector(`.download-btn[data-plugin-url*="${slug}"]`);
                        if (statusElement) statusElement.textContent = statuses[slug];
                        if (buttonElement && statuses[slug] === 'Activated') {
                            buttonElement.classList.add('activated');
                            buttonElement.disabled = true;
                        }
                    });
                } else {
                    console.error('Error fetching plugin statuses:', data);
                }
            })
            .catch(error => console.error('Error fetching plugin statuses:', error));
    }

    // Initialization function for plugins tab
    let initialised = false;

    function initPlugins() {
        if (initialised) return;
        initialised = true;
        fetchPlugins();
    }

    // Check if Plugins tab is already active on page load
    if (jQuery('#plugins').hasClass('active') || jQuery('#plugins').hasClass('show')) {
        initPlugins();
    }

    // Bootstrap 3/4 tab shown event
    jQuery(document).on('shown.bs.tab', 'a[href="#plugins"]', function () {
        initPlugins();
    });
});
