<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Matrix VPN Monitor</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/Share-Tech-Mono/1.0.0/ShareTechMono.woff2" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?family=Orbitron" rel="stylesheet">
    <style>
        * {
            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;
            padding-bottom: 60px;
        }

        .container {
            padding: 1rem;
            margin: 0 auto;
            max-width: 800px;
            width: 100%;
        }

        /* Title Container and Animations */
        .title-container {
            text-align: center;
            padding: 20px 0;
            margin-top: 20px;
        }

        .main-title {
            font-family: 'Orbitron', sans-serif;
            font-size: 2.5em !important;
            color: #00ff00;
            text-transform: uppercase;
            letter-spacing: 3px;
            margin: 15px 0;
            text-shadow: 0 0 10px #00ff00;
            animation: titlePulse 2s infinite;
        }

        .subtitle {
            font-family: 'Share Tech Mono', monospace;
            color: #4ade80;
            font-size: 1.7em;
            letter-spacing: 2px;
            opacity: 0.8;
            animation: subtitleGlow 1.5s infinite alternate;
        }

        @keyframes titlePulse {
            0% { text-shadow: 0 0 10px #00ff00, 0 0 20px #00ff00; }
            50% { text-shadow: 0 0 20px #00ff00, 0 0 30px #00ff00, 0 0 40px #00ff00; }
            100% { text-shadow: 0 0 10px #00ff00, 0 0 20px #00ff00; }
        }

        @keyframes subtitleGlow {
            from {
                opacity: 0.8;
                text-shadow: 0 0 5px #4ade80;
            }
            to {
                opacity: 1;
                text-shadow: 0 0 15px #4ade80;
            }
        }

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

        .metric-card {
            border: 1px solid #00ff00;
            padding: 1.5rem;
            background: rgba(0, 255, 0, 0.05);
            backdrop-filter: blur(10px);
            box-shadow: 0 0 15px rgba(0, 255, 0, 0.1);
            transition: all 0.3s ease;
        }

        .metric-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 0 20px rgba(0, 255, 0, 0.2);
        }

        h1, h2 {
            text-transform: uppercase;
            font-family: 'Orbitron', sans-serif;
            letter-spacing: 2px;
            border-bottom: 2px solid #00ff00;
            padding-bottom: 0.5rem;
            margin: 1rem 0;
            text-align: center;
        }

       
        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;
        }

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

       
        .matrix-footer {
            position: fixed;
            bottom: 0;
            left: 0;
            width: 100%;
            background-color: rgba(0, 0, 0, 0.9);
            color: #4ade80;
            text-align: center;
            padding: 0.5rem 0;
            height: 60px;
            z-index: 1000;
        }

       
        /* Logo styles */
        .logo-container {
            text-align: center;
            margin-bottom: 25px;
            margin-top: 10px;
        }

        .vpn-logo {
            transform-origin: center;
            animation: logoSpin 20s linear infinite;
            width: 70px;
            height: 70px;
        }

        @keyframes logoSpin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        @media screen and (orientation: portrait) {
            .container {
                padding: 0.5rem;
            }

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

            .metric-card {
                width: 100%;
                margin-bottom: 1rem;
            }

            button {
                width: calc(100% - 1rem);
                margin: 0.5rem;
            }

            .main-title {
                font-size: 1em;
                padding: 0 10px;
            }

            .subtitle {
                font-size: 0.9em;
                padding: 0 10px;
            }

            .back-to-main {
                top: 10px;
                left: 10px;
                padding: 8px 15px;
                font-size: 0.9em;
            }

            #ipHistory {
                height: 200px;
                margin-bottom: 70px;
            }

            .vpn-logo {
                width: 60px;
                height: 60px;
            }
        }


#ipHistory {
    height: 200px;
    overflow-y: auto;
    border: 1px solid #00ff00;
    padding: 1rem;
    background: rgba(0, 0, 0, 0.7);
    font-size: 0.9rem;
    line-height: 1.5;
    margin: 20px 2rem; /* Added horizontal margin */
    max-width: calc(100% - 4rem); /* Accounts for margins */
    box-sizing: border-box;
}

/* For mobile portrait mode */
@media screen and (orientation: portrait) {
    .status,
    #ipHistory {
        margin: 1rem 1rem;
        max-width: calc(100% - 2rem);
    }
    
    #ipHistory {
        margin-bottom: 70px; /* Space for footer */
    }
}

status {
    padding: 1rem;
    margin: 1rem 2rem;  /* Added horizontal margin */
    border: 1px solid #00ff00;
    position: relative;
    background: rgba(0, 255, 0, 0.05);
    max-width: calc(100% - 4rem); /* Accounts for margins */
    box-sizing: border-box;
overflow: hidden;
}

.status.connected {
    background: rgba(0, 255, 0, 0.1);
    border-color: #00ff00;
    color: #00ff00;
    text-shadow: 0 0 5px #00ff00;
}

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

/* Alert styles for IP History */
.warning {
    color: #ffa500; /* Orange for warnings */
    text-shadow: 0 0 5px #ffa500;
}

.alert {
    color: #ffa500; /* Orange for alerts */
    text-shadow: 0 0 5px #ffa500;
}

/* Button styles */
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;
    border-color: rgba(0, 255, 0, 0.5);
}

#startBtn.scanning {
    background: rgba(0, 255, 0, 0.1);
    opacity: 0.5;
    cursor: not-allowed;
}
/* Fix for the back button */
.back-to-main {
    position: absolute; /* Changed from fixed to absolute */
    top: 20px;
    left: 20px;
    padding: 10px 20px;
    background: rgba(0, 255, 0, 0.1);
    border: 1px solid #0f0;
    color: #0f0;
    text-decoration: none;
    z-index: 10;
}

/* Container fixes for mobile */
.container {
    width: 100%;
    max-width: 800px;
    margin: 0 auto;
    padding: 1rem;
    overflow-x: hidden; /* Prevent horizontal scroll */
    position: relative;
}

/* Mobile-specific fixes */
@media screen and (orientation: portrait) {
    .container {
        padding: 0.5rem;
    }
    
    .metrics-grid,
    .status,
    #ipHistory,
    button {
        width: calc(100% - 2rem) !important; /* Force contained width */
        margin-left: 1rem !important;
        margin-right: 1rem !important;
        box-sizing: border-box !important;
    }
    
    button {
        width: calc(100% - 1rem) !important;
        margin: 0.5rem !important;
    }

    .back-to-main {
        top: 10px;
        left: 10px;
        padding: 8px 15px;
        font-size: 0.9em;
    }
}

/* Fix for buttons container */
.button-container {
    width: 100%;
    max-width: calc(100% - 2rem);
    margin: 1rem auto;
    text-align: center;
    box-sizing: border-box;
}

/* Metrics grid container fixes */
.metrics-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 1rem;
    margin: 1rem auto;
    max-width: 800px;
    box-sizing: border-box;
    padding: 0 1rem;
}

/* Individual metric card fixes */
.metric-card {
    border: 1px solid #00ff00;
    padding: 1.5rem;
    background: rgba(0, 255, 0, 0.05);
    backdrop-filter: blur(10px);
    box-shadow: 0 0 15px rgba(0, 255, 0, 0.1);
    transition: all 0.3s ease;
    width: 100%;
    box-sizing: border-box;
}

/* Mobile portrait mode fixes */
@media screen and (orientation: portrait) {
    .metrics-grid {
        grid-template-columns: 1fr;
        width: calc(100% - 2rem) !important;
        margin-left: 1rem !important;
        margin-right: 1rem !important;
        padding: 0;
        gap: 0.75rem;
    }
    .status {

        grid-template-columns: 1fr;
        width: calc(100% - 2rem) !important;
        margin-left: 1rem !important;
        margin-right: 1rem !important;
        padding: 0;
        gap: 0.75rem;

    }
    .metric-card {
        width: 100% !important;
        margin: 0 0 0.75rem 0;
        padding: 1rem;
    }
    
    /* Fix for metric values */
    .metric-value {
        word-break: break-word;
        overflow-wrap: break-word;
        font-size: 0.9em;
    }
}

/* General container width fix */
.container {
    width: 100%;
    max-width: 800px;
    margin: 0 auto;
    padding: 1rem;
    overflow-x: hidden;
}

@media screen and (max-width: 480px) {
    .container {
        padding: 0.5rem;
    }
}
    </style>
</head>
<body>

<iframe src="matrix.html" style="position: fixed; top: 0; left: 0; width: 100%; height: 100%; border: none; z-index: -1;"></iframe>

  <a href="https://kalkikrivadna.com/cyberkalkitoolsob.html" class="back-to-main">Back to Toolkit</a>
    
        
        <div class="title-container">
            <div class="logo-container">
                <svg class="vpn-logo" viewBox="0 0 100 100" width="120" height="120">
                    <circle class="outer-circle" cx="50" cy="50" r="45" fill="none" stroke="#00ff00" stroke-width="2"/>
                    <circle class="inner-circle" cx="50" cy="50" r="35" fill="none" stroke="#00ff00" stroke-width="2"/>
                    <path class="shield" d="M50 20 L70 30 L70 50 C70 65 50 75 50 75 C50 75 30 65 30 50 L30 30 Z" fill="none" stroke="#00ff00" stroke-width="2"/>
                    <path class="signal-waves" d="M50 45 L60 45 M50 52 L63 52 M50 59 L66 59" stroke="#00ff00" stroke-width="2"/>
                </svg>
            </div>
            <h1 class="main-title" style="font-size: 24px;">Matrix VPN Monitor</h1>
 
            <div class="subtitle">DNS LEAK & KILL SWITCH DETECTION BY CYBER KALKI</div>
        </div>

        <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>

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

        <h2 style="font-size: 18px;">System Log</h2>
        <div id="ipHistory"></div>
    </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>