if (typeof process === 'undefined') {
    window.process = { env: {} };
}
import Select from './vendor/react-select.min.js';
console.log('Initial globals check:', {
    React: !!window.React,
    ReactDOM: !!window.ReactDOM,
    axios: !!window.axios,
    createElement: !!window.React?.createElement,
    createRoot: !!window.ReactDOM?.createRoot
});
const React = window.React;
const { useState, useEffect, useMemo, useRef } = window.React;
const createRoot = window.ReactDOM?.createRoot;
const axios = window.axios;
if (!React || !useState || !useEffect || !createRoot || !axios) {
    console.error('Required globals missing:', {
        React: !!React,
        useState: !!useState,
        useEffect: !!useEffect,
        createRoot: !!createRoot,
        axios: !!axios
    });
    throw new Error('Required globals not loaded');
}
console.log('Globals captured successfully');
const PackageManager = () => {
    const [packages, setPackages] = useState([]);
    const [filter, setFilter] = useState('');
    const [progress, setProgress] = useState({});
    const [output, setOutput] = useState({});
    const [isLoading, setIsLoading] = useState({});
    const [expanded, setExpanded] = useState({});
    const [sshStatus, setSshStatus] = useState({ success: false, message: 'Checking SSH status...' });
    const [isPackagesLoading, setIsPackagesLoading] = useState(true);
    const isInitialFetch = useRef(true);
    const pollingIntervals = useRef({});
    console.log('Inside PackageManager, React is:', !!React);
    useEffect(() => {
        const checkSshStatus = () => {
            console.log('Starting checkSshStatus');
            axios
                .get(wpkginstAjax.ajax_url, {
                    params: { action: 'wpkginst_test_ssh_connection', nonce: wpkginstAjax.nonce },
                    timeout: 10000
                })
                .then((response) => {
                    console.log('SSH status response:', response.data);
                    const newSshStatus = {
                        success: response.data.success,
                        message: response.data.message || 'SSH connection successful'
                    };
                    setSshStatus(newSshStatus);
                    if (newSshStatus.success) {
                        console.log('SSH successful, fetching packages');
                        if (isInitialFetch.current) {
                            setIsPackagesLoading(true);
                        }
                        axios
                            .get(wpkginstAjax.ajax_url, {
                                params: { action: 'wpkginst_fetch_packages', nonce: wpkginstAjax.nonce },
                                timeout: 10000
                            })
                            .then((response) => {
                                console.log('get_packages success:', response.data);
                                if (response.data.success && Array.isArray(response.data.data.packages)) {
                                    setPackages([...response.data.data.packages]);
                                } else {
                                    console.error('Invalid packages data:', response.data);
                                    setPackages([]);
                                }
                                isInitialFetch.current = false;
                            })
                            .catch((error) => {
                                console.error('get_packages error:', error);
                                setPackages([]);
                            })
                            .finally(() => {
                                console.log('get_packages finally, isInitialFetch:', isInitialFetch.current);
                                setIsPackagesLoading(false);
                            });
                    } else {
                        console.log('SSH failed, clearing loading');
                        setIsPackagesLoading(false);
                    }
                })
                .catch((error) => {
                    console.error('test_ssh_connection error:', error);
                    setSshStatus({
                        success: false,
                        message: error.response?.data?.message || 'Failed to check SSH status'
                    });
                    setIsPackagesLoading(false);
                });
        };
        checkSshStatus();
        const interval = setInterval(checkSshStatus, 30000);
        return () => {
            clearInterval(interval);
            Object.values(pollingIntervals.current).forEach(clearInterval);
        };
    }, []);
    const handleAction = (packageName, action) => {
        if (!sshStatus.success) return;
        console.log('handleAction:', packageName, action);
        setIsLoading((prev) => ({ ...prev, [packageName]: true }));
        setProgress((prev) => ({ ...prev, [packageName]: '0%' }));
        axios
            .post(
                wpkginstAjax.ajax_url,
                {
                    action: action === 'install' ? 'wpkginst_install_package' : 'wpkginst_uninstall_package',
                    package: packageName,
                    nonce: wpkginstAjax.nonce
                },
                {
                    headers: { 'Content-Type': 'multipart/form-data' },
                    timeout: 10000
                }
            )
            .then((response) => {
                console.log('Action response:', response.data);
                if (response.data.success) {
                    setProgress((prev) => ({ ...prev, [packageName]: response.data.data.progress || '0%' }));
                    setOutput((prev) => ({ ...prev, [packageName]: response.data.data.output }));
                    setPackages((prev) => {
                        const newPackages = prev.map((pkg) =>
                            pkg.name === packageName
                                ? { ...pkg, installed: response.data.data.installed }
                                : pkg
                        );
                        console.log('setPackages:', newPackages, 'installed:', response.data.data.installed);
                        return [...newPackages];
                    });
                    if (response.data.data.progress !== '100%' || (action === 'install' && !response.data.data.installed) || (action === 'uninstall' && response.data.data.installed)) {
                        pollingIntervals.current[packageName] = setInterval(() => {
                            axios
                                .get(wpkginstAjax.ajax_url, {
                                    params: {
                                        action: 'wpkginst_fetch_package_progress',
                                        package: packageName,
                                        nonce: wpkginstAjax.nonce
                                    },
                                    timeout: 10000
                                })
                                .then((pollResponse) => {
                                    console.log('Polling response:', pollResponse.data);
                                    if (pollResponse.data.success) {
                                        setProgress((prev) => ({ ...prev, [packageName]: pollResponse.data.data.progress }));
                                        setOutput((prev) => ({ ...prev, [packageName]: pollResponse.data.data.output }));
                                        setPackages((prev) => {
                                            const newPackages = prev.map((pkg) =>
                                                pkg.name === packageName
                                                    ? { ...pkg, installed: pollResponse.data.data.installed }
                                                    : pkg
                                            );
                                            console.log('setPackages poll:', newPackages, 'installed:', pollResponse.data.data.installed);
                                            return [...newPackages];
                                        });
                                        if (pollResponse.data.data.progress === '100%' || (action === 'install' && pollResponse.data.data.installed) || (action === 'uninstall' && !pollResponse.data.data.installed)) {
                                            clearInterval(pollingIntervals.current[packageName]);
                                            delete pollingIntervals.current[packageName];
                                            setIsLoading((prev) => ({ ...prev, [packageName]: false }));
                                        }
                                    }
                                })
                                .catch((error) => {
                                    console.error('Polling error:', error);
                                    clearInterval(pollingIntervals.current[packageName]);
                                    delete pollingIntervals.current[packageName];
                                    setIsLoading((prev) => ({ ...prev, [packageName]: false }));
                                });
                        }, 2000);
                    } else {
                        setIsLoading((prev) => ({ ...prev, [packageName]: false }));
                    }
                } else {
                    console.error('Action failed:', response.data.data.message);
                    setIsLoading((prev) => ({ ...prev, [packageName]: false }));
                }
            })
            .catch((error) => {
                console.error('Error performing action:', error);
                setIsLoading((prev) => ({ ...prev, [packageName]: false }));
            });
    };
    const toggleOutput = (packageName) => {
        setExpanded((prev) => ({
            ...prev,
            [packageName]: !prev[packageName]
        }));
    };
    const filteredPackages = useMemo(() => {
        return packages.filter((pkg) => pkg.name.toLowerCase().startsWith(filter.toLowerCase()));
    }, [packages, filter]);
    return React.createElement(
        'div',
        { className: 'p-4' },
        React.createElement('h2', { className: 'text-2xl font-bold mb-4' }, 'Gestion des packages'),
        React.createElement(
            'div',
            { className: 'flex items-center mb-4' },
            React.createElement('span', { className: 'text-lg font-semibold mr-2' }, 'État SSH :'),
            React.createElement(
                'span',
                {
                    className: `inline-flex items-center px-3 py-1 rounded-full text-sm font-medium ${sshStatus.success ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'}`
                },
                sshStatus.success ? 'Connecté' : 'Non connecté',
                React.createElement('span', {
                    className: `ml-2 h-3 w-3 rounded-full ${sshStatus.success ? 'bg-green-500' : 'bg-red-500'}`
                })
            ),
            !sshStatus.success &&
                React.createElement('p', { className: 'ml-4 text-red-600' }, sshStatus.message)
        ),
        React.createElement(Select, {
            options: packages.map((pkg) => ({ value: pkg.name, label: pkg.name })),
            onInputChange: setFilter,
            placeholder: 'Rechercher un package...',
            className: 'mb-4'
        }),
        React.createElement(
            'table',
            { className: 'w-full border-collapse' },
            React.createElement(
                'thead',
                null,
                React.createElement(
                    'tr',
                    { className: 'bg-gray-200' },
                    React.createElement('th', { className: 'p-2' }, 'Package'),
                    React.createElement('th', { className: 'p-2' }, 'Statut'),
                    React.createElement('th', { className: 'p-2' }, 'Action'),
                    React.createElement('th', { className: 'p-2' }, 'Progression'),
                    React.createElement('th', { className: 'p-2' }, 'Détails')
                )
            ),
            React.createElement(
                'tbody',
                null,
                isPackagesLoading
                    ? Array(5).fill().map((_, index) =>
                          React.createElement(
                              'tr',
                              { key: `skeleton-${index}`, className: 'border-b' },
                              React.createElement('td', { className: 'p-2' },
                                  React.createElement('div', { className: 'h-4 bg-gray-200 rounded w-3/4 animate-pulse' })
                              ),
                              React.createElement('td', { className: 'p-2' },
                                  React.createElement('div', { className: 'h-4 bg-gray-200 rounded w-1/2 animate-pulse' })
                              ),
                              React.createElement('td', { className: 'p-2' },
                                  React.createElement('div', { className: 'h-8 bg-gray-200 rounded w-24 animate-pulse' })
                              ),
                              React.createElement('td', { className: 'p-2' },
                                  React.createElement('div', { className: 'h-2.5 bg-gray-200 rounded-full w-full animate-pulse' })
                              ),
                              React.createElement('td', { className: 'p-2' },
                                  React.createElement('div', { className: 'h-6 bg-gray-200 rounded w-20 animate-pulse' })
                              )
                          )
                      )
                    : filteredPackages.length === 0
                    ? React.createElement(
                          'tr',
                          null,
                          React.createElement(
                              'td',
                              { colSpan: 5, className: 'p-4 text-center text-gray-500' },
                              'Aucun package trouvé'
                          )
                      )
                    : filteredPackages.map((pkg) =>
                          React.createElement(
                              'tr',
                              { key: pkg.name, className: 'border-b' },
                              React.createElement('td', { className: 'p-2' }, pkg.name),
                              React.createElement('td', { className: 'p-2' }, pkg.installed ? 'Installé' : 'Non installé'),
                              React.createElement(
                                  'td',
                                  { className: 'p-2' },
                                  React.createElement(
                                      'button',
                                      {
                                          onClick: () => handleAction(pkg.name, pkg.installed ? 'uninstall' : 'install'),
                                          className: `px-4 py-2 rounded ${pkg.installed ? 'bg-red-500' : 'bg-green-500'} text-white ${isLoading[pkg.name] ? 'opacity-50 cursor-not-allowed' : ''}`,
                                          disabled: isLoading[pkg.name] || !sshStatus.success
                                      },
                                      isLoading[pkg.name]
                                          ? 'En cours...'
                                          : pkg.installed
                                          ? 'Désinstaller'
                                          : 'Installer'
                                  )
                              ),
                              React.createElement(
                                  'td',
                                  { className: 'p-2' },
                                  React.createElement(
                                      'div',
                                      { className: 'w-full bg-gray-200 rounded-full h-2.5' },
                                      React.createElement('div', {
                                          className: 'bg-blue-600 h-2.5 rounded-full transition-all duration-500',
                                          style: { width: progress[pkg.name] || '0%' }
                                      })
                                  )
                              ),
                              React.createElement(
                                  'td',
                                  { className: 'p-2' },
                                  React.createElement(
                                      'button',
                                      {
                                          onClick: () => toggleOutput(pkg.name),
                                          className: 'px-2 py-1 rounded bg-gray-500 text-white'
                                      },
                                      expanded[pkg.name] ? 'Masquer' : 'Afficher'
                                  ),
                                  expanded[pkg.name] &&
                                      React.createElement(
                                          'pre',
                                          { className: 'mt-2 p-2 bg-gray-100 text-sm overflow-auto' },
                                          output[pkg.name] || 'Aucune sortie disponible'
                                      )
                              )
                          )
                      )
            )
        )
    );
};
const rootElement = document.getElementById('wpkginst-package-manager');
if (rootElement) {
    const root = createRoot(rootElement);
    root.render(React.createElement(PackageManager));
} else {
    console.error('Root element #wpkginst-package-manager not found');
}
