<template>
  <div>
    <div class="hidden md:block mb-8">
      <h1 class="text-3xl font-bold text-white mb-2">Network</h1>
      <p class="text-white/70">Manage your network infrastructure and Web3 services</p>
      <p class="text-sm text-white/60 mt-2">{{ connectedNodes }} connected nodes</p>
    </div>

    <!-- Disk Space Warning Banner -->
    <div
      v-if="diskWarning"
      class="mb-6 p-4 rounded-xl border flex items-center justify-between"
      :class="diskWarning.level === 'critical'
        ? 'bg-red-500/10 border-red-500/30'
        : 'bg-yellow-500/10 border-yellow-500/30'"
    >
      <div class="flex items-center gap-3">
        <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 shrink-0" :class="diskWarning.level === 'critical' ? 'text-red-400' : 'text-yellow-400'" fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4.5c-.77-.833-2.694-.833-3.464 0L3.34 16.5c-.77.833.192 2.5 1.732 2.5z" />
        </svg>
        <div>
          <p class="text-sm font-medium" :class="diskWarning.level === 'critical' ? 'text-red-300' : 'text-yellow-300'">
            {{ diskWarning.level === 'critical' ? 'Disk Space Critical' : 'Disk Space Warning' }}
          </p>
          <p class="text-xs text-white/60">
            {{ diskWarning.used_percent.toFixed(1) }}% used — {{ formatBytes(diskWarning.free_bytes) }} remaining
          </p>
        </div>
      </div>
      <button
        class="glass-button glass-button-sm px-3 py-1.5 text-xs font-medium rounded"
        :disabled="diskCleaning"
        @click="runDiskCleanup"
      >
        {{ diskCleaning ? 'Cleaning...' : 'Clean Up' }}
      </button>
    </div>

    <!-- Quick Actions Container -->
    <div class="glass-card p-6 mb-6">
      <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        <!-- Service Status -->
        <div data-controller-container tabindex="0" class="flex flex-col gap-3 p-4 bg-white/5 rounded-lg min-w-0">
          <div class="flex items-center gap-3 min-w-0">
            <div class="relative shrink-0">
              <div class="w-3 h-3 rounded-full" :class="servicesRunning ? 'bg-green-400' : 'bg-red-400'"></div>
              <div v-if="servicesRunning" class="absolute inset-0 w-3 h-3 rounded-full bg-green-400 animate-ping opacity-75"></div>
            </div>
            <div class="min-w-0">
              <p class="text-sm font-medium text-white">Services</p>
              <p class="text-xs text-white/60">{{ servicesRunning ? 'All Running' : 'Some Stopped' }}</p>
            </div>
          </div>
          <button
            @click="restartServices"
            class="w-fit px-3 py-1.5 glass-button glass-button-sm rounded text-xs font-medium text-white/90 hover:text-white transition-colors disabled:opacity-50"
            :disabled="restarting"
          >
            {{ restarting ? 'Restarting...' : 'Restart' }}
          </button>
        </div>

        <!-- Connectivity Status -->
        <div data-controller-container tabindex="0" class="flex flex-col gap-3 p-4 bg-white/5 rounded-lg min-w-0">
          <div class="flex items-center gap-3 min-w-0">
            <div class="relative shrink-0">
              <div class="w-3 h-3 rounded-full" :class="connectivityStatus === 'connected' ? 'bg-green-400' : connectivityStatus === 'checking' ? 'bg-yellow-400' : 'bg-red-400'"></div>
              <div v-if="connectivityStatus === 'connected'" class="absolute inset-0 w-3 h-3 rounded-full bg-green-400 animate-ping opacity-75"></div>
            </div>
            <div class="min-w-0">
              <p class="text-sm font-medium text-white">Connectivity</p>
              <p class="text-xs text-white/60 capitalize">{{ connectivityStatus }}</p>
            </div>
          </div>
          <button
            @click="checkConnectivity"
            class="w-fit px-3 py-1.5 glass-button glass-button-sm rounded text-xs font-medium text-white/90 hover:text-white transition-colors disabled:opacity-50"
            :disabled="checkingConnectivity"
          >
            {{ checkingConnectivity ? 'Checking...' : 'Check' }}
          </button>
        </div>

        <!-- Auto-Sync Toggle -->
        <div data-controller-container tabindex="0" class="flex flex-col gap-3 p-4 bg-white/5 rounded-lg min-w-0">
          <div class="flex items-center gap-3 min-w-0">
            <svg class="w-5 h-5 text-white/60 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8.684 13.342C8.886 12.938 9 12.482 9 12c0-.482-.114-.938-.316-1.342m0 2.684a3 3 0 110-2.684m0 2.684l6.632 3.316m-6.632-6l6.632-3.316m0 0a3 3 0 105.367-2.684 3 3 0 00-5.367 2.684zm0 9.316a3 3 0 105.368 2.684 3 3 0 00-5.368-2.684z" />
            </svg>
            <div class="min-w-0">
              <p class="text-sm font-medium text-white">Auto-Sync</p>
              <p class="text-xs text-white/60">{{ autoSyncEnabled ? 'Enabled' : 'Disabled' }}</p>
            </div>
          </div>
          <button
            @click="toggleAutoSync"
            class="relative inline-flex h-6 w-11 items-center rounded-full transition-colors self-start"
            :class="autoSyncEnabled ? 'bg-green-500' : 'bg-white/20'"
          >
            <span
              class="inline-block h-4 w-4 transform rounded-full bg-white transition-transform"
              :class="autoSyncEnabled ? 'translate-x-6' : 'translate-x-1'"
            />
          </button>
        </div>

        <!-- Logs & Diagnostics -->
        <div data-controller-container tabindex="0" class="flex flex-col gap-3 p-4 bg-white/5 rounded-lg min-w-0">
          <div class="flex items-center gap-3 min-w-0">
            <svg class="w-5 h-5 text-white/60 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
            </svg>
            <div class="min-w-0">
              <p class="text-sm font-medium text-white">Logs</p>
              <p class="text-xs text-white/60">{{ logCount > 0 ? `${logCount} new` : 'No new logs' }}</p>
            </div>
          </div>
          <button
            @click="viewLogs"
            class="w-fit px-3 py-1.5 glass-button glass-button-sm rounded text-xs font-medium text-white/90 hover:text-white transition-colors"
          >
            View
          </button>
        </div>
      </div>
    </div>

    <!-- Overview Cards -->
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-8">
      <!-- Local Network Card -->
      <div data-controller-container tabindex="0" class="glass-card p-6 flex flex-col h-full min-h-0">
        <div class="flex items-start gap-4 mb-4 shrink-0">
          <div class="flex-shrink-0 w-12 h-12 rounded-lg bg-white/10 flex items-center justify-center">
            <svg class="w-6 h-6 text-white/80" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8.111 16.404a5.5 5.5 0 017.778 0M12 20h.01m-7.08-7.071c3.904-3.905 10.236-3.905 14.141 0M1.394 9.393c5.857-5.857 15.355-5.857 21.213 0" />
            </svg>
          </div>
          <div class="flex-1">
            <h2 class="text-xl font-semibold text-white mb-2">Local Network</h2>
            <p class="text-white/70 text-sm mb-4">OpenWRT-integrated router and network management</p>
          </div>
        </div>

        <div class="space-y-3 flex-1 min-h-0">
          <!-- Skeleton loading -->
          <template v-if="networkLoading">
            <div v-for="i in 4" :key="i" class="flex items-center justify-between p-3 bg-white/5 rounded-lg animate-pulse">
              <div class="flex items-center gap-3">
                <div class="w-5 h-5 bg-white/10 rounded"></div>
                <div class="w-24 h-4 bg-white/10 rounded"></div>
              </div>
              <div class="w-16 h-4 bg-white/10 rounded"></div>
            </div>
          </template>

          <template v-else>
            <div class="flex items-center justify-between p-3 bg-white/5 rounded-lg">
              <div class="flex items-center gap-3">
                <svg class="w-5 h-5 text-white/60" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z" />
                </svg>
                <span class="text-white/80 text-sm">Firewall Active</span>
              </div>
              <span class="text-green-400 text-sm font-medium">Protected</span>
            </div>

            <div class="flex items-center justify-between p-3 bg-white/5 rounded-lg">
              <div class="flex items-center gap-3">
                <svg class="w-5 h-5 text-white/60" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
                </svg>
                <span class="text-white/80 text-sm">WiFi Networks</span>
              </div>
              <span class="text-white/60 text-sm">{{ networkData.wifiCount }}</span>
            </div>

            <div class="flex items-center justify-between p-3 bg-white/5 rounded-lg">
              <div class="flex items-center gap-3">
                <svg class="w-5 h-5 text-white/60" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 12a9 9 0 01-9 9m9-9a9 9 0 00-9-9m9 9H3m9 9a9 9 0 01-9-9m9 9c1.657 0 3-4.03 3-9s-1.343-9-3-9m0 18c-1.657 0-3-4.03-3-9s1.343-9 3-9m-9 9a9 9 0 019-9" />
                </svg>
                <span class="text-white/80 text-sm">Connectivity</span>
              </div>
              <span class="text-sm" :class="networkData.torConnected ? 'text-green-400' : 'text-white/60'">{{ networkData.torConnected ? 'Tor Connected' : 'N/A' }}</span>
            </div>

            <div class="flex items-center justify-between p-3 bg-white/5 rounded-lg">
              <div class="flex items-center gap-3">
                <svg class="w-5 h-5 text-white/60" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z" />
                </svg>
                <span class="text-white/80 text-sm">Port Forwarding</span>
              </div>
              <span class="text-white/60 text-sm">{{ networkData.forwardCount }}</span>
            </div>

            <div class="flex items-center justify-between p-3 bg-white/5 rounded-lg">
              <div class="flex items-center gap-3">
                <svg class="w-5 h-5 text-white/60" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
                </svg>
                <span class="text-white/80 text-sm">VPN</span>
              </div>
              <span class="text-sm" :class="networkData.vpnConnected ? 'text-green-400' : 'text-white/40'">
                {{ networkData.vpnConnected ? `${networkData.vpnProvider} (${networkData.vpnIp})` : 'Not Connected' }}
              </span>
            </div>

            <button class="w-full flex items-center justify-between p-3 bg-white/5 rounded-lg hover:bg-white/10 transition-colors text-left" @click="showDnsModal = true">
              <div class="flex items-center gap-3">
                <svg class="w-5 h-5 text-white/60" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 12a9 9 0 01-9 9m9-9a9 9 0 00-9-9m9 9H3m9 9a9 9 0 01-9-9m9 9c1.657 0 3-4.03 3-9s-1.343-9-3-9m0 18c-1.657 0-3-4.03-3-9s1.343-9 3-9" />
                </svg>
                <span class="text-white/80 text-sm">DNS</span>
              </div>
              <span class="text-sm" :class="networkData.dnsProvider !== 'system' ? 'text-green-400' : 'text-white/60'">
                {{ dnsDisplayLabel }}
              </span>
            </button>
          </template>
        </div>

        <button disabled title="Coming Soon" class="mt-auto pt-4 w-full px-4 py-2 glass-button rounded-lg text-sm font-medium opacity-50 cursor-not-allowed shrink-0">
          Manage Local Network
        </button>
      </div>

      <!-- Web3 Card -->
      <div data-controller-container tabindex="0" class="glass-card p-6 flex flex-col h-full min-h-0">
        <div class="flex items-start gap-4 mb-4 shrink-0">
          <div class="flex-shrink-0 w-12 h-12 rounded-lg bg-white/10 flex items-center justify-center">
            <svg class="w-6 h-6 text-white/80" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 12a9 9 0 01-9 9m9-9a9 9 0 00-9-9m9 9H3m9 9a9 9 0 01-9-9m9 9c1.657 0 3-4.03 3-9s-1.343-9-3-9m0 18c-1.657 0-3-4.03-3-9s1.343-9 3-9m-9 9a9 9 0 019-9" />
            </svg>
          </div>
          <div class="flex-1">
            <h2 class="text-xl font-semibold text-white mb-2">Web3</h2>
            <p class="text-white/70 text-sm mb-4">Decentralized web hosting and services</p>
          </div>
        </div>

        <div class="space-y-3 flex-1 min-h-0">
          <div class="flex items-center justify-between p-3 bg-white/5 rounded-lg">
            <div class="flex items-center gap-3">
              <svg class="w-5 h-5 text-white/60" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 12a9 9 0 01-9 9m9-9a9 9 0 00-9-9m9 9H3m9 9a9 9 0 01-9-9m9 9c1.657 0 3-4.03 3-9s-1.343-9-3-9m0 18c-1.657 0-3-4.03-3-9s1.343-9 3-9m-9 9a9 9 0 019-9" />
              </svg>
              <span class="text-white/80 text-sm">Hosted Websites</span>
            </div>
            <span class="text-white/40 text-xs px-2 py-0.5 bg-white/5 rounded-full">Coming Soon</span>
          </div>

          <div class="flex items-center justify-between p-3 bg-white/5 rounded-lg">
            <div class="flex items-center gap-3">
              <svg class="w-5 h-5 text-white/60" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z" />
              </svg>
              <span class="text-white/80 text-sm">SSL Certificates</span>
            </div>
            <span class="text-white/40 text-xs px-2 py-0.5 bg-white/5 rounded-full">Coming Soon</span>
          </div>

          <div class="flex items-center justify-between p-3 bg-white/5 rounded-lg">
            <div class="flex items-center gap-3">
              <svg class="w-5 h-5 text-white/60" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12" />
              </svg>
              <span class="text-white/80 text-sm">IPFS Storage</span>
            </div>
            <span class="text-white/40 text-xs px-2 py-0.5 bg-white/5 rounded-full">Coming Soon</span>
          </div>

          <div class="flex items-center justify-between p-3 bg-white/5 rounded-lg">
            <div class="flex items-center gap-3">
              <svg class="w-5 h-5 text-white/60" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 20l-5.447-2.724A1 1 0 013 16.382V5.618a1 1 0 011.447-.894L9 7m0 13l6-3m-6 3V7m6 10l4.553 2.276A1 1 0 0021 18.382V7.618a1 1 0 00-.553-.894L15 4m0 13V4m0 0L9 7" />
      </svg>
              <span class="text-white/80 text-sm">ENS Domains</span>
            </div>
            <span class="text-white/40 text-xs px-2 py-0.5 bg-white/5 rounded-full">Coming Soon</span>
          </div>
        </div>

        <button disabled title="Coming Soon" class="mt-auto pt-4 w-full px-4 py-2 glass-button rounded-lg text-sm font-medium opacity-50 cursor-not-allowed shrink-0">
          Manage Web3 Services
        </button>
      </div>
    </div>

    <!-- Network Interfaces -->
    <div class="glass-card p-6 mb-6">
      <div class="flex items-center justify-between mb-4">
        <div>
          <h2 class="text-xl font-semibold text-white mb-1">Network Interfaces</h2>
          <p class="text-sm text-white/60">Detected hardware and virtual interfaces</p>
        </div>
        <button
          v-if="wifiAvailable"
          @click="showWifiModal = true"
          class="px-3 py-1.5 glass-button rounded text-xs font-medium text-white/90 hover:text-white transition-colors"
        >
          Scan WiFi
        </button>
      </div>

      <template v-if="interfacesLoading">
        <div class="space-y-3">
          <div v-for="i in 3" :key="i" class="p-3 bg-white/5 rounded-lg animate-pulse h-14"></div>
        </div>
      </template>
      <template v-else>
        <div class="space-y-3">
          <div
            v-for="iface in physicalInterfaces"
            :key="iface.name"
            class="flex items-center justify-between p-3 bg-white/5 rounded-lg"
          >
            <div class="flex items-center gap-3">
              <div class="w-2 h-2 rounded-full" :class="iface.state === 'up' ? 'bg-green-400' : 'bg-white/30'"></div>
              <div>
                <p class="text-sm font-medium text-white">{{ iface.name }}</p>
                <p class="text-xs text-white/50">{{ iface.type === 'wifi' ? 'WiFi' : 'Ethernet' }} &middot; {{ iface.mac }}</p>
              </div>
            </div>
            <div class="text-right">
              <p v-if="iface.ipv4.length > 0" class="text-sm text-white/80">{{ iface.ipv4[0] }}</p>
              <p v-else class="text-sm text-white/40">No IP</p>
            </div>
          </div>
          <p v-if="physicalInterfaces.length === 0" class="text-sm text-white/50 text-center py-4">No physical interfaces detected</p>
        </div>
      </template>
    </div>

    <!-- Tor Services -->
    <div class="glass-card px-6 py-6 mb-6">
      <div class="flex items-center justify-between mb-4">
        <div>
          <h2 class="text-xl font-semibold text-white/96">Tor Services</h2>
          <p class="text-sm text-white/60 mt-1">Manage hidden service addresses for your node and apps</p>
        </div>
        <button @click="loadTorServices" class="glass-button px-4 py-2 rounded-lg text-sm flex items-center gap-2">
          <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
          </svg>
          Refresh
        </button>
      </div>
      <div v-if="torServicesLoading && torServices.length === 0" class="text-sm text-white/40 py-4 text-center">Loading Tor services...</div>
      <div v-else-if="torServices.length === 0" class="text-sm text-white/40 py-4 text-center">No Tor services configured</div>
      <div v-else class="space-y-2">
        <div v-for="svc in torServices" :key="svc.name" class="bg-black/20 rounded-xl border border-white/10 p-3 flex items-center justify-between gap-3">
          <div class="flex-1 min-w-0">
            <p class="text-white text-sm font-medium">{{ svc.name }}</p>
            <p v-if="svc.onion_address" class="text-amber-300/80 text-xs font-mono truncate cursor-pointer" :title="svc.onion_address" @click="copyTorAddress(svc.onion_address)">{{ svc.onion_address }}</p>
            <p v-else class="text-white/30 text-xs">No .onion address</p>
          </div>
          <div class="flex items-center gap-2 shrink-0">
            <button
              v-if="svc.name === 'archipelago'"
              @click="rotateNodeAddress"
              :disabled="torRotating"
              class="glass-button px-3 py-1.5 rounded-lg text-xs"
            >
              {{ torRotating ? 'Rotating...' : 'Rotate' }}
            </button>
            <label class="tor-toggle-label">
              <input
                type="checkbox"
                :checked="svc.enabled"
                @change="toggleTorApp(svc.name, !svc.enabled)"
                class="tor-toggle-input"
              />
              <span class="tor-toggle-slider"></span>
            </label>
          </div>
        </div>
      </div>
    </div>

    <!-- WiFi Scan Modal -->
    <div v-if="showWifiModal" class="fixed inset-0 bg-black/60 backdrop-blur-sm z-50 flex items-center justify-center p-4" @click.self="showWifiModal = false">
      <div class="glass-card p-6 w-full max-w-md">
        <div class="flex items-center justify-between mb-4">
          <h3 class="text-lg font-semibold text-white">WiFi Networks</h3>
          <button @click="showWifiModal = false" class="text-white/40 hover:text-white transition-colors">
            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
            </svg>
          </button>
        </div>
        <template v-if="wifiScanning">
          <div class="space-y-3">
            <div v-for="i in 4" :key="i" class="p-3 bg-white/5 rounded-lg animate-pulse h-12"></div>
          </div>
        </template>
        <template v-else-if="wifiNetworks.length > 0">
          <div class="space-y-2 max-h-72 overflow-y-auto">
            <button
              v-for="net in wifiNetworks"
              :key="net.ssid"
              class="w-full flex items-center justify-between p-3 bg-white/5 rounded-lg hover:bg-white/10 transition-colors text-left"
              @click="selectWifi(net.ssid)"
            >
              <div>
                <p class="text-sm font-medium text-white">{{ net.ssid }}</p>
                <p class="text-xs text-white/50">{{ net.security || 'Open' }}</p>
              </div>
              <div class="flex items-center gap-2">
                <div class="flex gap-0.5">
                  <div v-for="bar in 4" :key="bar" class="w-1 rounded-full" :class="bar <= Math.ceil(net.signal / 25) ? 'bg-white/80' : 'bg-white/20'" :style="{ height: (bar * 3 + 4) + 'px' }"></div>
                </div>
                <span class="text-xs text-white/50">{{ net.signal }}%</span>
              </div>
            </button>
          </div>
        </template>
        <template v-else>
          <p class="text-sm text-white/50 text-center py-8">No networks found</p>
        </template>

        <!-- WiFi password prompt -->
        <div v-if="wifiConnecting" class="mt-4 pt-4 border-t border-white/10">
          <p class="text-sm text-white/80 mb-2">Connect to <span class="font-medium text-white">{{ wifiSelectedSsid }}</span></p>
          <input
            v-model="wifiPassword"
            type="password"
            placeholder="WiFi password"
            class="w-full px-3 py-2 bg-white/5 border border-white/10 rounded-lg text-white text-sm placeholder-white/30 focus:outline-none focus:border-white/30 mb-3"
            @keyup.enter="connectToWifi"
          />
          <p v-if="wifiError" class="text-sm text-red-400 mb-3">{{ wifiError }}</p>
          <div class="flex gap-2">
            <button @click="wifiConnecting = false; wifiPassword = ''; wifiError = ''" :disabled="wifiSubmitting" class="flex-1 px-3 py-2 glass-button rounded-lg text-sm">Cancel</button>
            <button @click="connectToWifi" class="flex-1 px-3 py-2 glass-button rounded-lg text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed" :disabled="!wifiPassword || wifiSubmitting">{{ wifiSubmitting ? 'Connecting...' : 'Connect' }}</button>
          </div>
        </div>
      </div>
    </div>

    <!-- DNS Configuration Modal -->
    <div v-if="showDnsModal" class="fixed inset-0 bg-black/60 backdrop-blur-sm z-50 flex items-center justify-center p-4" @click.self="showDnsModal = false">
      <div class="glass-card p-6 w-full max-w-md">
        <div class="flex items-center justify-between mb-4">
          <h3 class="text-lg font-semibold text-white">DNS Configuration</h3>
          <button @click="showDnsModal = false" class="text-white/40 hover:text-white transition-colors">
            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
            </svg>
          </button>
        </div>

        <p class="text-sm text-white/60 mb-4">Choose a DNS provider. Providers with DoH encrypt your DNS queries.</p>

        <div class="space-y-2 mb-4">
          <button
            v-for="opt in dnsProviderOptions"
            :key="opt.value"
            class="w-full flex items-center justify-between p-3 rounded-lg transition-colors text-left"
            :class="dnsSelectedProvider === opt.value ? 'bg-white/15 border border-white/20' : 'bg-white/5 border border-transparent hover:bg-white/10'"
            @click="dnsSelectedProvider = opt.value; dnsCustomServers = ''"
          >
            <div>
              <p class="text-sm font-medium text-white">{{ opt.label }}</p>
              <p class="text-xs text-white/50">{{ opt.description }}</p>
            </div>
            <span v-if="opt.doh" class="text-xs px-2 py-0.5 rounded-full bg-green-400/20 text-green-400">DoH</span>
          </button>
        </div>

        <!-- Custom servers input -->
        <div v-if="dnsSelectedProvider === 'custom'" class="mb-4">
          <label class="block text-sm text-white/70 mb-1">DNS Servers (comma-separated)</label>
          <input
            v-model="dnsCustomServers"
            type="text"
            placeholder="1.1.1.1, 8.8.8.8"
            class="w-full px-3 py-2 bg-white/5 border border-white/10 rounded-lg text-white text-sm placeholder-white/30 focus:outline-none focus:border-white/30"
          />
        </div>

        <!-- Current servers info -->
        <div v-if="networkData.dnsServers.length > 0" class="mb-4 p-3 bg-white/5 rounded-lg">
          <p class="text-xs text-white/50 mb-1">Current resolv.conf servers</p>
          <p class="text-sm text-white/80">{{ networkData.dnsServers.join(', ') }}</p>
        </div>

        <p v-if="dnsError" class="text-sm text-red-400 mb-3">{{ dnsError }}</p>

        <div class="flex gap-2">
          <button @click="showDnsModal = false; dnsError = ''" class="flex-1 px-3 py-2 glass-button rounded-lg text-sm">Cancel</button>
          <button
            @click="applyDnsConfig"
            class="flex-1 px-3 py-2 glass-button rounded-lg text-sm font-medium"
            :disabled="dnsApplying || (dnsSelectedProvider === 'custom' && !dnsCustomServers.trim())"
          >
            {{ dnsApplying ? 'Applying...' : 'Apply' }}
          </button>
        </div>
      </div>
    </div>

    <!-- Logs info toast -->
    <Transition name="fade">
      <div v-if="logsToast" class="fixed bottom-20 left-1/2 -translate-x-1/2 z-50 max-w-md w-full px-4">
        <div class="bg-white/10 border border-white/20 backdrop-blur-sm rounded-lg px-4 py-3 text-white/80 text-sm flex items-center justify-between gap-3">
          <span>{{ logsToast }}</span>
          <button @click="logsToast = ''" class="text-white/50 hover:text-white shrink-0">&times;</button>
        </div>
      </div>
    </Transition>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { rpcClient } from '@/api/rpc-client'

// Connected nodes
const connectedNodes = ref(0)

// Service status
const servicesRunning = ref(true)
const restarting = ref(false)

// Connectivity status: 'connected' | 'disconnected' | 'checking'
const connectivityStatus = ref<'connected' | 'disconnected' | 'checking'>('connected')
const checkingConnectivity = ref(false)

// Auto-sync toggle
const autoSyncEnabled = ref(true)

// Logs
const logCount = ref(0)

// Network data
const networkLoading = ref(true)
const networkData = ref({
  wifiCount: 'N/A',
  torConnected: false,
  forwardCount: 'N/A',
  vpnConnected: false,
  vpnProvider: '',
  vpnIp: '',
  vpnHostname: '',
  vpnPeers: 0,
  dnsProvider: 'system',
  dnsServers: [] as string[],
  dnsDoH: false,
})

async function loadNetworkData() {
  networkLoading.value = true
  try {
    const [diagRes, fwdRes, vpnRes, dnsRes] = await Promise.allSettled([
      rpcClient.call<{ wan_ip: string | null; nat_type: string; upnp_available: boolean; tor_connected: boolean; wifi_count?: number }>({ method: 'network.diagnostics' }),
      rpcClient.call<{ forwards: unknown[] }>({ method: 'router.list-forwards' }),
      rpcClient.vpnStatus(),
      rpcClient.dnsStatus(),
    ])

    if (diagRes.status === 'fulfilled') {
      networkData.value.torConnected = diagRes.value.tor_connected
      networkData.value.wifiCount = diagRes.value.wifi_count !== undefined
        ? `${diagRes.value.wifi_count} configured`
        : 'N/A'
    }

    if (fwdRes.status === 'fulfilled') {
      const count = fwdRes.value.forwards?.length ?? 0
      networkData.value.forwardCount = `${count} rule${count !== 1 ? 's' : ''}`
    }

    if (vpnRes.status === 'fulfilled') {
      networkData.value.vpnConnected = vpnRes.value.connected
      networkData.value.vpnProvider = vpnRes.value.provider ?? ''
      networkData.value.vpnIp = vpnRes.value.ip_address ?? ''
      networkData.value.vpnHostname = vpnRes.value.hostname ?? ''
      networkData.value.vpnPeers = vpnRes.value.peers_connected
    }

    if (dnsRes.status === 'fulfilled') {
      networkData.value.dnsProvider = dnsRes.value.provider
      networkData.value.dnsServers = dnsRes.value.resolv_conf_servers ?? []
      networkData.value.dnsDoH = dnsRes.value.doh_enabled
    }
  } catch (e) {
    if (import.meta.env.DEV) console.warn('Keep N/A defaults on failure', e)
  } finally {
    networkLoading.value = false
  }
}

// Load peer count
async function loadPeerCount() {
  try {
    const res = await rpcClient.listPeers()
    connectedNodes.value = res.peers?.length ?? 0
  } catch {
    connectedNodes.value = 0
  }
}

// Network interfaces
interface NetworkInterface {
  name: string
  type: string
  state: string
  mac: string
  ipv4: string[]
}

interface WifiNetwork {
  ssid: string
  signal: number
  security: string
}

const interfacesLoading = ref(true)
const allInterfaces = ref<NetworkInterface[]>([])
const physicalInterfaces = computed(() =>
  allInterfaces.value.filter(i => i.type === 'ethernet' || i.type === 'wifi')
)
const wifiAvailable = computed(() =>
  allInterfaces.value.some(i => i.type === 'wifi')
)

const showWifiModal = ref(false)
const wifiScanning = ref(false)
const wifiNetworks = ref<WifiNetwork[]>([])
const wifiConnecting = ref(false)
const wifiSubmitting = ref(false)
const wifiSelectedSsid = ref('')
const wifiPassword = ref('')
const wifiError = ref('')

// DNS configuration
const showDnsModal = ref(false)
const dnsSelectedProvider = ref('system')
const dnsCustomServers = ref('')
const dnsApplying = ref(false)
const dnsError = ref('')

const dnsProviderOptions = [
  { value: 'system', label: 'System Default', description: 'DHCP-assigned DNS servers', doh: false },
  { value: 'cloudflare', label: 'Cloudflare', description: '1.1.1.1 / 1.0.0.1', doh: true },
  { value: 'google', label: 'Google', description: '8.8.8.8 / 8.8.4.4', doh: true },
  { value: 'quad9', label: 'Quad9', description: '9.9.9.9 / 149.112.112.112', doh: true },
  { value: 'mullvad', label: 'Mullvad', description: '194.242.2.2 (no logging)', doh: true },
  { value: 'custom', label: 'Custom', description: 'Enter your own DNS servers', doh: false },
]

type DnsProviderValue = 'system' | 'cloudflare' | 'google' | 'quad9' | 'mullvad' | 'custom'

const dnsDisplayLabel = computed(() => {
  const p = networkData.value.dnsProvider
  const opt = dnsProviderOptions.find(o => o.value === p)
  if (opt && p !== 'system') {
    return `${opt.label}${networkData.value.dnsDoH ? ' (DoH)' : ''}`
  }
  if (networkData.value.dnsServers.length > 0) {
    return networkData.value.dnsServers.slice(0, 2).join(', ')
  }
  return 'System Default'
})

async function applyDnsConfig() {
  dnsApplying.value = true
  dnsError.value = ''
  try {
    const provider = dnsSelectedProvider.value as DnsProviderValue
    const params: { provider: DnsProviderValue; servers?: string[] } = { provider }
    if (provider === 'custom') {
      params.servers = dnsCustomServers.value
        .split(',')
        .map(s => s.trim())
        .filter(s => s.length > 0)
    }
    const res = await rpcClient.configureDns(params)
    networkData.value.dnsProvider = res.provider
    networkData.value.dnsServers = res.servers
    networkData.value.dnsDoH = res.doh_enabled
    showDnsModal.value = false
  } catch (e) {
    dnsError.value = e instanceof Error ? e.message : 'DNS configuration failed. Please try again.'
    if (import.meta.env.DEV) console.warn('DNS configuration failed', e)
  } finally {
    dnsApplying.value = false
  }
}

async function loadInterfaces() {
  interfacesLoading.value = true
  try {
    const res = await rpcClient.call<{ interfaces: NetworkInterface[] }>({ method: 'network.list-interfaces' })
    allInterfaces.value = res.interfaces
  } catch {
    allInterfaces.value = []
  } finally {
    interfacesLoading.value = false
  }
}

async function scanWifi() {
  wifiScanning.value = true
  wifiNetworks.value = []
  try {
    const res = await rpcClient.call<{ networks: WifiNetwork[] }>({ method: 'network.scan-wifi' })
    wifiNetworks.value = res.networks
  } catch {
    wifiNetworks.value = []
  } finally {
    wifiScanning.value = false
  }
}

function selectWifi(ssid: string) {
  wifiSelectedSsid.value = ssid
  wifiPassword.value = ''
  wifiConnecting.value = true
}

async function connectToWifi() {
  if (!wifiPassword.value || !wifiSelectedSsid.value) return
  wifiError.value = ''
  wifiSubmitting.value = true
  try {
    await rpcClient.call({ method: 'network.configure-wifi', params: { ssid: wifiSelectedSsid.value, password: wifiPassword.value } })
    showWifiModal.value = false
    wifiConnecting.value = false
    wifiPassword.value = ''
    logsToast.value = 'WiFi connected successfully'
    setTimeout(() => { logsToast.value = '' }, 4000)
    loadInterfaces()
  } catch (e) {
    wifiError.value = e instanceof Error ? e.message : 'WiFi connection failed. Check password and try again.'
    if (import.meta.env.DEV) console.warn('WiFi connection failed', e)
  } finally {
    wifiSubmitting.value = false
  }
}

// Disk space monitoring
const diskWarning = ref<{
  level: 'warning' | 'critical'
  used_percent: number
  free_bytes: number
} | null>(null)
const diskCleaning = ref(false)

async function loadDiskStatus() {
  try {
    const res = await rpcClient.diskStatus()
    if (res.level === 'warning' || res.level === 'critical') {
      diskWarning.value = {
        level: res.level,
        used_percent: res.used_percent,
        free_bytes: res.free_bytes,
      }
    } else {
      diskWarning.value = null
    }
  } catch {
    // Disk status is non-critical
  }
}

async function runDiskCleanup() {
  diskCleaning.value = true
  try {
    await rpcClient.diskCleanup()
    await loadDiskStatus()
    logsToast.value = 'Disk cleanup completed'
    setTimeout(() => { logsToast.value = '' }, 4000)
  } catch (e) {
    logsToast.value = `Disk cleanup failed: ${e instanceof Error ? e.message : 'Unknown error'}`
    setTimeout(() => { logsToast.value = '' }, 6000)
    if (import.meta.env.DEV) console.warn('Disk cleanup failed', e)
  } finally {
    diskCleaning.value = false
  }
}

function formatBytes(bytes: number): string {
  const gb = 1024 * 1024 * 1024
  const mb = 1024 * 1024
  if (bytes >= gb) return `${(bytes / gb).toFixed(1)} GB`
  if (bytes >= mb) return `${(bytes / mb).toFixed(0)} MB`
  return `${(bytes / 1024).toFixed(0)} KB`
}

// --- Tor Services ---
interface TorServiceInfo {
  name: string
  local_port: number
  onion_address: string | null
  enabled: boolean
}

const torServices = ref<TorServiceInfo[]>([])
const torServicesLoading = ref(false)

async function loadTorServices() {
  torServicesLoading.value = true
  try {
    const res = await rpcClient.call<{ services: TorServiceInfo[] }>({ method: 'tor.list-services' })
    torServices.value = res.services || []
  } catch {
    torServices.value = []
  } finally {
    torServicesLoading.value = false
  }
}

const torRotating = ref(false)

function copyTorAddress(address: string) {
  navigator.clipboard.writeText(address)
  logsToast.value = 'Onion address copied to clipboard'
  setTimeout(() => { logsToast.value = '' }, 3000)
}

async function toggleTorApp(appId: string, enabled: boolean) {
  try {
    await rpcClient.call({ method: 'tor.toggle-service', params: { name: appId, enabled } })
    await loadTorServices()
  } catch (e) {
    if (import.meta.env.DEV) console.warn('Failed to toggle Tor app:', e)
  }
}

async function rotateNodeAddress() {
  torRotating.value = true
  try {
    await rpcClient.call({ method: 'tor.rotate-address', params: { name: 'archipelago' } })
    await loadTorServices()
  } catch (e) {
    if (import.meta.env.DEV) console.warn('Failed to rotate Tor address:', e)
  } finally {
    torRotating.value = false
  }
}

onMounted(() => {
  checkConnectivity()
  loadNetworkData()
  loadPeerCount()
  loadInterfaces()
  loadDiskStatus()
  loadTorServices()
})

watch(showWifiModal, (open) => {
  if (open) scanWifi()
})

watch(showDnsModal, (open) => {
  if (open) {
    dnsSelectedProvider.value = networkData.value.dnsProvider || 'system'
    dnsCustomServers.value = ''
    dnsError.value = ''
  }
})

async function restartServices() {
  restarting.value = true
  servicesRunning.value = false
  try {
    await rpcClient.restartServer()
    logsToast.value = 'Services restarting...'
    setTimeout(() => { logsToast.value = '' }, 4000)
  } catch (e) {
    logsToast.value = `Restart failed: ${e instanceof Error ? e.message : 'Unknown error'}`
    setTimeout(() => { logsToast.value = '' }, 6000)
    if (import.meta.env.DEV) console.warn('Restart RPC failed', e)
  }
  // Poll health to confirm recovery instead of assuming success
  const pollHealth = async (retries: number) => {
    for (let i = 0; i < retries; i++) {
      await new Promise(r => setTimeout(r, 2000))
      try {
        await rpcClient.call({ method: 'server.health', params: {} })
        servicesRunning.value = true
        restarting.value = false
        return
      } catch {
        // Still restarting
      }
    }
    restarting.value = false
    servicesRunning.value = false
    connectivityStatus.value = 'disconnected'
  }
  pollHealth(15)
}

async function checkConnectivity() {
  checkingConnectivity.value = true
  connectivityStatus.value = 'checking'
  try {
    await rpcClient.call({ method: 'server.health', params: {} })
    connectivityStatus.value = 'connected'
  } catch {
    connectivityStatus.value = 'disconnected'
  } finally {
    checkingConnectivity.value = false
  }
}

function toggleAutoSync() {
  autoSyncEnabled.value = !autoSyncEnabled.value
}

const logsToast = ref('')

function viewLogs() {
  logCount.value = 0
  logsToast.value = 'Server logs are available via SSH: journalctl -u archipelago -f'
  setTimeout(() => { logsToast.value = '' }, 6000)
}
</script>

