<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Matrix VPN Monitor</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/Share-Tech-Mono/1.0.0/ShareTechMono.woff2" rel="stylesheet">
    <style>
        body {
            font-family: 'Share Tech Mono', monospace;
            background-color: #000;
            color: #00ff00;
            max-width: 800px;
            margin: 2rem auto;
            padding: 0 1rem;
            text-shadow: 0 0 5px #00ff00;
            position: relative;
            overflow-x: hidden;
        }

        body::before {
            content: "";
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: linear-gradient(rgba(0, 255, 0, 0.03), rgba(0, 255, 0, 0.03));
            pointer-events: none;
            z-index: -1;
        }

        h1, h2 {
            text-transform: uppercase;
            letter-spacing: 2px;
            border-bottom: 2px solid #00ff00;
            padding-bottom: 0.5rem;
            animation: glow 1.5s ease-in-out infinite alternate;
        }

        .status {
            padding: 1rem;
            margin: 1rem 0;
            border: 1px solid #00ff00;
            border-radius: 0;
            position: relative;
            overflow: hidden;
        }

        .status::before {
            content: "";
            position: absolute;
            top: 0;
            left: -100%;
            width: 100%;
            height: 2px;
            background-color: #00ff00;
            animation: scan 2s linear infinite;
        }

        .connected {
            background: rgba(0, 255, 0, 0.1);
            box-shadow: 0 0 10px rgba(0, 255, 0, 0.3);
        }

        .disconnected {
            background: rgba(255, 0, 0, 0.1);
            border-color: #ff0000;
            color: #ff0000;
            text-shadow: 0 0 5px #ff0000;
        }

        #ipHistory {
            height: 200px;
            overflow-y: auto;
            border: 1px solid #00ff00;
            padding: 1rem;
            background: rgba(0, 255, 0, 0.05);
            font-size: 0.9rem;
            line-height: 1.5;
        }

        #ipHistory::-webkit-scrollbar {
            width: 8px;
        }

        #ipHistory::-webkit-scrollbar-track {
            background: #000;
        }

        #ipHistory::-webkit-scrollbar-thumb {
            background: #00ff00;
            border-radius: 4px;
        }

        button {
            background: transparent;
            color: #00ff00;
            border: 1px solid #00ff00;
            padding: 0.5rem 1rem;
            margin: 0.5rem;
            cursor: pointer;
            font-family: 'Share Tech Mono', monospace;
            text-transform: uppercase;
            transition: all 0.3s ease;
            text-shadow: 0 0 5px #00ff00;
        }

        button:hover:not(:disabled) {
            background: rgba(0, 255, 0, 0.2);
            box-shadow: 0 0 10px rgba(0, 255, 0, 0.5);
        }

        button:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }

        @keyframes glow {
            from {
                text-shadow: 0 0 5px #00ff00, 0 0 10px #00ff00;
            }
            to {
                text-shadow: 0 0 10px #00ff00, 0 0 20px #00ff00;
            }
        }

        @keyframes scan {
            from {
                left: -100%;
            }
            to {
                left: 100%;
            }
        }

        /* Matrix rain effect */
        .matrix-rain {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            pointer-events: none;
            z-index: -1;
            opacity: 0.1;
        }

       .metrics-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 1rem;
            margin: 1rem 0;
        }

        .metric-card {
            border: 1px solid #00ff00;
            padding: 1rem;
            background: rgba(0, 255, 0, 0.05);
            box-shadow: 0 0 10px rgba(0, 255, 0, 0.1);
        }

        .metric-title {
            font-size: 0.9em;
            margin-bottom: 0.5rem;
            opacity: 0.8;
        }

        .metric-value {
            font-size: 1.2em;
            font-weight: bold;
        }


        .status {
            padding: 1rem;
            margin: 1rem 0;
            border: 1px solid #00ff00;
            border-radius: 0;
            position: relative;
            overflow: hidden;
        }

        #detailedInfo {
            margin-top: 1rem;
            display: none;
        }

        .warning {
            color: #ff9900;
            text-shadow: 0 0 5px #ff9900;
        }

        .error {
            color: #ff0000;
            text-shadow: 0 0 5px #ff0000;
        }
       #webrtcTestBtn {
            background: transparent;
            color: #00ff00;
            border: 1px solid #00ff00;
            padding: 0.5rem 1rem;
            margin: 0.5rem;
            cursor: pointer;
            font-family: 'Share Tech Mono', monospace;
            text-transform: uppercase;
            transition: all 0.3s ease;
            text-shadow: 0 0 5px #00ff00;
        }

        #webrtcTestBtn:hover:not(:disabled) {
            background: rgba(0, 255, 0, 0.2);
            box-shadow: 0 0 10px rgba(0, 255, 0, 0.5);
        }

        #webrtcTestBtn:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }
.matrix-footer {
                        position: fixed;
                        bottom: 0;
                        left: 0;
                        width: 100%;
                        background-color: rgba(0, 0, 0, 0.7);
                        color: #4ade80;
                        text-align: center;
                        padding: 0.5rem 0;
                        box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.5);
                        letter-spacing: 0.05em;
                        z-index: 9999; /* Ensures the footer appears above other elements */
                    }
                    .footer-content {
                        animation: pulse-slow 3s ease-in-out infinite;
                    }
                    .footer-line {
                        position: absolute;
                        left: 0;
                        right: 0;
                        bottom: 0;
                        height: 2px;
                        background-color: #22c55e;
                        opacity: 0.5;
                        filter: blur(1px);
                        animation: flicker 0.1s linear infinite;
                    }

/* Base styles remain the same */

/* Small devices (phones, 320px and up) */
@media only screen and (min-width: 320px) {
    body {
        margin: 1rem;
        padding: 0 0.5rem;
    }

    .metrics-grid {
        grid-template-columns: 1fr;
        gap: 0.75rem;
    }

    h1, h2 {
        font-size: 1.25rem;
        margin-bottom: 1rem;
    }

    .status {
        padding: 0.75rem;
        margin: 0.75rem 0;
    }

    button {
        width: 100%;
        margin: 0.5rem 0;
    }

    #ipHistory {
        height: 150px;
    }
}

/* Medium devices (tablets, 768px and up) */
@media only screen and (min-width: 768px) {
    body {
        margin: 1.5rem auto;
        padding: 0 1rem;
    }

    .metrics-grid {
        grid-template-columns: repeat(2, 1fr);
        gap: 1rem;
    }

    h1, h2 {
        font-size: 1.5rem;
    }

    button {
        width: auto;
        margin: 0.5rem;
    }

    #ipHistory {
        height: 200px;
    }
}

/* Large devices (desktops, 1024px and up) */
@media only screen and (min-width: 1024px) {
    body {
        margin: 2rem auto;
        max-width: 800px;
    }

    .metrics-grid {
        grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    }

    h1, h2 {
        font-size: 1.75rem;
    }
}

/* Extra safeguards for very small screens */
@media only screen and (max-width: 319px) {
    body {
        margin: 0.5rem;
        padding: 0 0.25rem;
    }

    .metric-card {
        padding: 0.5rem;
    }

    .metric-value {
        font-size: 1rem;
    }

    .matrix-footer {
        padding: 0.25rem 0;
        font-size: 0.8rem;
    }
}

/* Print styles */
@media print {
    body {
        background: white;
        color: black;
        text-shadow: none;
        margin: 1cm;
    }

    .matrix-rain,
    .matrix-footer,
    button {
        display: none;
    }

    .status::before {
        animation: none;
    }

    #ipHistory {
        height: auto;
        border: 1px solid black;
    }
}

/* Reset default margin and padding */
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body {
    font-family: 'Share Tech Mono', monospace;
    background-color: #000;
    color: #00ff00;
    text-shadow: 0 0 5px #00ff00;
    position: relative;
    overflow-x: hidden;
    min-height: 100vh;
    width: 100%;
}

/* Base container styles */
.container {
    width: 100%;
    padding: 1rem;
    margin: 0 auto;
}

/* Small devices (phones, 320px and up) */
@media only screen and (min-width: 320px) {
    body {
        padding: 1rem;
    }

    .container {
        width: 100%;
        min-height: 100vh;
    }

    .metrics-grid {
        grid-template-columns: 1fr;
        gap: 0.75rem;
        width: 100%;
    }

    h1, h2 {
        font-size: 1.25rem;
        margin-bottom: 1rem;
        width: 100%;
    }

    .status {
        padding: 0.75rem;
        margin: 0.75rem 0;
        width: 100%;
    }

    button {
        width: 100%;
        margin: 0.5rem 0;
    }

    #ipHistory {
        height: 150px;
        width: 100%;
    }

    .metric-card {
        width: 100%;
    }
}

/* Medium devices (tablets, 768px and up) */
@media only screen and (min-width: 768px) {
    .container {
        max-width: 720px;
        margin: 0 auto;
    }

    .metrics-grid {
        grid-template-columns: repeat(2, 1fr);
        gap: 1rem;
    }

    h1, h2 {
        font-size: 1.5rem;
    }

    button {
        width: auto;
        margin: 0.5rem;
    }
}

/* Large devices (desktops, 1024px and up) */
@media only screen and (min-width: 1024px) {
    .container {
        max-width: 800px;
    }

    .metrics-grid {
        grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    }

    h1, h2 {
        font-size: 1.75rem;
    }
}

/* Matrix rain and other styles remain the same */
.matrix-rain {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    pointer-events: none;
    z-index: -1;
    opacity: 0.1;
}

/* Footer adjustments */
.matrix-footer {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    padding: 0.5rem;
}

/* Ensure all content is properly spaced above footer */
main {
    padding-bottom: 60px; /* Adjust based on footer height */
}
    </style>
</head>

<body>

    <h1>Enhanced VPN Security Monitor</h1>

    <div id="currentStatus" class="status">Initializing secure connection verification...</div>

    <div class="metrics-grid">
        <div class="metric-card">
            <div class="metric-title">CURRENT IP</div>
            <div class="metric-value" id="currentIP">---.---.---.---</div>
        </div>

<div class="metric-card">
    <div class="metric-title">PRIVATE IPs</div>
    <div class="metric-value" id="privateIP">Scanning...</div>
</div>

        <div class="metric-card">
            <div class="metric-title">DNS LEAKS</div>
            <div class="metric-value" id="dnsStatus">Checking...</div>
        </div>
        <div class="metric-card">
            <div class="metric-title">LATENCY</div>
            <div class="metric-value" id="latency">-- ms</div>
        </div>
    </div>

    </div>

    <button onclick="startMonitoring()" id="startBtn">Initialize Security Scan</button>
    <button onclick="stopMonitoring()" id="stopBtn" disabled>Terminate Monitoring</button>


    <h2>System Log</h2>
    <div id="ipHistory"></div>
<footer class="matrix-footer">
                    <div class="footer-content">
                        © 2024 Cyber Kalki Matrix Tools | Prepare for Next Level of Digital Defense
                    </div>
                    <div class="footer-line"></div>
                </footer>
    <script>


// Constants
let monitoring = false;
let previousIP = '';
let checkInterval;
let killswitchInterval;
let consecutiveFailures = 0;
const previousConnections = new Set();
const recentLogs = new Set();
const LOG_EXPIRY_TIME = 30000; // 30 seconds

// API Services
const IP_SERVICES = [
    'https://api64.ipify.org?format=json',
    'https://api.ipapi.is/',
    'https://api.ipify.org?format=json',
    'https://ip.seeip.org/json'
];

const PROXY_API = 'https://proxycheck.io/v2/{ip}?key=28bkv6-lm5vi6-g8063j-569463&vpn=1';
const DNS_CHECK_API = 'https://dns-leak-test.com/api/test';

// Network Interface Detection


// Helper Functions
function isPrivateIP(ip) {
    return /^(10\.|172\.(1[6-9]|2[0-9]|3[0-1])\.|192\.168\.)/.test(ip);
}

// Core IP Check Functions
async function tryServices() {
    for (const service of IP_SERVICES) {
        try {
            const response = await fetch(service);
            const data = await response.json();
            const ip = data.ip || data.query || data.address;
            if (ip) return ip;
        } catch (error) {
            console.log(`Service ${service} failed:`, error);
            continue;
        }
    }
    throw new Error('All IP services failed');
}

async function checkProxyChain(ip) {
    try {
        // First try with proxycheck.io
        const proxyUrl = `https://proxycheck.io/v2/${ip}?key=28bkv6-lm5vi6-g8063j-569463&vpn=1`;
        let response = await fetch(proxyUrl, {
            method: 'GET',
            mode: 'cors',
            headers: { 'Accept': 'application/json' }
        });

        if (!response.ok) {
            // Fallback to alternative proxy detection
            response = await fetch(`https://vpn.bvss.fr/check/${ip}`);
        }

        const data = await response.json();
        const proxyInfo = data[ip] || data;

        const isProxy = proxyInfo.proxy === 'yes' || proxyInfo.type === 'VPN';
        const type = proxyInfo.type || 'Unknown';
        const provider = proxyInfo.provider || proxyInfo.network || '';

        const currentStatus = document.getElementById('proxyHops').textContent;
        const newStatus = isProxy ? `${type.toUpperCase()} ${provider}` : 'DIRECT';

        if (currentStatus !== newStatus) {
            document.getElementById('proxyHops').textContent = newStatus;
        }

        return isProxy;
    } catch (error) {
        console.error('Proxy check error:', error);
        return null;
    }
}

// Enhanced WebRTC Leak Detection
async function checkWebRTCLeaks() {
    try {
        const pc = new RTCPeerConnection({
            iceServers: [{ urls: 'stun:stun.l.google.com:19302' }]
        });

        return new Promise((resolve) => {
            const localIPs = new Set();
            let privateIPFound = false;
            let publicIPFound = false;

            pc.onicecandidate = (event) => {
                if (event.candidate) {
                    const matches = event.candidate.candidate.match(/([0-9]{1,3}(\.[0-9]{1,3}){3})/);
                    if (matches) {
                        const ip = matches[1];
                        localIPs.add(ip);

                        if (isPrivateIP(ip)) {
                            privateIPFound = true;
                        } else {
                            publicIPFound = true;
                        }
                    }
                } else {
                    pc.close();
                    const isLeaking = privateIPFound && publicIPFound;
                    if (isLeaking) {
                        logEvent('WebRTC leak detected - Local IP exposed', 'warning', true);
                    }
                    resolve(isLeaking);
                }
            };

            pc.createDataChannel('');
            pc.createOffer()
                .then(offer => pc.setLocalDescription(offer))
                .catch(() => resolve(true));

            setTimeout(() => {
                pc.close();
                resolve(privateIPFound && publicIPFound);
            }, 5000);
        });
    } catch {
        return true;
    }
}

        // Enhanced WebRTC testing function
        async function testWebRTC() {
            const button = document.getElementById('webrtcTestBtn');
            const statusElement = document.getElementById('webrtcStatus');

            button.disabled = true;
            button.textContent = 'Testing WebRTC...';
            statusElement.textContent = 'Checking...';

            try {
                const isLeaking = await checkWebRTCLeaks();
                if (isLeaking) {
                    logEvent('WARNING: WebRTC leak detected - Your real IP might be exposed', 'warning');
                    updateStatus('WebRTC Protection Failed', false);
                    statusElement.textContent = 'LEAKING';
                    statusElement.style.color = '#ff0000';
                } else {
                    logEvent('WebRTC protection test passed - No leaks detected', 'info');
                    updateStatus('WebRTC Protection Active', true);
                    statusElement.textContent = 'PROTECTED';
                    statusElement.style.color = '#00ff00';
                }
            } catch (error) {
                logEvent('WebRTC test failed - Error during check', 'error');
                statusElement.textContent = 'ERROR';
                statusElement.style.color = '#ff9900';
            } finally {
                button.disabled = false;
                button.textContent = 'Test WebRTC Protection';
            }
        }

        // Enhance the monitoring to include WebRTC checks
        async function startMonitoring() {
            monitoring = true;
            document.getElementById('startBtn').disabled = true;
            document.getElementById('stopBtn').disabled = false;

            // Initial WebRTC check
            await testWebRTC();

            checkIP();
            checkInterval = setInterval(checkIP, 5000);

            // Add periodic WebRTC checks
            webrtcInterval = setInterval(testWebRTC, 30000); // Check every 30 seconds


            logEvent('System monitoring initialized with WebRTC and killswitch verification');
        }

        // Update stopMonitoring to clear WebRTC interval
        function stopMonitoring() {
            monitoring = false;
            clearInterval(checkInterval);
            clearInterval(killswitchInterval);
            clearInterval(webrtcInterval);
            document.getElementById('startBtn').disabled = false;
            document.getElementById('stopBtn').disabled = true;
            logEvent('System monitoring terminated');
        }



// DNS Leak Detection
async function checkDNSLeaks() {
    try {
        document.getElementById('dnsStatus').textContent = 'CHECKING...';

        const checks = await Promise.all([
            checkSystemDNS(),
            checkWebRTCLeaks(),
            checkMultipleDNSServers()
        ]);

        const isLeaking = checks.some(result => result === true);

        document.getElementById('dnsStatus').textContent = isLeaking ? 'LEAKING' : 'PROTECTED';

        if (isLeaking) {
            logEvent('WARNING: DNS leak detected - Your real location might be exposed', 'warning');
        }

        return !isLeaking;
    } catch (error) {
        console.error('DNS check error:', error);
        document.getElementById('dnsStatus').textContent = 'CHECK FAILED';
        return null;
    }
}


async function detectPrivateIPs() {
    try {
        const pc = new RTCPeerConnection();
        const privateIPs = new Set();

        return new Promise((resolve) => {
            pc.onicecandidate = (event) => {
                if (event.candidate) {
                    const candidate = event.candidate.candidate;
                    const ipMatch = candidate.match(/([0-9]{1,3}(\.[0-9]{1,3}){3})/);

                    if (ipMatch) {
                        const ip = ipMatch[1];
                        if (isPrivateIP(ip)) {
                            privateIPs.add(ip);
                        }
                    }
                } else {
                    pc.close();
                    const privateIPArray = Array.from(privateIPs);

                    // Display private IPs
                    const privateIPElement = document.getElementById('privateIP');
                    privateIPElement.textContent = privateIPArray.length > 0
                        ? privateIPArray.join(', ')
                        : 'No private IPs detected';

                    resolve(privateIPArray);
                }
            };

            pc.createDataChannel('');
            pc.createOffer()
                .then(offer => pc.setLocalDescription(offer))
                .catch(() => resolve([]));

            setTimeout(() => {
                pc.close();
                resolve(Array.from(privateIPs));
            }, 5000);
        });
    } catch (error) {
        console.error('Failed to detect private IPs:', error);
        return [];
    }
}

async function checkSystemDNS() {
    try {
        const responses = await Promise.all([
            fetch('https://dns.google/resolve?name=myip.opendns.com&type=A'),
            fetch('https://cloudflare-dns.com/dns-query?name=myip.opendns.com&type=A'),
            fetch('https://dns.quad9.net/dns-query?name=myip.opendns.com&type=A')
        ]);

        const ips = new Set();

        for (const response of responses) {
            const data = await response.json();
            if (data.Answer) {
                data.Answer.forEach(record => ips.add(record.data));
            }
        }

        return ips.size > 1;
    } catch {
        return true;
    }
}

async function checkMultipleDNSServers() {
    const dnsServers = [
        'https://dns.google/resolve',
        'https://cloudflare-dns.com/dns-query',
        'https://dns.quad9.net/dns-query',
        'https://dns.adguard.com/dns-query'
    ];

    const testDomains = ['myip.opendns.com', 'whoami.akamai.net', 'resolver.dnscrypt.info'];
    const results = new Set();

    try {
        for (const server of dnsServers) {
            for (const domain of testDomains) {
                const response = await fetch(`${server}?name=${domain}&type=A`, {
                    headers: { 'Accept': 'application/dns-json' }
                });
                const data = await response.json();
                if (data.Answer) {
                    data.Answer.forEach(record => results.add(record.data));
                }
            }
        }

        return results.size > 1;
    } catch {
        return true;
    }
}

// Latency Check
async function checkLatency() {
    const start = performance.now();
    try {
        await fetch('https://api64.ipify.org?format=json');
        const latency = Math.round(performance.now() - start);
        document.getElementById('latency').textContent = `${latency} ms`;
        return latency;
    } catch (error) {
        document.getElementById('latency').textContent = 'ERROR';
        return null;
    }
}

// Main Check Functions
async function checkIP() {
    try {
        const currentIP = await tryServices();
        const privateIPs = await detectPrivateIPs(); // Add this line

        document.getElementById('currentIP').textContent = currentIP;

        const [proxyResult, dnsResult, latencyResult] = await Promise.all([
            checkProxyChain(currentIP),
            checkDNSLeaks(),
            checkLatency()
        ]);

        if (previousIP && previousIP !== currentIP) {
            logEvent(`ALERT: IP change detected: ${previousIP} → ${currentIP}`, 'warning');
        } else if (!previousIP) {
            logEvent(`Connection established: ${currentIP}`);
        }

        previousIP = currentIP;

        const isSecure = proxyResult && dnsResult && latencyResult < 500;
        updateStatus(
            `Status: ${isSecure ? 'SECURE' : 'WARNING'} - IP: ${currentIP}`,
            isSecure
        );

    } catch (error) {
        console.error('Check failed:', error);
        consecutiveFailures++;
        handleConnectionFailure();
    }
}

// UI Update Functions
function handleConnectionFailure() {
    if (consecutiveFailures >= 3) {
        logEvent('CRITICAL: Connection lost - Possible VPN failure', 'error');
        updateStatus('DISCONNECTED: Security compromised', false);
    } else {
        logEvent('WARNING: Check failed - Retrying...', 'warning');
    }
}

function updateStatus(message, connected) {
    const status = document.getElementById('currentStatus');
    status.textContent = message;
    status.className = `status ${connected ? 'connected' : 'disconnected'}`;
}

function logEvent(message, level = 'info', force = false) {
    const logKey = `${level}:${message}`;

    if (!force && recentLogs.has(logKey)) {
        return;
    }

    const history = document.getElementById('ipHistory');
    const time = new Date().toLocaleTimeString();
    const className = level === 'error' ? 'error' : level === 'warning' ? 'warning' : '';

    history.insertAdjacentHTML('afterbegin',
        `<div class="${className}">[${time}] ${message}</div>`
    );

    recentLogs.add(logKey);
    setTimeout(() => recentLogs.delete(logKey), LOG_EXPIRY_TIME);
}

// Killswitch Functions
async function monitorKillswitch() {
    try {
        const interfaces = await getNetworkInterfaces();
        const currentConnections = new Set(interfaces);

        for (const connection of currentConnections) {
            if (!previousConnections.has(connection)) {
                logEvent('ALERT: New network interface detected - Checking killswitch', 'warning');
                await verifyKillswitch();
            }
        }

        previousConnections.clear();
        currentConnections.forEach(conn => previousConnections.add(conn));

    } catch (error) {
        console.error('Killswitch monitoring error:', error);
    }
}

async function verifyKillswitch() {
    const vpnIP = previousIP;
    const testUrls = [
        'https://api64.ipify.org?format=json',
        'https://api.ipify.org?format=json',
        'https://ip.seeip.org/json'
    ];

    try {
        for (const url of testUrls) {
            try {
                const response = await fetch(url, {
                    mode: 'no-cors',
                    cache: 'no-store',
                    credentials: 'omit',
                    timeout: 5000
                });

                const data = await response.json();
                if (data.ip && data.ip !== vpnIP) {
                    logEvent('CRITICAL: Killswitch failure detected!', 'error', true);
                    return false;
                }
            } catch {
                continue;
            }
        }

        logEvent('Killswitch verified - Network properly secured', 'info', true);
        return true;
    } catch (error) {
        console.error('Killswitch verification error:', error);
        return null;
    }
}

// Button Event Handlers
async function testWebRTC() {
    const button = document.getElementById('webrtcTestBtn');
    button.disabled = true;
    button.textContent = 'Testing WebRTC...';

    try {
        const isLeaking = await checkWebRTCLeaks();
        if (isLeaking) {
            logEvent('WARNING: WebRTC leak detected - Your real IP might be exposed', 'warning');
            updateStatus('WebRTC Protection Failed', false);
        } else {
            logEvent('WebRTC protection test passed - No leaks detected', 'info');
            updateStatus('WebRTC Protection Active', true);
        }
    } catch (error) {
        logEvent('WebRTC test failed - Error during check', 'error');
    } finally {
        button.disabled = false;
        button.textContent = 'Test WebRTC Protection';
    }
}

function testKillswitch() {
    const button = document.getElementById('killswitchTestBtn');
    button.disabled = true;
    button.textContent = 'Testing...';

    verifyKillswitch().then(result => {
        if (result === true) {
            logEvent('Killswitch test passed - No leaks detected', 'info', true);
            updateStatus('Killswitch operational', true);
        } else if (result === false) {
            logEvent('Killswitch test failed - Traffic leaks possible', 'error', true);
            updateStatus('Killswitch failure detected', false);
        } else {
            logEvent('Killswitch test inconclusive', 'warning', true);
        }
    }).finally(() => {
        button.disabled = false;
        button.textContent = 'Test Killswitch';
    });
}

// Monitoring Control Functions
function startMonitoring() {
    monitoring = true;
    document.getElementById('startBtn').disabled = true;
    document.getElementById('stopBtn').disabled = false;

    checkIP();
    checkInterval = setInterval(checkIP, 5000);

    monitorKillswitch

monitorKillswitch();
    killswitchInterval = setInterval(monitorKillswitch, 10000);

    logEvent('System monitoring initialized with killswitch verification');
}

function stopMonitoring() {
    monitoring = false;
    clearInterval(checkInterval);
    clearInterval(killswitchInterval);
    document.getElementById('startBtn').disabled = false;
    document.getElementById('stopBtn').disabled = true;
    logEvent('System monitoring terminated');
}

// Security Check Functions
async function performSecurityChecks() {
    const checks = {
        vpn: false,
        proxy: false,
        dnsLeak: false,
        webRTC: false
    };

    try {
        checks.webRTC = await checkWebRTCLeaks();
        checks.dnsLeak = await checkDNSLeaks();

        const ip = await tryServices();
        const proxyResult = await checkProxyChain(ip);
        checks.proxy = proxyResult === true;
        checks.vpn = checks.proxy && await isVPN(ip);

        return checks;
    } catch (error) {
        console.error('Security checks failed:', error);
        return checks;
    }
}

async function isVPN(ip) {
    try {
        const response = await fetch(`https://vpn-check-api.com/check/${ip}`);
        const data = await response.json();
        return data.isVPN === true;
    } catch {
        return false;
    }
}

function updateDetailedInfo(checks) {
    const securityChecks = document.getElementById('securityChecks');
    const currentIP = document.getElementById('currentIP').textContent;

    securityChecks.innerHTML = `
        <div style="padding: 1rem;">
            <div style="margin-bottom: 0.5rem;">Current IP: ${currentIP}</div>
            <div style="margin-bottom: 0.5rem;">WebRTC Protection: ${checks.webRTC ? 'Active' : 'Inactive'}</div>
            <div style="margin-bottom: 0.5rem;">DNS Encryption: ${checks.dnsLeak ? 'Secure' : 'Check Failed'}</div>
            <div style="margin-bottom: 0.5rem;">Connection Protocol: ${checks.vpn ? 'VPN' : checks.proxy ? 'Proxy' : 'Direct'}</div>
            <div style="margin-bottom: 0.5rem;">Last Check: ${new Date().toLocaleTimeString()}</div>
        </div>
    `;
}

function toggleDetailedInfo() {
    const details = document.getElementById('detailedInfo');
    if (details.style.display === 'none') {
        details.style.display = 'block';
        performSecurityChecks().then(updateDetailedInfo);
    } else {
        details.style.display = 'none';
    }
}

// Initialize when document loads
document.addEventListener('DOMContentLoaded', function() {
    document.getElementById('detailedInfo').style.display = 'none';

    // Initialize event listeners for network changes
    if ('connection' in navigator) {
        navigator.connection.addEventListener('change', async () => {
            logEvent('Network change detected - Verifying security', 'warning');
            await monitorKillswitch();
            await checkIP();
        });
    }

    // Add periodic WebRTC check
    setInterval(async () => {
        if (monitoring) {
            const isLeaking = await checkWebRTCLeaks();
            if (isLeaking) {
                logEvent('WARNING: WebRTC leak detected during periodic check', 'warning');
            }
        }
    }, 30000); // Check every 30 seconds
});

// Export functions for external use if needed
window.vpnMonitor = {
    start: startMonitoring,
    stop: stopMonitoring,
    testKillswitch,
    testWebRTC,
    toggleDetailedInfo
};

</script>
</body>
</html>