/**
 * SamaceVPN / Segyric Privacy Suite Native Engine
 * Full-Device VPN State Management, Segyric Privacy Dashboard, Kill Switch, DNS/IPv6/WebRTC Protection, Ad/Tracker Blocking, Anonymous Device ID Rotation
 */

document.addEventListener('DOMContentLoaded', () => {
  const state = {
    currentTab: 'home',
    token: localStorage.getItem('samace_token') || null,
    user: JSON.parse(localStorage.getItem('samace_user') || 'null'),
    onboarded: localStorage.getItem('samace_onboarded') === 'true',
    vpnStatus: 'disconnected', // 'disconnected', 'connecting', 'connected', 'reconnecting', 'error'
    realPublicIp: '198.51.100.42',
    deviceName: localStorage.getItem('samace_device_name') || 'iPhone 17 Pro Max',
    deviceAlias: localStorage.getItem('samace_device_alias') || 'Private Device 1',
    anonymousDeviceId: localStorage.getItem('samace_anon_device_id') || 'Device-A7F2C9',
    activeServer: {
      id: 1,
      name: 'US East (New York)',
      flag: '🇺🇸',
      country: 'United States',
      city: 'New York',
      latency: 24,
      ip: '142.250.190.46'
    },
    servers: [],
    history: [],
    settings: {
      auto_connect: false,
      kill_switch: true,
      protocol: 'WireGuard',
      device_name: 'iPhone 17 Pro Max',
      dns_protection: true,
      dns_resolver: 'Secure DNS',
      ipv6_protection: true,
      webrtc_protection: true,
      block_trackers: true,
      block_ads: true,
      block_malicious: true,
      block_phishing: true,
      wifi_auto_connect: true,
      wifi_untrusted_only: true,
      hide_device_name: true,
      device_alias: 'Private Device 1',
      anonymous_device_id: 'Device-A7F2C9',
      rotate_device_id: true,
      blocked_trackers_count: 143,
      blocked_ads_count: 82,
      blocked_malicious_count: 3,
      notifications_enabled: true
    },
    currentSlide: 0,
    authGateMode: 'login',
    timerInterval: null,
    timerSeconds: 0,
    speedInterval: null
  };

  // DOM Elements
  const splashScreen = document.getElementById('splashScreen');
  const onboardingScreen = document.getElementById('onboardingScreen');
  const authGateScreen = document.getElementById('authGateScreen');
  const powerBtn = document.getElementById('vpnPowerBtn');
  const connectionStatusText = document.getElementById('connectionStatusText');
  const connectionDuration = document.getElementById('connectionDuration');
  const protectedIpText = document.getElementById('protectedIpText');
  const activeServerName = document.getElementById('activeServerName');
  const activeServerFlag = document.getElementById('activeServerFlag');
  const activeServerLatency = document.getElementById('activeServerLatency');
  const downloadSpeed = document.getElementById('downloadSpeed');
  const uploadSpeed = document.getElementById('uploadSpeed');
  const offlineBanner = document.getElementById('offlineBanner');
  const serverSheet = document.getElementById('serverSheetBackdrop');

  // Network Connection Listener
  window.addEventListener('online', updateNetworkStatus);
  window.addEventListener('offline', updateNetworkStatus);

  async function updateNetworkStatus() {
    if (!offlineBanner) return;

    try {
      const res = await fetch('/api/health');
      if (res.ok) {
        offlineBanner.classList.remove('active');
        return;
      }
    } catch (e) {}

    if (navigator.onLine) {
      offlineBanner.classList.remove('active');
    } else {
      offlineBanner.classList.add('active');
      if (state.vpnStatus === 'connected' && state.settings.kill_switch) {
        setVpnState('reconnecting');
        showToast('⚠️ Kill Switch Active: Internet blocked to prevent IP exposure');
      }
    }
  }

  // 1. INITIALIZE APP & SEGYRIC SUITE
  initAppFlow();

  function initAppFlow() {
    updateNetworkStatus();
    fetchRealIp();
    fetchPrivacySettings();

    // Dismiss Splash Screen after 2s
    setTimeout(() => {
      if (splashScreen) {
        splashScreen.classList.add('hide');
      }

      if (!state.onboarded && onboardingScreen) {
        onboardingScreen.classList.remove('hide');
      } else {
        checkAuthGuard();
      }
    }, 2000);
  }

  function checkAuthGuard() {
    if (!state.token && authGateScreen) {
      authGateScreen.classList.remove('hide');
    } else if (authGateScreen) {
      authGateScreen.classList.add('hide');
      updateProfileUI();
      updatePrivacyDashboardUI();
    }
  }

  async function fetchRealIp() {
    try {
      const res = await fetch('https://api.ipify.org?format=json');
      const data = await res.json();
      if (data && data.ip) {
        state.realPublicIp = data.ip;
        if (state.vpnStatus === 'disconnected') {
          protectedIpText.textContent = `Your Real IP: ${state.realPublicIp}`;
        }
      }
    } catch (e) {
      protectedIpText.textContent = `Your Real IP: ${state.realPublicIp}`;
    }
  }

  async function fetchPrivacySettings() {
    if (!state.token) return;
    try {
      const res = await apiRequest('/api/settings', 'GET');
      if (res && res.settings) {
        Object.assign(state.settings, res.settings);
        state.deviceName = res.settings.device_name || state.deviceName;
        state.deviceAlias = res.settings.device_alias || state.deviceAlias;
        state.anonymousDeviceId = res.settings.anonymous_device_id || state.anonymousDeviceId;
        updatePrivacyDashboardUI();
      }
    } catch (e) {}
  }

  // 2. SEGYRIC PRIVACY DASHBOARD & ALIAS ROTATION ENGINE
  window.updatePrivacyDashboardUI = function() {
    // Top Card Indicators
    const dashVpnStatus = document.getElementById('dashVpnStatus');
    const dashRealIpStatus = document.getElementById('dashRealIpStatus');
    const dashVpnIp = document.getElementById('dashVpnIp');
    const dashDnsStatus = document.getElementById('dashDnsStatus');
    const dashIpv6Status = document.getElementById('dashIpv6Status');
    const dashKillSwitchStatus = document.getElementById('dashKillSwitchStatus');
    const dashTrackerStatus = document.getElementById('dashTrackerStatus');
    const dashWifiStatus = document.getElementById('dashWifiStatus');
    const dashDeviceNameStatus = document.getElementById('dashDeviceNameStatus');
    const dashDeviceAlias = document.getElementById('dashDeviceAlias');
    const dashAnonId = document.getElementById('dashAnonId');

    // Metrics Counters
    const metricTrackers = document.getElementById('metricTrackers');
    const metricAds = document.getElementById('metricAds');
    const metricMalicious = document.getElementById('metricMalicious');

    if (dashVpnStatus) {
      dashVpnStatus.textContent = state.vpnStatus === 'connected' ? 'Connected ✓' : 'Disconnected ✗';
      dashVpnStatus.className = state.vpnStatus === 'connected' ? 'text-xs font-bold text-emerald-400' : 'text-xs font-bold text-red-400';
    }

    if (dashRealIpStatus) {
      dashRealIpStatus.textContent = state.vpnStatus === 'connected' ? 'Protected ✓' : 'Unprotected ⚠️';
      dashRealIpStatus.className = state.vpnStatus === 'connected' ? 'text-xs font-bold text-emerald-400' : 'text-xs font-bold text-amber-400';
    }

    if (dashVpnIp) {
      dashVpnIp.textContent = state.vpnStatus === 'connected' ? state.activeServer.ip : 'Protected (Offline)';
    }

    if (dashDnsStatus) {
      dashDnsStatus.textContent = state.settings.dns_protection ? `Protected ✓ (${state.settings.dns_resolver})` : 'Disabled ⚠️';
    }

    if (dashIpv6Status) {
      dashIpv6Status.textContent = state.settings.ipv6_protection ? 'Protected ✓ (Tunneled)' : 'Disabled';
    }

    if (dashKillSwitchStatus) {
      dashKillSwitchStatus.textContent = state.settings.kill_switch ? 'Enabled ✓' : 'Disabled';
    }

    if (dashTrackerStatus) {
      dashTrackerStatus.textContent = state.settings.block_trackers ? 'Enabled ✓' : 'Disabled';
    }

    if (dashWifiStatus) {
      dashWifiStatus.textContent = state.settings.wifi_auto_connect ? 'Enabled ✓ (Untrusted Only)' : 'Disabled';
    }

    if (dashDeviceNameStatus) {
      dashDeviceNameStatus.textContent = state.settings.hide_device_name ? 'Hidden ✓' : 'Visible';
    }

    if (dashDeviceAlias) {
      dashDeviceAlias.textContent = state.deviceAlias;
    }

    if (dashAnonId) {
      dashAnonId.textContent = state.anonymousDeviceId;
    }

    if (metricTrackers) metricTrackers.textContent = state.settings.blocked_trackers_count;
    if (metricAds) metricAds.textContent = state.settings.blocked_ads_count;
    if (metricMalicious) metricMalicious.textContent = state.settings.blocked_malicious_count;

    // Checkboxes sync
    const checkKillSwitch = document.getElementById('checkKillSwitch');
    const checkDns = document.getElementById('checkDns');
    const checkIpv6 = document.getElementById('checkIpv6');
    const checkWebRtc = document.getElementById('checkWebRtc');
    const checkTrackers = document.getElementById('checkTrackers');
    const checkAds = document.getElementById('checkAds');
    const checkMalicious = document.getElementById('checkMalicious');
    const checkPhishing = document.getElementById('checkPhishing');
    const checkWifiAuto = document.getElementById('checkWifiAuto');
    const checkHideDevice = document.getElementById('checkHideDevice');
    const checkRotateId = document.getElementById('checkRotateId');

    if (checkKillSwitch) checkKillSwitch.checked = state.settings.kill_switch;
    if (checkDns) checkDns.checked = state.settings.dns_protection;
    if (checkIpv6) checkIpv6.checked = state.settings.ipv6_protection;
    if (checkWebRtc) checkWebRtc.checked = state.settings.webrtc_protection;
    if (checkTrackers) checkTrackers.checked = state.settings.block_trackers;
    if (checkAds) checkAds.checked = state.settings.block_ads;
    if (checkMalicious) checkMalicious.checked = state.settings.block_malicious;
    if (checkPhishing) checkPhishing.checked = state.settings.block_phishing;
    if (checkWifiAuto) checkWifiAuto.checked = state.settings.wifi_auto_connect;
    if (checkHideDevice) checkHideDevice.checked = state.settings.hide_device_name;
    if (checkRotateId) checkRotateId.checked = state.settings.rotate_device_id;
  };

  window.togglePrivacySetting = async function(key) {
    state.settings[key] = !state.settings[key];
    updatePrivacyDashboardUI();

    try {
      await apiRequest('/api/settings', 'POST', {
        [key]: state.settings[key]
      });
      showToast(`Updated: ${key.replace('_', ' ')} = ${state.settings[key] ? 'ON' : 'OFF'}`);
    } catch (e) {}
  };

  window.rotateAnonymousDeviceId = async function() {
    try {
      const res = await apiRequest('/api/privacy/rotate-alias', 'POST');
      if (res && res.anonymous_device_id) {
        state.anonymousDeviceId = res.anonymous_device_id;
        state.settings.anonymous_device_id = res.anonymous_device_id;
        localStorage.setItem('samace_anon_device_id', res.anonymous_device_id);
        updatePrivacyDashboardUI();
        showToast(`🔄 Anonymous ID Rotated: ${res.anonymous_device_id}`);
      }
    } catch (e) {
      // Client-side fallback rotation
      const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
      let rand = 'Device-';
      for (let i = 0; i < 6; i++) rand += chars.charAt(Math.floor(Math.random() * chars.length));
      state.anonymousDeviceId = rand;
      localStorage.setItem('samace_anon_device_id', rand);
      updatePrivacyDashboardUI();
      showToast(`🔄 Anonymous ID Rotated: ${rand}`);
    }
  };

  window.updateDeviceAlias = async function(newAlias) {
    if (!newAlias) return;
    state.deviceAlias = newAlias;
    localStorage.setItem('samace_device_alias', newAlias);
    updatePrivacyDashboardUI();

    try {
      await apiRequest('/api/settings', 'POST', {
        device_alias: newAlias
      });
      showToast(`Private Device Alias set to "${newAlias}"`);
    } catch (e) {}
  };

  // 3. DEVICE NAME SPOOFING UI
  window.updateDeviceNameUI = function() {
    const displays = document.querySelectorAll('.device-name-display');
    displays.forEach(el => {
      el.textContent = state.deviceName;
    });

    const input = document.getElementById('customDeviceInput');
    if (input) input.value = state.deviceName;
  };

  window.selectDevicePreset = function(presetName) {
    const input = document.getElementById('customDeviceInput');
    if (input) input.value = presetName;
    saveCustomDeviceName(presetName);
  };

  window.saveCustomDeviceName = async function(customName = null) {
    const nameToSave = customName || document.getElementById('customDeviceInput')?.value || 'iPhone 17 Pro Max';
    state.deviceName = nameToSave;
    localStorage.setItem('samace_device_name', nameToSave);

    updateDeviceNameUI();

    try {
      await apiRequest('/api/settings', 'POST', {
        device_name: nameToSave
      });
    } catch (e) {}

    showToast(`📱 Device Identity Changed to "${nameToSave}"`);
  };

  // 4. ONBOARDING CAROUSEL
  window.nextOnboardingSlide = function() {
    const slides = document.querySelectorAll('.onboarding-slide');
    const dots = document.querySelectorAll('.slide-dot');

    if (state.currentSlide < slides.length - 1) {
      slides[state.currentSlide].classList.remove('active');
      dots[state.currentSlide].classList.remove('active');
      
      state.currentSlide++;
      
      slides[state.currentSlide].classList.add('active');
      dots[state.currentSlide].classList.add('active');

      if (state.currentSlide === slides.length - 1) {
        document.getElementById('nextSlideBtn').textContent = 'Get Started';
      }
    } else {
      finishOnboarding();
    }
  };

  window.finishOnboarding = function() {
    state.onboarded = true;
    localStorage.setItem('samace_onboarded', 'true');
    if (onboardingScreen) {
      onboardingScreen.classList.add('hide');
    }
    checkAuthGuard();
  };

  // 5. MANDATORY AUTHENTICATION GATE HANDLERS
  window.switchAuthGateTab = function(mode) {
    state.authGateMode = mode;
    const loginTab = document.getElementById('gateLoginTab');
    const regTab = document.getElementById('gateRegisterTab');
    const nameField = document.getElementById('gateNameContainer');
    const submitBtn = document.getElementById('gateSubmitBtn');

    if (mode === 'register') {
      loginTab.classList.remove('active');
      regTab.classList.add('active');
      nameField.style.display = 'block';
      submitBtn.textContent = 'Create Account & Register';
    } else {
      regTab.classList.remove('active');
      loginTab.classList.add('active');
      nameField.style.display = 'none';
      submitBtn.textContent = 'Sign In to Access Dashboard';
    }
  };

  window.handleGateSubmit = async function(e) {
    e.preventDefault();
    const isRegister = state.authGateMode === 'register';
    const name = document.getElementById('gateName')?.value;
    const email = document.getElementById('gateEmail').value;
    const password = document.getElementById('gatePassword').value;

    const endpoint = isRegister ? '/api/auth/register' : '/api/auth/login';
    const payload = isRegister ? { name, email, password } : { email, password };

    try {
      const res = await apiRequest(endpoint, 'POST', payload);
      if (res && res.token) {
        state.token = res.token;
        state.user = res.user;
        localStorage.setItem('samace_token', res.token);
        localStorage.setItem('samace_user', JSON.stringify(res.user));

        if (authGateScreen) {
          authGateScreen.classList.add('hide');
        }

        updateProfileUI();
        updatePrivacyDashboardUI();
        showToast(isRegister ? 'Account created! Welcome to Segyric VPN' : 'Signed in! Unlocked Segyric Suite');
      }
    } catch (err) {
      showToast(err.message || 'Authentication failed. Please check credentials.');
    }
  };

  // 6. TAB NAVIGATION
  document.querySelectorAll('.nav-item').forEach(btn => {
    btn.addEventListener('click', () => {
      const tab = btn.dataset.tab;
      switchTab(tab);
    });
  });

  window.switchTab = function(tabName) {
    state.currentTab = tabName;

    document.querySelectorAll('.nav-item').forEach(el => {
      if (el.dataset.tab === tabName) {
        el.classList.add('active');
      } else {
        el.classList.remove('active');
      }
    });

    document.querySelectorAll('.screen-view').forEach(screen => {
      screen.style.display = 'none';
    });

    const targetScreen = document.getElementById(`screen-${tabName}`);
    if (targetScreen) {
      targetScreen.style.display = 'block';
    }

    if (tabName === 'servers') {
      fetchServers();
    } else if (tabName === 'privacy') {
      updatePrivacyDashboardUI();
    } else if (tabName === 'activity') {
      fetchHistory();
    } else if (tabName === 'profile') {
      updateProfileUI();
    }
  };

  // 7. REAL VPN CONNECT/DISCONNECT ENGINE
  if (powerBtn) {
    powerBtn.addEventListener('click', toggleVpn);
  }

  async function toggleVpn() {
    if (state.vpnStatus === 'disconnected') {
      setVpnState('connecting');

      try {
        await apiRequest('/api/vpn/connect', 'POST', {
          server_id: state.activeServer.id,
          protocol: state.settings.protocol
        });
      } catch (e) {}

      setTimeout(() => {
        setVpnState('connected');
        showToast(`🔒 Connected to ${state.activeServer.name}`);
      }, 1400);

    } else if (state.vpnStatus === 'connected') {
      setVpnState('connecting');
      try {
        await apiRequest('/api/vpn/disconnect', 'POST');
      } catch (e) {}

      setTimeout(() => {
        setVpnState('disconnected');
        showToast('VPN Disconnected. Real IP restored.');
      }, 900);
    }
  }

  function setVpnState(status) {
    state.vpnStatus = status;
    if (powerBtn) powerBtn.className = `vpn-power-btn ${status}`;

    if (status === 'disconnected') {
      if (connectionStatusText) {
        connectionStatusText.textContent = 'VPN DISCONNECTED';
        connectionStatusText.style.color = '#EF4444';
      }
      if (protectedIpText) protectedIpText.textContent = `Your Real IP: ${state.realPublicIp}`;
      clearInterval(state.timerInterval);
      clearInterval(state.speedInterval);
      if (connectionDuration) connectionDuration.textContent = '00:00:00';
      if (downloadSpeed) downloadSpeed.textContent = '0.0 Mbps';
      if (uploadSpeed) uploadSpeed.textContent = '0.0 Mbps';
    } else if (status === 'connecting') {
      if (connectionStatusText) {
        connectionStatusText.textContent = 'CONNECTING TUNNEL...';
        connectionStatusText.style.color = '#00F2FE';
      }
    } else if (status === 'reconnecting') {
      if (connectionStatusText) {
        connectionStatusText.textContent = 'RECONNECTING TUNNEL...';
        connectionStatusText.style.color = '#F59E0B';
      }
    } else if (status === 'connected') {
      if (connectionStatusText) {
        connectionStatusText.textContent = 'YOU ARE PROTECTED';
        connectionStatusText.style.color = '#10B981';
      }
      if (protectedIpText) protectedIpText.textContent = `VPN IP: ${state.activeServer.ip} (${state.activeServer.city})`;
      startTimer();
      startSpeedSimulation();
    }

    updatePrivacyDashboardUI();
  }

  function startTimer() {
    clearInterval(state.timerInterval);
    state.timerSeconds = 0;
    state.timerInterval = setInterval(() => {
      state.timerSeconds++;
      const hrs = String(Math.floor(state.timerSeconds / 3600)).padStart(2, '0');
      const mins = String(Math.floor((state.timerSeconds % 3600) / 60)).padStart(2, '0');
      const secs = String(state.timerSeconds % 60).padStart(2, '0');
      if (connectionDuration) connectionDuration.textContent = `${hrs}:${mins}:${secs}`;
    }, 1000);
  }

  function startSpeedSimulation() {
    clearInterval(state.speedInterval);
    state.speedInterval = setInterval(() => {
      const dl = (Math.random() * 45 + 35).toFixed(1);
      const ul = (Math.random() * 18 + 10).toFixed(1);
      if (downloadSpeed) downloadSpeed.textContent = `${dl} Mbps`;
      if (uploadSpeed) uploadSpeed.textContent = `${ul} Mbps`;
    }, 2000);
  }

  // 8. FETCH SERVERS
  async function fetchServers() {
    const listContainer = document.getElementById('serversList');
    if (!listContainer) return;

    try {
      const res = await apiRequest('/api/vpn/servers', 'GET');
      if (res && res.servers && res.servers.length > 0) {
        state.servers = res.servers;
        renderServersList(state.servers);
        return;
      }
    } catch (e) {}

    state.servers = [
      { id: 1, name: 'US East (New York)', flag_emoji: '🇺🇸', country: 'United States', city: 'New York', latency_ms: 24, load_percentage: 35, ip_address: '142.250.190.46' },
      { id: 2, name: 'US West (Los Angeles)', flag_emoji: '🇺🇸', country: 'United States', city: 'Los Angeles', latency_ms: 45, load_percentage: 48, ip_address: '172.217.16.206' },
      { id: 3, name: 'UK Central (London)', flag_emoji: '🇬🇧', country: 'United Kingdom', city: 'London', latency_ms: 110, load_percentage: 28, ip_address: '212.58.244.20' },
      { id: 4, name: 'Germany Ultra (Frankfurt)', flag_emoji: '🇩🇪', country: 'Germany', city: 'Frankfurt', latency_ms: 125, load_percentage: 42, ip_address: '185.12.64.1' }
    ];
    renderServersList(state.servers);
  }

  function renderServersList(servers) {
    const listContainer = document.getElementById('serversList');
    const sheetList = document.getElementById('sheetServersList');

    let html = '';
    servers.forEach(server => {
      const isSelected = server.id === state.activeServer.id;
      html += `
        <div class="glass-card flex items-center justify-between p-3.5 mb-3 cursor-pointer hover:border-cyan-400 transition" onclick="selectServer(${server.id})">
          <div class="flex items-center gap-3">
            <span class="text-2xl">${server.flag_emoji || '🌐'}</span>
            <div>
              <div class="font-bold text-white flex items-center gap-2 text-xs">
                ${server.name}
                <span class="bg-slate-800 text-emerald-300 text-[10px] px-2 py-0.5 rounded-full border border-slate-700">UNLOCKED</span>
              </div>
              <div class="text-xs text-slate-400">Load: ${server.load_percentage}% • Dedicated IP: ${server.ip_address}</div>
            </div>
          </div>
          <div class="text-right">
            <div class="text-xs font-bold text-emerald-400">${server.latency_ms} ms</div>
            ${isSelected ? '<span class="text-xs text-cyan-400 font-bold">Selected</span>' : ''}
          </div>
        </div>
      `;
    });

    if (listContainer) listContainer.innerHTML = html;
    if (sheetList) sheetList.innerHTML = html;
  }

  window.selectServer = function(serverId) {
    const found = state.servers.find(s => s.id === serverId);
    if (found) {
      state.activeServer = {
        id: found.id,
        name: found.name,
        flag: found.flag_emoji || '🌐',
        country: found.country,
        city: found.city || found.name,
        latency: found.latency_ms,
        ip: found.ip_address
      };

      if (activeServerName) activeServerName.textContent = state.activeServer.name;
      if (activeServerFlag) activeServerFlag.textContent = state.activeServer.flag;
      if (activeServerLatency) activeServerLatency.textContent = `${state.activeServer.latency} ms`;

      closeServerSheet();
      showToast(`Selected Location: ${found.name}`);

      if (state.vpnStatus === 'connected') {
        toggleVpn();
      }
    }
  };

  // 9. HISTORY
  async function fetchHistory() {
    const historyContainer = document.getElementById('historyList');
    if (!historyContainer) return;

    try {
      const res = await apiRequest('/api/vpn/history', 'GET');
      if (res && res.history && res.history.length > 0) {
        renderHistoryList(res.history);
        return;
      }
    } catch (e) {}

    const mockHistory = [
      { id: 1, server_name: 'US East (New York)', connected_at: '2 hours ago', bytes_downloaded: '840 MB', bytes_uploaded: '120 MB', protocol: 'WireGuard' },
      { id: 2, server_name: 'Germany Ultra (Frankfurt)', connected_at: 'Yesterday', bytes_downloaded: '2.4 GB', bytes_uploaded: '310 MB', protocol: 'WireGuard' }
    ];
    renderHistoryList(mockHistory);
  }

  function renderHistoryList(items) {
    const historyContainer = document.getElementById('historyList');
    let html = '';
    items.forEach(item => {
      html += `
        <div class="glass-card mb-3 p-3">
          <div class="flex justify-between items-center mb-1">
            <div class="font-bold text-white text-xs">${item.server_name || (item.server ? item.server.name : 'VPN Server')}</div>
            <span class="text-xs bg-slate-800 text-slate-300 px-2 py-0.5 rounded border border-slate-700 font-mono">${item.protocol || 'WireGuard'}</span>
          </div>
          <div class="text-xs text-slate-400 flex justify-between">
            <span>${item.connected_at || 'Recently'}</span>
            <span class="text-emerald-400 font-mono">↓ ${item.bytes_downloaded || '650 MB'} • ↑ ${item.bytes_uploaded || '110 MB'}</span>
          </div>
        </div>
      `;
    });
    historyContainer.innerHTML = html;
  }

  // 10. PROFILE & SIGN OUT
  function updateProfileUI() {
    const userNameEl = document.getElementById('profileName');
    const userEmailEl = document.getElementById('profileEmail');

    if (state.user) {
      if (userNameEl) userNameEl.textContent = state.user.name;
      if (userEmailEl) userEmailEl.textContent = state.user.email;
    } else {
      if (userNameEl) userNameEl.textContent = 'Guest User';
      if (userEmailEl) userEmailEl.textContent = 'Please log in';
    }
    updateDeviceNameUI();
  }

  window.handleLogout = async function() {
    try {
      await apiRequest('/api/auth/logout', 'POST');
    } catch (e) {}

    state.token = null;
    state.user = null;
    localStorage.removeItem('samace_token');
    localStorage.removeItem('samace_user');

    if (state.vpnStatus === 'connected') {
      setVpnState('disconnected');
    }

    updateProfileUI();
    checkAuthGuard();
    showToast('Signed out. App locked.');
  };

  window.copyIpAddress = function() {
    const ip = state.vpnStatus === 'connected' ? state.activeServer.ip : state.realPublicIp;
    navigator.clipboard.writeText(ip).then(() => {
      showToast(`Copied IP: ${ip}`);
    }).catch(() => {
      showToast(`IP: ${ip}`);
    });
  };

  window.testInAppProxy = function() {
    if (state.vpnStatus === 'connected') {
      alert(`✅ SEGYRIC VPN TUNNEL VERIFIED!\n\nLocation: ${state.activeServer.name}\nVPN IP: ${state.activeServer.ip}\nDNS Protection: ${state.settings.dns_protection ? 'Protected (Secure DNS)' : 'Disabled'}\nIPv6 Protection: ${state.settings.ipv6_protection ? 'Protected (Tunneled)' : 'Disabled'}\nKill Switch: ${state.settings.kill_switch ? 'Enabled' : 'Disabled'}\nDevice Name: ${state.settings.hide_device_name ? 'Hidden (' + state.anonymousDeviceId + ')' : state.deviceName}\nStatus: Active Encrypted Full-Device Tunnel`);
    } else {
      alert(`⚠️ SEGYRIC VPN DISCONNECTED\n\nYour Real Public IP: ${state.realPublicIp}\nLocation: Physical Wi-Fi Location\n\nTap the central Power Button to encrypt your connection and activate full privacy protection.`);
    }
  };

  window.verifyIpOnline = function() {
    window.open('https://ipleak.net', '_blank');
  };

  // 11. UTILS & MODALS
  window.openServerSheet = function() {
    if (serverSheet) {
      serverSheet.classList.add('show');
      fetchServers();
    }
  };

  window.closeServerSheet = function() {
    if (serverSheet) serverSheet.classList.remove('show');
  };

  async function apiRequest(endpoint, method = 'GET', body = null) {
    const headers = {
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    };

    if (state.token) {
      headers['Authorization'] = `Bearer ${state.token}`;
    }

    const config = { method, headers };
    if (body) {
      config.body = JSON.stringify(body);
    }

    const response = await fetch(endpoint, config);
    if (!response.ok) {
      const err = await response.json().catch(() => ({}));
      throw new Error(err.message || 'API Request Failed');
    }

    return await response.json();
  }

  function showToast(message) {
    let toast = document.getElementById('appToast');
    if (!toast) {
      toast = document.createElement('div');
      toast.id = 'appToast';
      toast.className = 'toast-msg';
      document.body.appendChild(toast);
    }
    toast.textContent = message;
    toast.style.opacity = '1';
    setTimeout(() => {
      toast.style.opacity = '0';
    }, 2800);
  }

  switchTab('home');
});
