<script lang="ts">
  import { invalidateAll } from "$app/navigation";
  import LinkUnifiSiteModal from "../../../../components/LinkUnifiSiteModal.svelte";
  import {
    unifi as unifiApi,
    type UnifiSite,
    type UnifiSiteOverview,
    type UnifiDevice,
    type UnifiWifiNetwork,
    type UnifiNetwork,
    type UnifiWlanGroup,
    type UnifiApGroup,
    type UnifiAccessPoint,
    type UnifiSpeedProfile,
    type UnifiPPSK,
  } from "$lib/optima-api/modules/unifi";
  import type { PermissionMap } from "$lib/permissions";
  import { formatUptime } from "../types";

  export let companyId: string;
  export let unifiSites: UnifiSite[];
  export let accessToken: string | null;
  export let permissions: PermissionMap;
  export let isLinkUnifiOpen: boolean;

  // UniFi state
  let selectedUnifiSite: UnifiSite | null = null;
  let unifiSiteOverview: UnifiSiteOverview | null = null;
  let unifiSiteDevices: UnifiDevice[] = [];
  let unifiSiteWifi: UnifiWifiNetwork[] = [];
  let unifiSiteNetworks: UnifiNetwork[] = [];
  let unifiWlanGroups: UnifiWlanGroup[] = [];
  let unifiApGroups: UnifiApGroup[] = [];
  let unifiAccessPoints: UnifiAccessPoint[] = [];
  let unifiSpeedProfiles: UnifiSpeedProfile[] = [];
  let wifiPPSKs: UnifiPPSK[] = [];
  let isLoadingUnifiOverview = false;
  let isLoadingUnifiDevices = false;
  let isLoadingUnifiWifi = false;
  let isLoadingUnifiNetworks = false;
  let isLoadingSpeedProfiles = false;
  let isLoadingWlanGroups = false;
  let isLoadingApGroups = false;
  let isLoadingAccessPoints = false;
  let isLoadingPPSKs = false;
  let unifiManagementTab: "overview" | "devices" | "wifi" | "networks" =
    "overview";
  let isUnlinkingSite = false;
  let isUnifiSiteMenuOpen = false;
  let revealedWifiPassphrases: Record<string, boolean> = {};

  // WiFi split-view state
  let selectedWifi: UnifiWifiNetwork | null = null;
  let wifiEditState: Record<string, unknown> = {};
  let wifiOriginalState: Record<string, unknown> = {};
  let isWifiDirty = false;
  let isSavingWifi = false;
  let wifiSaveError: string | null = null;
  let wifiAdvancedMode: "auto" | "manual" = "auto";
  // PPSK add form state
  let ppskNewName = "";
  let ppskNewKey = "";
  let ppskNewVlanId = "";
  let ppskNewMac = "";
  let isAddingPPSK = false;
  // MAC filter add form state
  let macFilterNewMac = "";
  // Speed profile create modal state
  let showSpeedProfileModal = false;
  let speedProfileName = "";
  let speedProfileDown = "";
  let speedProfileUp = "";
  let isCreatingSpeedProfile = false;
  // PMF warning state
  let showPmfWarning = false;
  let pendingPmfValue = "";
  $: canEditWifi = permissions["unifi.site.wifi.update"] === true;

  // Card-level overview stats
  let siteOverviews: Record<string, UnifiSiteOverview> = {};
  let loadedOverviewIds = new Set<string>();
  let isLoadingCardStats = false;

  async function loadCardOverviews() {
    if (!accessToken || unifiSites.length === 0) return;
    const toLoad = unifiSites.filter((s) => !loadedOverviewIds.has(s.id));
    if (toLoad.length === 0) return;
    isLoadingCardStats = true;
    try {
      const results = await Promise.allSettled(
        toLoad.map((s) =>
          unifiApi
            .fetchSiteOverview(accessToken!, s.id)
            .then((r) => ({ id: s.id, data: r?.data })),
        ),
      );
      for (const r of results) {
        if (r.status === "fulfilled" && r.value?.data) {
          siteOverviews[r.value.id] = r.value.data;
          loadedOverviewIds.add(r.value.id);
        }
      }
      siteOverviews = siteOverviews;
    } catch (err) {
      console.error("Failed to load card overviews:", err);
    } finally {
      isLoadingCardStats = false;
    }
  }

  // Preload overviews when sites are visible
  $: if (!selectedUnifiSite && unifiSites.length > 0) {
    loadCardOverviews();
  }

  function getCardHealthStatus(
    siteId: string,
  ): "ok" | "warn" | "error" | "unknown" {
    const overview = siteOverviews[siteId];
    if (!overview?.health) return "unknown";
    const statuses = overview.health.map((h) => h.status);
    if (statuses.some((s) => s === "error" || s === "critical")) return "error";
    if (statuses.some((s) => s === "warn" || s === "warning")) return "warn";
    if (statuses.every((s) => s === "ok")) return "ok";
    return "unknown";
  }

  function getCardDeviceCount(siteId: string): number {
    const overview = siteOverviews[siteId];
    if (!overview?.health) return 0;
    return overview.health.reduce((sum, h) => sum + (h.numAdopted ?? 0), 0);
  }

  function getCardGatewayCount(siteId: string): number {
    const overview = siteOverviews[siteId];
    if (!overview?.health) return 0;
    return overview.health.reduce((sum, h) => sum + (h.numGateway ?? 0), 0);
  }

  async function selectUnifiSite(site: UnifiSite) {
    if (isWifiDirty) {
      const confirmed = confirm("You have unsaved WiFi changes. Discard them?");
      if (!confirmed) return;
    }
    selectedUnifiSite = site;
    unifiManagementTab = "overview";
    unifiSiteOverview = null;
    unifiSiteDevices = [];
    unifiSiteWifi = [];
    unifiSiteNetworks = [];
    revealedWifiPassphrases = {};
    selectedWifi = null;
    wifiEditState = {};
    wifiOriginalState = {};
    isWifiDirty = false;
    wifiSaveError = null;
    await loadUnifiOverview(site.id);
  }

  function backToUnifiSites() {
    if (isWifiDirty) {
      const confirmed = confirm("You have unsaved WiFi changes. Discard them?");
      if (!confirmed) return;
    }
    selectedUnifiSite = null;
    unifiSiteOverview = null;
    revealedWifiPassphrases = {};
    unifiSiteDevices = [];
    unifiSiteWifi = [];
    unifiSiteNetworks = [];
    selectedWifi = null;
    wifiEditState = {};
    wifiOriginalState = {};
    isWifiDirty = false;
    wifiSaveError = null;
  }

  async function loadUnifiOverview(siteId: string) {
    if (!accessToken) return;
    isLoadingUnifiOverview = true;
    try {
      const result = await unifiApi.fetchSiteOverview(accessToken, siteId);
      unifiSiteOverview = result?.data ?? null;
    } catch (err) {
      console.error("Failed to load UniFi overview:", err);
    } finally {
      isLoadingUnifiOverview = false;
    }
  }

  async function loadUnifiDevices(siteId: string) {
    if (!accessToken) return;
    isLoadingUnifiDevices = true;
    try {
      const result = await unifiApi.fetchSiteDevices(accessToken, siteId);
      unifiSiteDevices = result?.data ?? [];
    } catch (err) {
      console.error("Failed to load UniFi devices:", err);
    } finally {
      isLoadingUnifiDevices = false;
    }
  }

  async function loadUnifiWifi(siteId: string) {
    if (!accessToken) return;
    isLoadingUnifiWifi = true;
    try {
      const result = await unifiApi.fetchSiteWifi(accessToken, siteId);
      unifiSiteWifi = Array.isArray(result?.data)
        ? result.data
        : Array.isArray(result)
          ? result
          : [];
    } catch (err) {
      console.error("Failed to load UniFi WiFi:", err);
    } finally {
      isLoadingUnifiWifi = false;
    }
  }

  async function loadUnifiNetworks(siteId: string) {
    if (!accessToken) return;
    isLoadingUnifiNetworks = true;
    try {
      const result = await unifiApi.fetchSiteNetworks(accessToken, siteId);
      unifiSiteNetworks = result?.data ?? [];
    } catch (err) {
      console.error("Failed to load UniFi networks:", err);
    } finally {
      isLoadingUnifiNetworks = false;
    }
  }

  async function loadSpeedProfiles(siteId: string) {
    if (!accessToken) return;
    isLoadingSpeedProfiles = true;
    try {
      const result = await unifiApi.fetchSpeedProfiles(accessToken, siteId);
      unifiSpeedProfiles = result?.data ?? [];
    } catch (err) {
      console.error("Failed to load speed profiles:", err);
    } finally {
      isLoadingSpeedProfiles = false;
    }
  }

  async function loadWlanGroups(siteId: string) {
    if (!accessToken) return;
    isLoadingWlanGroups = true;
    try {
      const result = await unifiApi.fetchWlanGroups(accessToken, siteId);
      unifiWlanGroups = result?.data ?? [];
    } catch (err) {
      console.error("Failed to load WLAN groups:", err);
    } finally {
      isLoadingWlanGroups = false;
    }
  }

  async function loadApGroups(siteId: string) {
    if (!accessToken) return;
    isLoadingApGroups = true;
    try {
      const result = await unifiApi.fetchApGroups(accessToken, siteId);
      unifiApGroups = result?.data ?? [];
    } catch (err) {
      console.error("Failed to load AP groups:", err);
    } finally {
      isLoadingApGroups = false;
    }
  }

  async function loadAccessPoints(siteId: string) {
    if (!accessToken) return;
    isLoadingAccessPoints = true;
    try {
      const result = await unifiApi.fetchAccessPoints(accessToken, siteId);
      unifiAccessPoints = result?.data ?? [];
    } catch (err) {
      console.error("Failed to load access points:", err);
    } finally {
      isLoadingAccessPoints = false;
    }
  }

  async function loadPPSKs(siteId: string, wlanId: string) {
    if (!accessToken) return;
    isLoadingPPSKs = true;
    try {
      const result = await unifiApi.fetchPPSKs(accessToken, siteId, wlanId);
      wifiPPSKs = result?.data ?? [];
    } catch (err) {
      console.error("Failed to load PPSKs:", err);
    } finally {
      isLoadingPPSKs = false;
    }
  }

  async function addPPSK() {
    if (!accessToken || !selectedUnifiSite || !selectedWifi) return;
    if (!ppskNewName.trim() || !ppskNewKey.trim()) return;
    isAddingPPSK = true;
    try {
      const data: { key: string; name: string; mac?: string; vlanId?: number } =
        {
          key: ppskNewKey.trim(),
          name: ppskNewName.trim(),
        };
      if (ppskNewMac.trim()) data.mac = ppskNewMac.trim();
      if (ppskNewVlanId && Number(ppskNewVlanId) > 0)
        data.vlanId = Number(ppskNewVlanId);
      const result = await unifiApi.createPPSK(
        accessToken,
        selectedUnifiSite.id,
        selectedWifi.id,
        data,
      );
      wifiPPSKs = result?.data ?? [...wifiPPSKs, data as UnifiPPSK];
      ppskNewName = "";
      ppskNewKey = "";
      ppskNewMac = "";
      ppskNewVlanId = "";
    } catch (err) {
      console.error("Failed to add PPSK:", err);
      wifiSaveError = err instanceof Error ? err.message : "Failed to add PPSK";
    } finally {
      isAddingPPSK = false;
    }
  }

  async function addMacToFilterList() {
    const mac = macFilterNewMac.trim().toUpperCase();
    if (!mac) return;
    const current = Array.isArray(wifiEditState.macFilterList)
      ? (wifiEditState.macFilterList as string[])
      : [];
    if (!current.includes(mac)) {
      updateWifiField("macFilterList", [...current, mac]);
    }
    macFilterNewMac = "";
  }

  function removeMacFromFilterList(mac: string) {
    const current = Array.isArray(wifiEditState.macFilterList)
      ? (wifiEditState.macFilterList as string[])
      : [];
    updateWifiField(
      "macFilterList",
      current.filter((m) => m !== mac),
    );
  }

  async function createSpeedProfile() {
    if (!accessToken || !selectedUnifiSite || !speedProfileName.trim()) return;
    isCreatingSpeedProfile = true;
    try {
      const data: {
        name: string;
        downloadLimitKbps?: number;
        uploadLimitKbps?: number;
      } = {
        name: speedProfileName.trim(),
      };
      if (speedProfileDown && Number(speedProfileDown) > 0)
        data.downloadLimitKbps = Number(speedProfileDown);
      if (speedProfileUp && Number(speedProfileUp) > 0)
        data.uploadLimitKbps = Number(speedProfileUp);
      await unifiApi.createSpeedProfile(
        accessToken,
        selectedUnifiSite.id,
        data,
      );
      await loadSpeedProfiles(selectedUnifiSite.id);
      showSpeedProfileModal = false;
      speedProfileName = "";
      speedProfileDown = "";
      speedProfileUp = "";
    } catch (err) {
      console.error("Failed to create speed profile:", err);
    } finally {
      isCreatingSpeedProfile = false;
    }
  }

  function confirmPmfChange(value: string) {
    if (value === "required" || value === "optional") {
      pendingPmfValue = value;
      showPmfWarning = true;
    } else {
      updateWifiField("pmfMode", value);
    }
  }

  function applyPmfChange() {
    updateWifiField("pmfMode", pendingPmfValue);
    showPmfWarning = false;
    pendingPmfValue = "";
  }

  async function switchUnifiManagementTab(tab: typeof unifiManagementTab) {
    if (unifiManagementTab === "wifi" && tab !== "wifi" && isWifiDirty) {
      const confirmed = confirm("You have unsaved WiFi changes. Discard them?");
      if (!confirmed) return;
      selectedWifi = null;
      wifiEditState = {};
      wifiOriginalState = {};
      isWifiDirty = false;
      wifiSaveError = null;
    }
    unifiManagementTab = tab;
    if (!selectedUnifiSite) return;
    if (tab === "overview" && !unifiSiteOverview) {
      await loadUnifiOverview(selectedUnifiSite.id);
    } else if (tab === "devices" && unifiSiteDevices.length === 0) {
      await loadUnifiDevices(selectedUnifiSite.id);
    } else if (tab === "wifi") {
      const loads: Promise<void>[] = [];
      if (unifiSiteWifi.length === 0)
        loads.push(loadUnifiWifi(selectedUnifiSite.id));
      if (unifiSiteNetworks.length === 0)
        loads.push(loadUnifiNetworks(selectedUnifiSite.id));
      if (unifiSpeedProfiles.length === 0)
        loads.push(loadSpeedProfiles(selectedUnifiSite.id));
      if (unifiWlanGroups.length === 0)
        loads.push(loadWlanGroups(selectedUnifiSite.id));
      if (unifiApGroups.length === 0)
        loads.push(loadApGroups(selectedUnifiSite.id));
      if (unifiAccessPoints.length === 0)
        loads.push(loadAccessPoints(selectedUnifiSite.id));
      if (loads.length > 0) await Promise.all(loads);
    } else if (tab === "networks" && unifiSiteNetworks.length === 0) {
      await loadUnifiNetworks(selectedUnifiSite.id);
    }
  }

  async function unlinkUnifiSite(siteId: string) {
    if (!accessToken) return;
    isUnlinkingSite = true;
    try {
      await unifiApi.unlinkSite(accessToken, siteId);
      selectedUnifiSite = null;
      await invalidateAll();
    } catch (err) {
      console.error("Failed to unlink UniFi site:", err);
    } finally {
      isUnlinkingSite = false;
    }
  }

  function selectWifiNetwork(wifi: UnifiWifiNetwork) {
    if (isWifiDirty) {
      const confirmed = confirm("You have unsaved WiFi changes. Discard them?");
      if (!confirmed) return;
    }
    selectedWifi = wifi;
    const editState: Record<string, unknown> = { ...wifi };
    const origState: Record<string, unknown> = { ...wifi };
    // Default apGroupMode to "all" if not provided by the API
    if (!editState.apGroupMode) {
      editState.apGroupMode = "all";
      origState.apGroupMode = "all";
    }
    if (!Array.isArray(editState.apGroupIds)) {
      editState.apGroupIds = [];
      origState.apGroupIds = [];
    }
    // For "devices" mode, resolve the hidden AP group to get the actual device MACs
    if (
      editState.apGroupMode === "devices" &&
      Array.isArray(editState.apGroupIds)
    ) {
      const groupId = (editState.apGroupIds as string[])[0];
      const hiddenGroup = groupId
        ? unifiApGroups.find((g) => g.id === groupId)
        : null;
      const macs = hiddenGroup ? [...hiddenGroup.deviceMacs] : [];
      editState.deviceMacs = macs;
      origState.deviceMacs = [...macs];
    } else {
      editState.deviceMacs = [];
      origState.deviceMacs = [];
    }
    wifiEditState = editState;
    wifiOriginalState = origState;
    isWifiDirty = false;
    wifiSaveError = null;
    wifiAdvancedMode = wifi.settingPreference === "manual" ? "manual" : "auto";
    revealedWifiPassphrases = {};
    ppskNewName = "";
    ppskNewKey = "";
    ppskNewMac = "";
    ppskNewVlanId = "";
    wifiPPSKs = [];
    macFilterNewMac = "";
    if (wifi.privatePreSharedKeysEnabled && selectedUnifiSite) {
      loadPPSKs(selectedUnifiSite.id, wifi.id);
    }
  }

  function backToWifiList() {
    if (isWifiDirty) {
      const confirmed = confirm("You have unsaved WiFi changes. Discard them?");
      if (!confirmed) return;
    }
    selectedWifi = null;
    wifiEditState = {};
    wifiOriginalState = {};
    isWifiDirty = false;
    wifiSaveError = null;
    wifiAdvancedMode = "auto";
  }

  function updateWifiField(field: string, value: unknown) {
    wifiEditState[field] = value;
    wifiEditState = wifiEditState;
    checkWifiDirty();
  }

  function checkWifiDirty() {
    const allEditableFields = [
      "name",
      "passphrase",
      "enabled",
      "networkconfId",
      "band",
      "apGroupMode",
      "apGroupIds",
      "deviceMacs",
      "security",
      "wpaMode",
      "wpaEnc",
      "pmfMode",
      "privatePreSharedKeysEnabled",
      "hideSSID",
      "l2Isolation",
      "fastRoamingEnabled",
      "proxyArp",
      "bssTransition",
      "uapsdEnabled",
      "macFilterEnabled",
      "macFilterPolicy",
      "macFilterList",
      "radiusMacAuthEnabled",
      "radiusMacaclFormat",
      "usergroupId",
      "dtimMode",
      "dtimNg",
      "dtimNa",
      "dtim6e",
      "groupRekey",
      "no2ghzOui",
      "settingPreference",
      "wpa3Support",
      "wpa3Transition",
      "wpa3FastRoaming",
      "wpa3Enhanced192",
      "iappEnabled",
      "mcastenhanceEnabled",
      "isGuest",
      "passphraseAutogenerated",
      "radiusDasEnabled",
      "minrateSettingPreference",
      "minrateNgEnabled",
      "minrateNgDataRateKbps",
      "minrateNgAdvertisingRates",
      "minrateNaEnabled",
      "minrateNaDataRateKbps",
      "minrateNaAdvertisingRates",
    ];
    isWifiDirty = allEditableFields.some((f) => {
      if (!(f in wifiEditState)) return false;
      const a = wifiEditState[f];
      const b = wifiOriginalState[f];
      if (Array.isArray(a) || Array.isArray(b)) {
        return JSON.stringify(a) !== JSON.stringify(b);
      }
      return a !== b;
    });
  }

  function discardWifiChanges() {
    wifiEditState = { ...wifiOriginalState };
    isWifiDirty = false;
    wifiSaveError = null;
    wifiAdvancedMode =
      wifiOriginalState.settingPreference === "manual" ? "manual" : "auto";
  }

  async function saveWifiChanges() {
    if (!accessToken || !selectedUnifiSite || !selectedWifi) return;
    isSavingWifi = true;
    wifiSaveError = null;
    try {
      // Fields that are allowed in "auto" mode (basic settings only)
      const autoOnlyFields = new Set([
        "name",
        "passphrase",
        "enabled",
        "band",
        "security",
        "wpaMode",
        "hideSSID",
        "isGuest",
        "settingPreference",
        "networkconfId",
        "apGroupMode",
        "apGroupIds",
        "deviceMacs",
      ]);
      const payload: Record<string, unknown> = {};
      for (const field of Object.keys(wifiEditState)) {
        const a = wifiEditState[field];
        const b = wifiOriginalState[field];
        const changed =
          Array.isArray(a) || Array.isArray(b)
            ? JSON.stringify(a) !== JSON.stringify(b)
            : a !== b;
        if (changed) {
          if (wifiAdvancedMode === "auto" && !autoOnlyFields.has(field))
            continue;
          payload[field] = wifiEditState[field];
        }
      }
      if (Object.keys(payload).length === 0) return;
      // For "devices" mode, send deviceMacs and let the API handle apGroupIds
      if (wifiEditState.apGroupMode === "devices") {
        delete payload.apGroupIds;
        if (!payload.deviceMacs) {
          payload.deviceMacs = wifiEditState.deviceMacs;
        }
      } else {
        delete payload.deviceMacs;
      }
      const result = await unifiApi.updateWifi(
        accessToken,
        selectedUnifiSite.id,
        selectedWifi.id,
        payload,
      );
      const updated = result?.data ?? wifiEditState;
      selectedWifi = { ...selectedWifi, ...updated } as UnifiWifiNetwork;
      // Preserve deviceMacs for "devices" mode since the API doesn't return it
      const savedDeviceMacs =
        wifiEditState.apGroupMode === "devices"
          ? ((wifiEditState.deviceMacs as string[]) ?? [])
          : [];
      wifiEditState = { ...updated, deviceMacs: savedDeviceMacs };
      wifiOriginalState = { ...updated, deviceMacs: [...savedDeviceMacs] };
      isWifiDirty = false;
      unifiSiteWifi = unifiSiteWifi.map((w) =>
        w.id === selectedWifi!.id
          ? ({ ...w, ...updated } as UnifiWifiNetwork)
          : w,
      );
      // Re-fetch AP groups so the newly created hidden group is available
      if (wifiEditState.apGroupMode === "devices" && selectedUnifiSite) {
        loadApGroups(selectedUnifiSite.id);
      }
    } catch (err) {
      console.error("Failed to save WiFi changes:", err);
      wifiSaveError =
        err instanceof Error ? err.message : "Failed to save changes";
    } finally {
      isSavingWifi = false;
    }
  }
</script>

<svelte:window
  on:click={() => {
    isUnifiSiteMenuOpen = false;
  }}
/>

<LinkUnifiSiteModal
  bind:isOpen={isLinkUnifiOpen}
  {companyId}
  accessToken={accessToken ?? ""}
  linkedSiteIds={unifiSites.map((s) => s.id)}
  onSuccess={() => {
    isLinkUnifiOpen = false;
    invalidateAll();
  }}
/>

{#if selectedUnifiSite}
  <!-- Management view for a selected UniFi site -->
  <div class="unifi-management">
    <div class="unifi-management-header">
      <button
        class="unifi-back-btn"
        on:click={backToUnifiSites}
        type="button"
        aria-label="Back to sites"
      >
        <svg
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          stroke-width="2"
          width="16"
          height="16"
        >
          <path d="M19 12H5M12 19l-7-7 7-7" />
        </svg>
      </button>
      <div class="unifi-management-title-group">
        <h3 class="unifi-management-title">{selectedUnifiSite.name}</h3>
        <span class="unifi-management-site-id">{selectedUnifiSite.siteId}</span>
      </div>
      <div class="unifi-site-menu-wrap">
        <button
          type="button"
          class="unifi-site-menu-btn"
          aria-label="Site actions"
          on:click|stopPropagation={() =>
            (isUnifiSiteMenuOpen = !isUnifiSiteMenuOpen)}
        >
          <svg viewBox="0 0 16 16" fill="currentColor" width="14" height="14">
            <circle cx="8" cy="2.5" r="1.5" /><circle
              cx="8"
              cy="8"
              r="1.5"
            /><circle cx="8" cy="13.5" r="1.5" />
          </svg>
        </button>
        {#if isUnifiSiteMenuOpen}
          <!-- svelte-ignore a11y_no_static_element_interactions -->
          <!-- svelte-ignore a11y_click_events_have_key_events -->
          <div class="unifi-site-dropdown-menu" on:click|stopPropagation>
            <button
              type="button"
              class="unifi-site-dropdown-item unifi-site-dropdown-item-danger"
              disabled={isUnlinkingSite}
              on:click|stopPropagation={() => {
                isUnifiSiteMenuOpen = false;
                unlinkUnifiSite(selectedUnifiSite?.id ?? "");
              }}
            >
              {#if isUnlinkingSite}
                <svg
                  viewBox="0 0 24 24"
                  width="13"
                  height="13"
                  class="spin-icon"
                  ><circle
                    cx="12"
                    cy="12"
                    r="10"
                    stroke="currentColor"
                    stroke-width="3"
                    fill="none"
                    opacity="0.25"
                  /><path
                    d="M12 2a10 10 0 0 1 10 10"
                    stroke="currentColor"
                    stroke-width="3"
                    fill="none"
                    stroke-linecap="round"
                  /></svg
                >
              {:else}
                <svg
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  stroke-width="2"
                  width="13"
                  height="13"><path d="M18 6L6 18M6 6l12 12" /></svg
                >
              {/if}
              Unlink Site
            </button>
          </div>
        {/if}
      </div>
    </div>

    <!-- Management sub-tabs -->
    <div class="unifi-mgmt-tabs">
      <button
        class="unifi-mgmt-tab"
        class:active={unifiManagementTab === "overview"}
        on:click={() => switchUnifiManagementTab("overview")}
        type="button">Overview</button
      >
      <button
        class="unifi-mgmt-tab"
        class:active={unifiManagementTab === "devices"}
        on:click={() => switchUnifiManagementTab("devices")}
        type="button">Devices</button
      >
      {#if permissions["unifi.site.wifi"] && permissions["unifi.site.wifi.read.name"]}
        <button
          class="unifi-mgmt-tab"
          class:active={unifiManagementTab === "wifi"}
          on:click={() => switchUnifiManagementTab("wifi")}
          type="button">WiFi</button
        >
      {/if}
      <button
        class="unifi-mgmt-tab"
        class:active={unifiManagementTab === "networks"}
        on:click={() => switchUnifiManagementTab("networks")}
        type="button">Networks</button
      >
    </div>

    <div class="unifi-mgmt-content">
      {#if unifiManagementTab === "overview"}
        {#if isLoadingUnifiOverview}
          <div class="unifi-loading">
            <svg viewBox="0 0 24 24" width="20" height="20" class="spin-icon"
              ><circle
                cx="12"
                cy="12"
                r="10"
                stroke="currentColor"
                stroke-width="3"
                fill="none"
                opacity="0.25"
              /><path
                d="M12 2a10 10 0 0 1 10 10"
                stroke="currentColor"
                stroke-width="3"
                fill="none"
                stroke-linecap="round"
              /></svg
            >
            <span>Loading overview…</span>
          </div>
        {:else if unifiSiteOverview}
          <div class="unifi-overview-grid">
            {#if unifiSiteOverview.health && unifiSiteOverview.health.length > 0}
              <div class="unifi-overview-section">
                <h4 class="unifi-section-title">
                  <svg
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    stroke-width="2"
                    width="14"
                    height="14"><path d="M22 12h-4l-3 9L9 3l-3 9H2" /></svg
                  >
                  Health
                </h4>
                <div class="unifi-health-cards">
                  {#each unifiSiteOverview.health as h}
                    <div class="unifi-health-card">
                      <span
                        class="unifi-health-status"
                        class:healthy={h.status === "ok"}
                        class:unhealthy={h.status !== "ok"}
                      >
                        {h.status === "ok" ? "●" : "○"}
                      </span>
                      <span class="unifi-health-subsystem">{h.subsystem}</span>
                      <span class="unifi-health-status-text">{h.status}</span>
                    </div>
                  {/each}
                </div>
              </div>
            {/if}
            {#if unifiSiteOverview.sysInfo}
              <div class="unifi-overview-section">
                <h4 class="unifi-section-title">
                  <svg
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    stroke-width="2"
                    width="14"
                    height="14"
                    ><rect
                      x="2"
                      y="3"
                      width="20"
                      height="14"
                      rx="2"
                      ry="2"
                    /><line x1="8" y1="21" x2="16" y2="21" /><line
                      x1="12"
                      y1="17"
                      x2="12"
                      y2="21"
                    /></svg
                  >
                  System Info
                </h4>
                <div class="unifi-info-grid">
                  {#if unifiSiteOverview.sysInfo.hostname}
                    <div class="unifi-info-item">
                      <span class="unifi-info-label">Hostname</span><span
                        class="unifi-info-value"
                        >{unifiSiteOverview.sysInfo.hostname}</span
                      >
                    </div>
                  {/if}
                  {#if unifiSiteOverview.sysInfo.version}
                    <div class="unifi-info-item">
                      <span class="unifi-info-label">Version</span><span
                        class="unifi-info-value mono"
                        >{unifiSiteOverview.sysInfo.version}</span
                      >
                    </div>
                  {/if}
                  {#if unifiSiteOverview.sysInfo.timezone}
                    <div class="unifi-info-item">
                      <span class="unifi-info-label">Timezone</span><span
                        class="unifi-info-value"
                        >{unifiSiteOverview.sysInfo.timezone}</span
                      >
                    </div>
                  {/if}
                </div>
              </div>
            {/if}
          </div>
        {:else}
          <div class="unifi-empty-state"><p>No overview data available</p></div>
        {/if}
      {:else if unifiManagementTab === "devices"}
        {#if isLoadingUnifiDevices}
          <div class="unifi-loading">
            <svg viewBox="0 0 24 24" width="20" height="20" class="spin-icon"
              ><circle
                cx="12"
                cy="12"
                r="10"
                stroke="currentColor"
                stroke-width="3"
                fill="none"
                opacity="0.25"
              /><path
                d="M12 2a10 10 0 0 1 10 10"
                stroke="currentColor"
                stroke-width="3"
                fill="none"
                stroke-linecap="round"
              /></svg
            >
            <span>Loading devices…</span>
          </div>
        {:else if unifiSiteDevices.length === 0}
          <div class="unifi-empty-state">
            <svg
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="1.5"
              width="32"
              height="32"
              ><rect x="2" y="3" width="20" height="14" rx="2" ry="2" /><line
                x1="8"
                y1="21"
                x2="16"
                y2="21"
              /><line x1="12" y1="17" x2="12" y2="21" /></svg
            >
            <p>No devices found</p>
          </div>
        {:else}
          <div class="unifi-devices-table-wrap">
            <table class="unifi-devices-table">
              <thead
                ><tr
                  ><th>Status</th><th>Name</th><th>Model</th><th>IP</th><th
                    >MAC</th
                  ><th>Version</th><th>Uptime</th></tr
                ></thead
              >
              <tbody>
                {#each unifiSiteDevices as device (device.id)}
                  <tr class="unifi-device-row">
                    <td class="unifi-device-status-cell"
                      ><span
                        class="unifi-device-status-dot"
                        class:online={device.state === "connected" ||
                          device.state === 1}
                        class:offline={device.state !== "connected" &&
                          device.state !== 1}
                      ></span></td
                    >
                    <td class="unifi-device-name-cell"
                      >{device.name || device.mac}</td
                    >
                    <td class="unifi-device-model-cell">{device.model}</td>
                    <td class="unifi-device-mono-cell">{device.ip || "—"}</td>
                    <td class="unifi-device-mono-cell">{device.mac}</td>
                    <td class="unifi-device-mono-cell"
                      >{device.version || "—"}</td
                    >
                    <td class="unifi-device-uptime-cell"
                      >{#if device.uptime}{formatUptime(
                          device.uptime,
                        )}{:else}—{/if}</td
                    >
                  </tr>
                {/each}
              </tbody>
            </table>
          </div>
        {/if}
      {:else if unifiManagementTab === "wifi"}
        {#if isLoadingUnifiWifi}
          <div class="unifi-loading">
            <svg viewBox="0 0 24 24" width="20" height="20" class="spin-icon"
              ><circle
                cx="12"
                cy="12"
                r="10"
                stroke="currentColor"
                stroke-width="3"
                fill="none"
                opacity="0.25"
              /><path
                d="M12 2a10 10 0 0 1 10 10"
                stroke="currentColor"
                stroke-width="3"
                fill="none"
                stroke-linecap="round"
              /></svg
            >
            <span>Loading WiFi networks…</span>
          </div>
        {:else if unifiSiteWifi.length === 0}
          <div class="unifi-empty-state">
            <svg
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="1.5"
              width="32"
              height="32"
              ><path d="M5 12.55a11 11 0 0114.08 0" /><path
                d="M1.42 9a16 16 0 0121.16 0"
              /><path d="M8.53 16.11a6 6 0 016.95 0" /><line
                x1="12"
                y1="20"
                x2="12.01"
                y2="20"
              /></svg
            >
            <p>No WiFi networks found</p>
          </div>
        {:else}
          <div
            class="wifi-split-view"
            class:detail-open={selectedWifi !== null}
          >
            <!-- Network list panel -->
            <div class="wifi-list-panel">
              <div class="wifi-table-header">
                <span class="wifi-table-title">WiFi Networks</span><span
                  class="wifi-list-count">{unifiSiteWifi.length}</span
                >
              </div>
              <div class="wifi-table-head">
                <span class="wifi-col wifi-col-status"></span>
                <span class="wifi-col wifi-col-name">Name</span>
                <span class="wifi-col wifi-col-vlan">Network</span>
                <span class="wifi-col wifi-col-aps">Broadcasting AP's</span>
                <span class="wifi-col wifi-col-band">Radio Band</span>
                <span class="wifi-col wifi-col-clients">Clients</span>
                <span class="wifi-col wifi-col-security">Security</span>
              </div>
              <div class="wifi-table-body">
                {#each unifiSiteWifi as wifi, i (wifi.id ?? `wifi-${i}`)}
                  <button
                    class="wifi-table-row"
                    class:active={selectedWifi === wifi ||
                      (selectedWifi?.id && selectedWifi.id === wifi.id)}
                    on:click={() => selectWifiNetwork(wifi)}
                    type="button"
                  >
                    <span class="wifi-col wifi-col-status"
                      ><span
                        class="wifi-status-dot"
                        class:enabled={wifi.enabled !== false}
                        title={wifi.enabled !== false ? "Enabled" : "Disabled"}
                      ></span></span
                    >
                    <span class="wifi-col wifi-col-name">
                      <span class="wifi-network-name"
                        >{wifi.name ?? wifi.id ?? "Unknown"}</span
                      >
                      {#if "hideSSID" in wifi && wifi.hideSSID}<span
                          class="wifi-table-tag">Hidden</span
                        >{/if}
                      {#if "isGuest" in wifi && wifi.isGuest}<span
                          class="wifi-table-tag wifi-table-tag-guest"
                          >Guest</span
                        >{/if}
                    </span>
                    <span class="wifi-col wifi-col-vlan">
                      {#if "networkconfId" in wifi && wifi.networkconfId}
                        {@const net = unifiSiteNetworks.find(
                          (n) => n.id === wifi.networkconfId,
                        )}
                        {#if net}{net.name}{:else}—{/if}
                      {:else}—{/if}
                    </span>
                    <span class="wifi-col wifi-col-aps">
                      {#if wifi.apGroupMode === "all"}All
                      {:else if wifi.apGroupMode === "groups" && Array.isArray(wifi.apGroupIds)}
                        {@const names = wifi.apGroupIds
                          .map(
                            (gid) =>
                              unifiApGroups.find((g) => g.id === gid)?.name,
                          )
                          .filter(Boolean)}
                        {#if names.length > 0}{names.join(", ")}{:else}{wifi
                            .apGroupIds.length}
                          {wifi.apGroupIds.length === 1
                            ? "group"
                            : "groups"}{/if}
                      {:else if wifi.apGroupMode === "devices" && Array.isArray(wifi.apGroupIds)}
                        {@const groupId = wifi.apGroupIds[0]}
                        {@const hiddenGroup = groupId
                          ? unifiApGroups.find((g) => g.id === groupId)
                          : null}
                        {@const apCount = hiddenGroup
                          ? hiddenGroup.deviceMacs.length
                          : wifi.apGroupIds.length}
                        {apCount}
                        {apCount === 1 ? "AP" : "APs"}
                      {:else}—{/if}
                    </span>
                    <span class="wifi-col wifi-col-band">
                      {#if "band" in wifi}<span class="wifi-band-badge"
                          >{wifi.band === "both"
                            ? "2.4 / 5 GHz"
                            : wifi.band === "2g"
                              ? "2.4 GHz"
                              : wifi.band === "5g"
                                ? "5 GHz"
                                : wifi.band}</span
                        >{:else}—{/if}
                    </span>
                    <span class="wifi-col wifi-col-clients">—</span>
                    <span class="wifi-col wifi-col-security">
                      {#if "security" in wifi}
                        {wifi.security === "wpapsk"
                          ? "WPA Personal"
                          : wifi.security === "wpaeap"
                            ? "WPA Enterprise"
                            : wifi.security === "open"
                              ? "Open"
                              : wifi.security}{#if "wpaMode" in wifi}&nbsp;({wifi.wpaMode ===
                          "wpa2"
                            ? "WPA2"
                            : wifi.wpaMode === "wpa3"
                              ? "WPA3"
                              : wifi.wpaMode === "wpa2wpa3"
                                ? "WPA2/3"
                                : wifi.wpaMode}){/if}
                      {:else}—{/if}
                    </span>
                  </button>
                {/each}
              </div>
            </div>

            <!-- Detail panel -->
            <div class="wifi-detail-panel">
              {#if selectedWifi}
                <div class="wifi-detail-header">
                  <button
                    class="wifi-detail-back"
                    type="button"
                    on:click={backToWifiList}
                  >
                    <svg
                      viewBox="0 0 24 24"
                      fill="none"
                      stroke="currentColor"
                      stroke-width="2"
                      width="16"
                      height="16"><path d="M15 18l-6-6 6-6" /></svg
                    >
                    Back
                  </button>
                  {#if canEditWifi}
                    <div class="wifi-detail-actions">
                      {#if isWifiDirty}
                        <button
                          class="wifi-btn wifi-btn-ghost"
                          type="button"
                          on:click={discardWifiChanges}>Discard</button
                        >
                      {/if}
                      <button
                        class="wifi-btn wifi-btn-primary"
                        type="button"
                        on:click={saveWifiChanges}
                        disabled={!isWifiDirty || isSavingWifi}
                        >{isSavingWifi ? "Saving…" : "Save Changes"}</button
                      >
                    </div>
                  {/if}
                </div>

                {#if wifiSaveError}
                  <div class="wifi-save-error">{wifiSaveError}</div>
                {/if}

                <!-- PMF Warning Modal -->
                {#if showPmfWarning}
                  <div
                    class="wifi-modal-overlay"
                    on:click|self={() => {
                      showPmfWarning = false;
                    }}
                    on:keydown={(e) => {
                      if (e.key === "Escape") showPmfWarning = false;
                    }}
                    role="dialog"
                    tabindex="-1"
                  >
                    <div class="wifi-modal">
                      <div class="wifi-modal-header">
                        <svg
                          viewBox="0 0 24 24"
                          fill="none"
                          stroke="#f59e0b"
                          stroke-width="2"
                          width="20"
                          height="20"
                          ><path
                            d="M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z"
                          /><line x1="12" y1="9" x2="12" y2="13" /><line
                            x1="12"
                            y1="17"
                            x2="12.01"
                            y2="17"
                          /></svg
                        >
                        <span>PMF Warning</span>
                      </div>
                      <p class="wifi-modal-body">
                        Setting PMF to <strong
                          >{pendingPmfValue === "required"
                            ? "Required"
                            : "Optional"}</strong
                        > may cause connectivity issues with legacy IoT devices that
                        do not support Protected Management Frames.
                      </p>
                      <div class="wifi-modal-actions">
                        <button
                          class="wifi-btn wifi-btn-ghost"
                          type="button"
                          on:click={() => {
                            showPmfWarning = false;
                          }}>Cancel</button
                        >
                        <button
                          class="wifi-btn wifi-btn-primary"
                          type="button"
                          on:click={applyPmfChange}>Apply Anyway</button
                        >
                      </div>
                    </div>
                  </div>
                {/if}

                <!-- Speed Profile Create Modal -->
                {#if showSpeedProfileModal}
                  <div
                    class="wifi-modal-overlay"
                    on:click|self={() => {
                      showSpeedProfileModal = false;
                    }}
                    on:keydown={(e) => {
                      if (e.key === "Escape") showSpeedProfileModal = false;
                    }}
                    role="dialog"
                    tabindex="-1"
                  >
                    <div class="wifi-modal">
                      <div class="wifi-modal-header">
                        <svg
                          viewBox="0 0 24 24"
                          fill="none"
                          stroke="currentColor"
                          stroke-width="2"
                          width="18"
                          height="18"
                          ><polyline
                            points="22 12 18 12 15 21 9 3 6 12 2 12"
                          /></svg
                        >
                        <span>Create Speed Profile</span>
                      </div>
                      <div class="wifi-modal-form">
                        <label class="wifi-modal-field"
                          ><span>Name</span><input
                            type="text"
                            class="wifi-field-input"
                            bind:value={speedProfileName}
                            placeholder="e.g. Guest 10Mbps"
                          /></label
                        >
                        <label class="wifi-modal-field"
                          ><span>Download Limit (Kbps)</span><input
                            type="number"
                            class="wifi-field-input"
                            bind:value={speedProfileDown}
                            placeholder="Unlimited if empty"
                          /></label
                        >
                        <label class="wifi-modal-field"
                          ><span>Upload Limit (Kbps)</span><input
                            type="number"
                            class="wifi-field-input"
                            bind:value={speedProfileUp}
                            placeholder="Unlimited if empty"
                          /></label
                        >
                      </div>
                      <div class="wifi-modal-actions">
                        <button
                          class="wifi-btn wifi-btn-ghost"
                          type="button"
                          on:click={() => {
                            showSpeedProfileModal = false;
                          }}>Cancel</button
                        >
                        <button
                          class="wifi-btn wifi-btn-primary"
                          type="button"
                          on:click={createSpeedProfile}
                          disabled={!speedProfileName.trim() ||
                            isCreatingSpeedProfile}
                          >{isCreatingSpeedProfile
                            ? "Creating…"
                            : "Create"}</button
                        >
                      </div>
                    </div>
                  </div>
                {/if}

                <div class="wifi-detail-form">
                  <!-- Manual / Auto mode toggle -->
                  {#if canEditWifi}
                    <div class="wifi-mode-toggle-wrap">
                      <span class="wifi-mode-label">Configuration Mode</span>
                      <div class="wifi-mode-toggle">
                        <button
                          type="button"
                          class:active={wifiAdvancedMode === "auto"}
                          on:click={() => {
                            wifiAdvancedMode = "auto";
                            updateWifiField("settingPreference", "auto");
                          }}>Auto</button
                        >
                        <button
                          type="button"
                          class:active={wifiAdvancedMode === "manual"}
                          on:click={() => {
                            wifiAdvancedMode = "manual";
                            updateWifiField("settingPreference", "manual");
                          }}>Manual</button
                        >
                      </div>
                      <span class="wifi-mode-hint"
                        >{wifiAdvancedMode === "auto"
                          ? "Only general settings are sent. Security and behavior controls are locked."
                          : "All settings are editable. Changes are saved when you click Save."}</span
                      >
                    </div>
                  {/if}

                  <!-- SECTION 1: GENERAL -->
                  <div class="wifi-group-card">
                    <div class="wifi-group-header">
                      <div class="wifi-group-icon">
                        <svg
                          viewBox="0 0 24 24"
                          fill="none"
                          stroke="currentColor"
                          stroke-width="2"
                          width="16"
                          height="16"
                          ><path d="M5 12.55a11 11 0 0114.08 0" /><path
                            d="M1.42 9a16 16 0 0121.16 0"
                          /><path d="M8.53 16.11a6 6 0 016.95 0" /><circle
                            cx="12"
                            cy="20"
                            r="1"
                          /></svg
                        >
                      </div>
                      <div class="wifi-group-title-wrap">
                        <h4 class="wifi-group-title">General</h4>
                        <span class="wifi-group-desc"
                          >Network name, password, and broadcasting</span
                        >
                      </div>
                    </div>
                    <div class="wifi-group-fields">
                      <!-- Name (SSID) -->
                      <div class="wifi-field">
                        <div class="wifi-field-label-row">
                          <span class="wifi-field-label">Name (SSID)</span>
                        </div>
                        {#if canEditWifi}<input
                            type="text"
                            class="wifi-field-input"
                            value={wifiEditState.name ?? ""}
                            on:input={(e) =>
                              updateWifiField("name", e.currentTarget.value)}
                          />{:else}<span class="wifi-field-value"
                            >{wifiEditState.name ?? "—"}</span
                          >{/if}
                      </div>
                      <!-- Password -->
                      {#if wifiEditState.security !== "open"}
                        <div class="wifi-field">
                          <div class="wifi-field-label-row">
                            <span class="wifi-field-label">Password</span>
                          </div>
                          <div class="wifi-passphrase-wrap">
                            {#if canEditWifi}<input
                                type={revealedWifiPassphrases["detail"]
                                  ? "text"
                                  : "password"}
                                class="wifi-field-input mono"
                                value={wifiEditState.passphrase ?? ""}
                                on:input={(e) =>
                                  updateWifiField(
                                    "passphrase",
                                    e.currentTarget.value,
                                  )}
                              />{:else}<span class="wifi-field-value mono"
                                >{revealedWifiPassphrases["detail"]
                                  ? wifiEditState.passphrase
                                  : "••••••••"}</span
                              >{/if}
                            <button
                              class="wifi-reveal-btn"
                              type="button"
                              on:click={() => {
                                revealedWifiPassphrases["detail"] =
                                  !revealedWifiPassphrases["detail"];
                                revealedWifiPassphrases =
                                  revealedWifiPassphrases;
                              }}
                            >
                              {#if revealedWifiPassphrases["detail"]}<svg
                                  viewBox="0 0 24 24"
                                  fill="none"
                                  stroke="currentColor"
                                  stroke-width="2"
                                  width="14"
                                  height="14"
                                  ><path
                                    d="M17.94 17.94A10.07 10.07 0 0112 20c-7 0-11-8-11-8a18.45 18.45 0 015.06-5.94"
                                  /><path
                                    d="M9.9 4.24A9.12 9.12 0 0112 4c7 0 11 8 11 8a18.5 18.5 0 01-2.16 3.19"
                                  /><path
                                    d="M14.12 14.12a3 3 0 11-4.24-4.24"
                                  /><line x1="1" y1="1" x2="23" y2="23" /></svg
                                >{:else}<svg
                                  viewBox="0 0 24 24"
                                  fill="none"
                                  stroke="currentColor"
                                  stroke-width="2"
                                  width="14"
                                  height="14"
                                  ><path
                                    d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"
                                  /><circle cx="12" cy="12" r="3" /></svg
                                >{/if}
                            </button>
                          </div>
                        </div>
                      {/if}
                      <!-- Network -->
                      <div class="wifi-field">
                        <div class="wifi-field-label-row">
                          <span class="wifi-field-label">Network</span><span
                            class="wifi-field-hint"
                            >VLAN / network assignment for this SSID</span
                          >
                        </div>
                        {#if canEditWifi}<select
                            class="wifi-field-select"
                            value={String(wifiEditState.networkconfId ?? "")}
                            on:change={(e) =>
                              updateWifiField(
                                "networkconfId",
                                e.currentTarget.value,
                              )}
                            ><option value="">— Select Network —</option
                            >{#each unifiSiteNetworks as net}<option
                                value={net.id}
                                >{net.name}{net.vlanId
                                  ? ` (VLAN ${net.vlanId})`
                                  : ""}</option
                              >{/each}</select
                          >{:else}{@const net = unifiSiteNetworks.find(
                            (n) => n.id === String(wifiEditState.networkconfId),
                          )}<span class="wifi-field-value"
                            >{net
                              ? `${net.name}${net.vlanId ? ` (VLAN ${net.vlanId})` : ""}`
                              : "—"}</span
                          >{/if}
                      </div>
                      <!-- Broadcasting APs -->
                      <div class="wifi-field">
                        <div class="wifi-field-label-row">
                          <span class="wifi-field-label">Broadcasting APs</span
                          ><span class="wifi-field-hint"
                            >Which access points broadcast this network</span
                          >
                        </div>
                        {#if canEditWifi}<div class="wifi-bubble-select">
                            <button
                              type="button"
                              class="wifi-bubble"
                              class:active={wifiEditState.apGroupMode === "all"}
                              on:click={() => {
                                updateWifiField("apGroupMode", "all");
                                updateWifiField("apGroupIds", []);
                                updateWifiField("deviceMacs", []);
                              }}>All</button
                            ><button
                              type="button"
                              class="wifi-bubble"
                              class:active={wifiEditState.apGroupMode ===
                                "groups"}
                              on:click={() => {
                                updateWifiField("apGroupMode", "groups");
                                updateWifiField("apGroupIds", []);
                                updateWifiField("deviceMacs", []);
                              }}>Group</button
                            ><button
                              type="button"
                              class="wifi-bubble"
                              class:active={wifiEditState.apGroupMode ===
                                "devices"}
                              on:click={() => {
                                updateWifiField("apGroupMode", "devices");
                                updateWifiField("apGroupIds", []);
                                updateWifiField("deviceMacs", []);
                              }}>Specific</button
                            >
                          </div>{:else}<span class="wifi-field-value"
                            >{wifiEditState.apGroupMode === "all"
                              ? "All APs"
                              : wifiEditState.apGroupMode === "groups"
                                ? "Groups"
                                : "Specific Devices"}</span
                          >{/if}
                        {#if wifiEditState.apGroupMode === "groups"}
                          <div class="wifi-group-checklist">
                            {#if isLoadingApGroups}
                              <div class="wifi-group-checklist-loading">
                                <svg
                                  viewBox="0 0 24 24"
                                  width="16"
                                  height="16"
                                  class="spin-icon"
                                >
                                  <circle
                                    cx="12"
                                    cy="12"
                                    r="10"
                                    stroke="currentColor"
                                    stroke-width="3"
                                    fill="none"
                                    opacity="0.25"
                                  />
                                  <path
                                    d="M12 2a10 10 0 0 1 10 10"
                                    stroke="currentColor"
                                    stroke-width="3"
                                    fill="none"
                                    stroke-linecap="round"
                                  />
                                </svg>
                                <span>Loading AP groups…</span>
                              </div>
                            {:else if unifiApGroups.length === 0}
                              <div class="wifi-group-checklist-empty">
                                No AP groups found
                              </div>
                            {:else}
                              <table class="wifi-group-table">
                                <thead>
                                  <tr>
                                    <th class="wifi-group-th-check"></th>
                                    <th class="wifi-group-th-name"
                                      >Group Name</th
                                    >
                                    <th class="wifi-group-th-meta">APs</th>
                                  </tr>
                                </thead>
                                <tbody>
                                  {#each unifiApGroups.filter((g) => g.name !== "devices_ap_group") as group (group.id)}
                                    {@const isChecked =
                                      Array.isArray(wifiEditState.apGroupIds) &&
                                      (
                                        wifiEditState.apGroupIds as string[]
                                      ).includes(group.id)}
                                    {@const isEmpty =
                                      group.deviceMacs.length === 0}
                                    <tr
                                      class="wifi-group-row"
                                      class:checked={isChecked}
                                      class:wifi-group-row-disabled={isEmpty}
                                    >
                                      <td class="wifi-group-td-check">
                                        {#if canEditWifi}
                                          <input
                                            type="checkbox"
                                            checked={isChecked}
                                            disabled={isEmpty}
                                            on:change={() => {
                                              const validIds = new Set(
                                                unifiApGroups.map((g) => g.id),
                                              );
                                              const current = Array.isArray(
                                                wifiEditState.apGroupIds,
                                              )
                                                ? (
                                                    wifiEditState.apGroupIds as string[]
                                                  ).filter((id) =>
                                                    validIds.has(id),
                                                  )
                                                : [];
                                              if (isChecked) {
                                                updateWifiField(
                                                  "apGroupIds",
                                                  current.filter(
                                                    (id) => id !== group.id,
                                                  ),
                                                );
                                              } else {
                                                updateWifiField("apGroupIds", [
                                                  ...current,
                                                  group.id,
                                                ]);
                                              }
                                            }}
                                          />
                                        {:else}
                                          <input
                                            type="checkbox"
                                            checked={isChecked}
                                            disabled
                                          />
                                        {/if}
                                      </td>
                                      <td class="wifi-group-td-name"
                                        >{group.name}</td
                                      >
                                      <td class="wifi-group-td-meta"
                                        >{group.deviceMacs.length}
                                        {group.deviceMacs.length === 1
                                          ? "AP"
                                          : "APs"}</td
                                      >
                                    </tr>
                                  {/each}
                                </tbody>
                              </table>
                            {/if}
                          </div>
                        {:else if wifiEditState.apGroupMode === "devices"}
                          <div class="wifi-group-checklist">
                            {#if isLoadingAccessPoints}
                              <div class="wifi-group-checklist-loading">
                                <svg
                                  viewBox="0 0 24 24"
                                  width="16"
                                  height="16"
                                  class="spin-icon"
                                >
                                  <circle
                                    cx="12"
                                    cy="12"
                                    r="10"
                                    stroke="currentColor"
                                    stroke-width="3"
                                    fill="none"
                                    opacity="0.25"
                                  />
                                  <path
                                    d="M12 2a10 10 0 0 1 10 10"
                                    stroke="currentColor"
                                    stroke-width="3"
                                    fill="none"
                                    stroke-linecap="round"
                                  />
                                </svg>
                                <span>Loading access points…</span>
                              </div>
                            {:else if unifiAccessPoints.length === 0}
                              <div class="wifi-group-checklist-empty">
                                No access points found
                              </div>
                            {:else}
                              <table class="wifi-group-table">
                                <thead>
                                  <tr>
                                    <th class="wifi-group-th-check"></th>
                                    <th class="wifi-group-th-name"
                                      >Access Point</th
                                    >
                                    <th class="wifi-group-th-meta">Model</th>
                                    <th class="wifi-group-th-meta">IP</th>
                                  </tr>
                                </thead>
                                <tbody>
                                  {#each unifiAccessPoints as ap (ap.id)}
                                    {@const isChecked =
                                      Array.isArray(wifiEditState.deviceMacs) &&
                                      (
                                        wifiEditState.deviceMacs as string[]
                                      ).includes(ap.mac)}
                                    <tr
                                      class="wifi-group-row"
                                      class:checked={isChecked}
                                    >
                                      <td class="wifi-group-td-check">
                                        {#if canEditWifi}
                                          <input
                                            type="checkbox"
                                            checked={isChecked}
                                            on:change={() => {
                                              const validMacs = new Set(
                                                unifiAccessPoints.map(
                                                  (a) => a.mac,
                                                ),
                                              );
                                              const current = Array.isArray(
                                                wifiEditState.deviceMacs,
                                              )
                                                ? (
                                                    wifiEditState.deviceMacs as string[]
                                                  ).filter((mac) =>
                                                    validMacs.has(mac),
                                                  )
                                                : [];
                                              if (isChecked) {
                                                updateWifiField(
                                                  "deviceMacs",
                                                  current.filter(
                                                    (mac) => mac !== ap.mac,
                                                  ),
                                                );
                                              } else {
                                                updateWifiField("deviceMacs", [
                                                  ...current,
                                                  ap.mac,
                                                ]);
                                              }
                                            }}
                                          />
                                        {:else}
                                          <input
                                            type="checkbox"
                                            checked={isChecked}
                                            disabled
                                          />
                                        {/if}
                                      </td>
                                      <td class="wifi-group-td-name">
                                        <span>{ap.name || ap.mac}</span>
                                        {#if ap.name}<span
                                            class="wifi-group-ap-mac"
                                            >{ap.mac}</span
                                          >{/if}
                                      </td>
                                      <td class="wifi-group-td-meta"
                                        >{ap.model}</td
                                      >
                                      <td class="wifi-group-td-meta mono"
                                        >{ap.ip}</td
                                      >
                                    </tr>
                                  {/each}
                                </tbody>
                              </table>
                            {/if}
                          </div>
                        {/if}
                      </div>
                      <!-- Application -->
                      <div class="wifi-field">
                        <div class="wifi-field-label-row">
                          <span class="wifi-field-label">Application</span><span
                            class="wifi-field-hint">Network purpose</span
                          >
                        </div>
                        {#if canEditWifi}<div class="wifi-bubble-select">
                            <button
                              type="button"
                              class="wifi-bubble"
                              class:active={!wifiEditState.isGuest}
                              on:click={() => updateWifiField("isGuest", false)}
                              >Standard</button
                            ><button
                              type="button"
                              class="wifi-bubble"
                              class:active={!!wifiEditState.isGuest}
                              on:click={() => updateWifiField("isGuest", true)}
                              >Guest / IoT</button
                            >
                          </div>{:else}<span class="wifi-field-value"
                            >{wifiEditState.isGuest
                              ? "Guest / IoT"
                              : "Standard"}</span
                          >{/if}
                      </div>
                      <!-- Radio Band -->
                      <div class="wifi-field">
                        <div class="wifi-field-label-row">
                          <span class="wifi-field-label">Radio Band</span><span
                            class="wifi-field-hint"
                            >Which frequencies to broadcast on</span
                          >
                        </div>
                        {#if canEditWifi}<div class="wifi-radio-band-checks">
                            <label class="wifi-radio-check"
                              ><input
                                type="checkbox"
                                checked={wifiEditState.band === "2g" ||
                                  wifiEditState.band === "both"}
                                on:change={(e) => {
                                  const has5g =
                                    wifiEditState.band === "5g" ||
                                    wifiEditState.band === "both";
                                  if (e.currentTarget.checked) {
                                    updateWifiField(
                                      "band",
                                      has5g ? "both" : "2g",
                                    );
                                  } else {
                                    updateWifiField(
                                      "band",
                                      has5g ? "5g" : "2g",
                                    );
                                  }
                                }}
                              /><span>2.4 GHz</span></label
                            ><label class="wifi-radio-check"
                              ><input
                                type="checkbox"
                                checked={wifiEditState.band === "5g" ||
                                  wifiEditState.band === "both"}
                                on:change={(e) => {
                                  const has2g =
                                    wifiEditState.band === "2g" ||
                                    wifiEditState.band === "both";
                                  if (e.currentTarget.checked) {
                                    updateWifiField(
                                      "band",
                                      has2g ? "both" : "5g",
                                    );
                                  } else {
                                    updateWifiField(
                                      "band",
                                      has2g ? "2g" : "5g",
                                    );
                                  }
                                }}
                              /><span>5 GHz</span></label
                            ><label
                              class="wifi-radio-check wifi-radio-disabled"
                              title="6 GHz support coming soon"
                              ><input type="checkbox" disabled /><span
                                >6 GHz</span
                              ><span class="wifi-todo-badge">TODO</span></label
                            >
                          </div>{:else}<span class="wifi-field-value"
                            >{wifiEditState.band === "both"
                              ? "2.4 / 5 GHz"
                              : wifiEditState.band === "2g"
                                ? "2.4 GHz"
                                : wifiEditState.band === "5g"
                                  ? "5 GHz"
                                  : String(wifiEditState.band)}</span
                          >{/if}
                      </div>
                    </div>
                  </div>

                  <!-- SECTION 2: SECURITY -->
                  <div
                    class="wifi-group-card"
                    class:wifi-section-disabled={wifiAdvancedMode === "auto"}
                  >
                    <div class="wifi-group-header">
                      <div class="wifi-group-icon">
                        <svg
                          viewBox="0 0 24 24"
                          fill="none"
                          stroke="currentColor"
                          stroke-width="2"
                          width="16"
                          height="16"
                          ><path
                            d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"
                          /></svg
                        >
                      </div>
                      <div class="wifi-group-title-wrap">
                        <h4 class="wifi-group-title">Security</h4>
                        <span class="wifi-group-desc"
                          >Authentication, encryption, and access control</span
                        >
                      </div>
                    </div>
                    <div class="wifi-group-fields">
                      <!-- Security Protocol -->
                      <div class="wifi-field">
                        <div class="wifi-field-label-row">
                          <span class="wifi-field-label">Security Protocol</span
                          >
                        </div>
                        {#if canEditWifi}<select
                            class="wifi-field-select"
                            value={String(wifiEditState.security ?? "wpapsk")}
                            on:change={(e) =>
                              updateWifiField(
                                "security",
                                e.currentTarget.value,
                              )}
                            ><option value="wpapsk">WPA Personal</option><option
                              value="wpaeap">WPA Enterprise</option
                            ><option value="open">Open (No Security)</option
                            ></select
                          >{:else}<span class="wifi-field-value"
                            >{wifiEditState.security === "wpapsk"
                              ? "WPA Personal"
                              : wifiEditState.security === "wpaeap"
                                ? "WPA Enterprise"
                                : wifiEditState.security === "open"
                                  ? "Open"
                                  : String(wifiEditState.security)}</span
                          >{/if}
                      </div>
                      <!-- WPA Mode -->
                      {#if wifiEditState.security !== "open"}<div
                          class="wifi-field"
                        >
                          <div class="wifi-field-label-row">
                            <span class="wifi-field-label">WPA Version</span>
                          </div>
                          {#if canEditWifi}<select
                              class="wifi-field-select"
                              value={String(wifiEditState.wpaMode ?? "wpa2")}
                              on:change={(e) =>
                                updateWifiField(
                                  "wpaMode",
                                  e.currentTarget.value,
                                )}
                              ><option value="wpa2">WPA2</option><option
                                value="wpa3">WPA3</option
                              ><option value="wpa2wpa3"
                                >WPA2 / WPA3 Mixed</option
                              ></select
                            >{:else}<span class="wifi-field-value"
                              >{wifiEditState.wpaMode === "wpa2"
                                ? "WPA2"
                                : wifiEditState.wpaMode === "wpa3"
                                  ? "WPA3"
                                  : "WPA2/WPA3"}</span
                            >{/if}
                        </div>{/if}
                      <!-- PMF Mode -->
                      {#if wifiEditState.security !== "open"}<div
                          class="wifi-field"
                        >
                          <div class="wifi-field-label-row">
                            <span class="wifi-field-label"
                              >PMF (Protected Management Frames)</span
                            ><span class="wifi-field-hint"
                              >Protects management frames from forgery</span
                            >
                          </div>
                          {#if canEditWifi}<div class="wifi-bubble-select">
                              <button
                                type="button"
                                class="wifi-bubble"
                                class:active={wifiEditState.pmfMode ===
                                  "required"}
                                on:click={() => confirmPmfChange("required")}
                                >Required</button
                              ><button
                                type="button"
                                class="wifi-bubble"
                                class:active={wifiEditState.pmfMode ===
                                  "optional"}
                                on:click={() => confirmPmfChange("optional")}
                                >Optional</button
                              ><button
                                type="button"
                                class="wifi-bubble"
                                class:active={wifiEditState.pmfMode ===
                                  "disabled"}
                                on:click={() =>
                                  updateWifiField("pmfMode", "disabled")}
                                >Disabled</button
                              >
                            </div>{:else}<span class="wifi-field-value"
                              >{wifiEditState.pmfMode === "required"
                                ? "Required"
                                : wifiEditState.pmfMode === "optional"
                                  ? "Optional"
                                  : "Disabled"}</span
                            >{/if}
                        </div>{/if}
                      <!-- Private Pre-Shared Keys -->
                      {#if wifiEditState.security === "wpapsk"}
                        <div class="wifi-field wifi-field-inline">
                          <div class="wifi-field-label-row">
                            <span class="wifi-field-label"
                              >Private Pre-Shared Keys</span
                            ><span class="wifi-field-hint"
                              >Unique per-device passwords</span
                            >
                          </div>
                          {#if canEditWifi}<label class="wifi-toggle"
                              ><input
                                type="checkbox"
                                checked={!!wifiEditState.privatePreSharedKeysEnabled}
                                on:change={(e) => {
                                  updateWifiField(
                                    "privatePreSharedKeysEnabled",
                                    e.currentTarget.checked,
                                  );
                                  if (
                                    e.currentTarget.checked &&
                                    selectedUnifiSite &&
                                    selectedWifi
                                  ) {
                                    loadPPSKs(
                                      selectedUnifiSite.id,
                                      selectedWifi.id,
                                    );
                                  }
                                }}
                              /><span class="wifi-toggle-slider"></span></label
                            >{:else}<span
                              class="wifi-field-value wifi-bool"
                              class:yes={!!wifiEditState.privatePreSharedKeysEnabled}
                              >{wifiEditState.privatePreSharedKeysEnabled
                                ? "Yes"
                                : "No"}</span
                            >{/if}
                        </div>
                        {#if wifiEditState.privatePreSharedKeysEnabled}
                          <div class="wifi-ppsk-section">
                            {#if isLoadingPPSKs}<div class="wifi-ppsk-loading">
                                Loading keys…
                              </div>{:else if wifiPPSKs.length === 0}<div
                                class="wifi-ppsk-empty"
                              >
                                No private PSKs configured
                              </div>{:else}<div class="wifi-ppsk-list">
                                {#each wifiPPSKs as psk, i (psk.name + i)}<div
                                    class="wifi-ppsk-item"
                                  >
                                    <div class="wifi-ppsk-info">
                                      <span class="wifi-ppsk-name"
                                        >{psk.name}</span
                                      >{#if psk.vlanId}<span
                                          class="wifi-ppsk-vlan"
                                          >VLAN {psk.vlanId}</span
                                        >{/if}{#if psk.mac}<span
                                          class="wifi-ppsk-mac">{psk.mac}</span
                                        >{/if}
                                    </div>
                                    <div class="wifi-passphrase-wrap">
                                      <span class="wifi-field-value mono"
                                        >{revealedWifiPassphrases[`ppsk-${i}`]
                                          ? psk.key
                                          : "••••••••"}</span
                                      ><button
                                        class="wifi-reveal-btn"
                                        type="button"
                                        on:click={() => {
                                          revealedWifiPassphrases[`ppsk-${i}`] =
                                            !revealedWifiPassphrases[
                                              `ppsk-${i}`
                                            ];
                                          revealedWifiPassphrases =
                                            revealedWifiPassphrases;
                                        }}
                                        >{#if revealedWifiPassphrases[`ppsk-${i}`]}<svg
                                            viewBox="0 0 24 24"
                                            fill="none"
                                            stroke="currentColor"
                                            stroke-width="2"
                                            width="14"
                                            height="14"
                                            ><path
                                              d="M17.94 17.94A10.07 10.07 0 0112 20c-7 0-11-8-11-8a18.45 18.45 0 015.06-5.94"
                                            /><path
                                              d="M9.9 4.24A9.12 9.12 0 0112 4c7 0 11 8 11 8a18.5 18.5 0 01-2.16 3.19"
                                            /><path
                                              d="M14.12 14.12a3 3 0 11-4.24-4.24"
                                            /><line
                                              x1="1"
                                              y1="1"
                                              x2="23"
                                              y2="23"
                                            /></svg
                                          >{:else}<svg
                                            viewBox="0 0 24 24"
                                            fill="none"
                                            stroke="currentColor"
                                            stroke-width="2"
                                            width="14"
                                            height="14"
                                            ><path
                                              d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"
                                            /><circle
                                              cx="12"
                                              cy="12"
                                              r="3"
                                            /></svg
                                          >{/if}</button
                                      >
                                    </div>
                                  </div>{/each}
                              </div>{/if}
                            {#if canEditWifi}<div class="wifi-ppsk-add">
                                <input
                                  type="text"
                                  class="wifi-field-input"
                                  bind:value={ppskNewName}
                                  placeholder="Name (e.g. John's Laptop)"
                                /><input
                                  type="password"
                                  class="wifi-field-input mono"
                                  bind:value={ppskNewKey}
                                  placeholder="Password (min 8 chars)"
                                /><input
                                  type="text"
                                  class="wifi-field-input"
                                  bind:value={ppskNewVlanId}
                                  placeholder="VLAN (optional)"
                                /><button
                                  class="wifi-btn wifi-btn-primary"
                                  type="button"
                                  on:click={addPPSK}
                                  disabled={!ppskNewName.trim() ||
                                    ppskNewKey.trim().length < 8 ||
                                    isAddingPPSK}
                                  >{isAddingPPSK
                                    ? "Adding…"
                                    : "Add PSK"}</button
                                >
                              </div>{/if}
                          </div>
                        {/if}
                      {/if}
                      <!-- Hide WiFi Name -->
                      <div class="wifi-field wifi-field-inline">
                        <div class="wifi-field-label-row">
                          <span class="wifi-field-label">Hide WiFi Name</span
                          ><span class="wifi-field-hint"
                            >Network won't appear in scan results</span
                          >
                        </div>
                        {#if canEditWifi}<label class="wifi-toggle"
                            ><input
                              type="checkbox"
                              checked={!!wifiEditState.hideSSID}
                              on:change={(e) =>
                                updateWifiField(
                                  "hideSSID",
                                  e.currentTarget.checked,
                                )}
                            /><span class="wifi-toggle-slider"></span></label
                          >{:else}<span
                            class="wifi-field-value wifi-bool"
                            class:yes={!!wifiEditState.hideSSID}
                            >{wifiEditState.hideSSID ? "Yes" : "No"}</span
                          >{/if}
                      </div>
                      <!-- Client Device Isolation -->
                      <div class="wifi-field wifi-field-inline">
                        <div class="wifi-field-label-row">
                          <span class="wifi-field-label"
                            >Client Device Isolation</span
                          ><span class="wifi-field-hint"
                            >Prevent clients from communicating with each other</span
                          >
                        </div>
                        {#if canEditWifi}<label class="wifi-toggle"
                            ><input
                              type="checkbox"
                              checked={!!wifiEditState.l2Isolation}
                              on:change={(e) =>
                                updateWifiField(
                                  "l2Isolation",
                                  e.currentTarget.checked,
                                )}
                            /><span class="wifi-toggle-slider"></span></label
                          >{:else}<span
                            class="wifi-field-value wifi-bool"
                            class:yes={!!wifiEditState.l2Isolation}
                            >{wifiEditState.l2Isolation ? "Yes" : "No"}</span
                          >{/if}
                      </div>
                    </div>
                  </div>

                  <!-- SECTION 3: BEHAVIOR CONTROLS -->
                  <div
                    class="wifi-group-card"
                    class:wifi-section-disabled={wifiAdvancedMode === "auto"}
                  >
                    <div class="wifi-group-header">
                      <div class="wifi-group-icon">
                        <svg
                          viewBox="0 0 24 24"
                          fill="none"
                          stroke="currentColor"
                          stroke-width="2"
                          width="16"
                          height="16"
                          ><circle cx="12" cy="12" r="3" /><path
                            d="M19.4 15a1.65 1.65 0 00.33 1.82l.06.06a2 2 0 010 2.83 2 2 0 01-2.83 0l-.06-.06a1.65 1.65 0 00-1.82-.33 1.65 1.65 0 00-1 1.51V21a2 2 0 01-4 0v-.09A1.65 1.65 0 009 19.4a1.65 1.65 0 00-1.82.33l-.06.06a2 2 0 01-2.83 0 2 2 0 010-2.83l.06-.06A1.65 1.65 0 004.68 15a1.65 1.65 0 00-1.51-1H3a2 2 0 010-4h.09A1.65 1.65 0 004.6 9a1.65 1.65 0 00-.33-1.82l-.06-.06a2 2 0 012.83-2.83l.06.06A1.65 1.65 0 009 4.68a1.65 1.65 0 001-1.51V3a2 2 0 014 0v.09a1.65 1.65 0 001 1.51 1.65 1.65 0 001.82-.33l.06-.06a2 2 0 012.83 2.83l-.06.06A1.65 1.65 0 0019.4 9a1.65 1.65 0 001.51 1H21a2 2 0 010 4h-.09a1.65 1.65 0 00-1.51 1z"
                          /></svg
                        >
                      </div>
                      <div class="wifi-group-title-wrap">
                        <h4 class="wifi-group-title">Behavior Controls</h4>
                        <span class="wifi-group-desc"
                          >Advanced wireless features and optimizations</span
                        >
                      </div>
                    </div>
                    <div class="wifi-group-fields">
                      <div
                        class="wifi-field wifi-field-inline"
                        class:wifi-field-disabled={wifiEditState.band !==
                          "both"}
                      >
                        <div class="wifi-field-label-row">
                          <span class="wifi-field-label">Band Steering</span
                          ><span class="wifi-field-hint"
                            >{wifiEditState.band !== "both"
                              ? "Requires both 2.4 GHz and 5 GHz bands"
                              : "Prefer 5 GHz for dual-band clients"}</span
                          >
                        </div>
                        {#if canEditWifi}<label class="wifi-toggle"
                            ><input
                              type="checkbox"
                              checked={!!wifiEditState.no2ghzOui}
                              disabled={wifiEditState.band !== "both"}
                              on:change={(e) =>
                                updateWifiField(
                                  "no2ghzOui",
                                  e.currentTarget.checked,
                                )}
                            /><span class="wifi-toggle-slider"></span></label
                          >{:else}<span
                            class="wifi-field-value wifi-bool"
                            class:yes={!!wifiEditState.no2ghzOui}
                            >{wifiEditState.no2ghzOui ? "Yes" : "No"}</span
                          >{/if}
                      </div>
                      <div class="wifi-field wifi-field-inline">
                        <div class="wifi-field-label-row">
                          <span class="wifi-field-label">Proxy ARP</span><span
                            class="wifi-field-hint"
                            >AP answers ARP requests on behalf of clients</span
                          >
                        </div>
                        {#if canEditWifi}<label class="wifi-toggle"
                            ><input
                              type="checkbox"
                              checked={!!wifiEditState.proxyArp}
                              on:change={(e) =>
                                updateWifiField(
                                  "proxyArp",
                                  e.currentTarget.checked,
                                )}
                            /><span class="wifi-toggle-slider"></span></label
                          >{:else}<span
                            class="wifi-field-value wifi-bool"
                            class:yes={!!wifiEditState.proxyArp}
                            >{wifiEditState.proxyArp ? "Yes" : "No"}</span
                          >{/if}
                      </div>
                      <div class="wifi-field wifi-field-inline">
                        <div class="wifi-field-label-row">
                          <span class="wifi-field-label"
                            >BSS Transition (802.11v)</span
                          ><span class="wifi-field-hint"
                            >Helps clients find a better AP</span
                          >
                        </div>
                        {#if canEditWifi}<label class="wifi-toggle"
                            ><input
                              type="checkbox"
                              checked={!!wifiEditState.bssTransition}
                              on:change={(e) =>
                                updateWifiField(
                                  "bssTransition",
                                  e.currentTarget.checked,
                                )}
                            /><span class="wifi-toggle-slider"></span></label
                          >{:else}<span
                            class="wifi-field-value wifi-bool"
                            class:yes={!!wifiEditState.bssTransition}
                            >{wifiEditState.bssTransition ? "Yes" : "No"}</span
                          >{/if}
                      </div>
                      <div class="wifi-field wifi-field-inline">
                        <div class="wifi-field-label-row">
                          <span class="wifi-field-label"
                            >U-APSD (Power Save)</span
                          ><span class="wifi-field-hint"
                            >Reduces power consumption on mobile devices</span
                          >
                        </div>
                        {#if canEditWifi}<label class="wifi-toggle"
                            ><input
                              type="checkbox"
                              checked={!!wifiEditState.uapsdEnabled}
                              on:change={(e) =>
                                updateWifiField(
                                  "uapsdEnabled",
                                  e.currentTarget.checked,
                                )}
                            /><span class="wifi-toggle-slider"></span></label
                          >{:else}<span
                            class="wifi-field-value wifi-bool"
                            class:yes={!!wifiEditState.uapsdEnabled}
                            >{wifiEditState.uapsdEnabled ? "Yes" : "No"}</span
                          >{/if}
                      </div>
                      <div class="wifi-field wifi-field-inline">
                        <div class="wifi-field-label-row">
                          <span class="wifi-field-label"
                            >Fast Roaming (802.11r)</span
                          ><span class="wifi-field-hint"
                            >Faster transitions between access points</span
                          >
                        </div>
                        {#if canEditWifi}<label class="wifi-toggle"
                            ><input
                              type="checkbox"
                              checked={!!wifiEditState.fastRoamingEnabled}
                              on:change={(e) =>
                                updateWifiField(
                                  "fastRoamingEnabled",
                                  e.currentTarget.checked,
                                )}
                            /><span class="wifi-toggle-slider"></span></label
                          >{:else}<span
                            class="wifi-field-value wifi-bool"
                            class:yes={!!wifiEditState.fastRoamingEnabled}
                            >{wifiEditState.fastRoamingEnabled
                              ? "Yes"
                              : "No"}</span
                          >{/if}
                      </div>
                      <!-- MAC Address Filter -->
                      <div class="wifi-field wifi-field-inline">
                        <div class="wifi-field-label-row">
                          <span class="wifi-field-label"
                            >MAC Address Filter</span
                          ><span class="wifi-field-hint"
                            >Allow or deny specific devices</span
                          >
                        </div>
                        {#if canEditWifi}<label class="wifi-toggle"
                            ><input
                              type="checkbox"
                              checked={!!wifiEditState.macFilterEnabled}
                              on:change={(e) =>
                                updateWifiField(
                                  "macFilterEnabled",
                                  e.currentTarget.checked,
                                )}
                            /><span class="wifi-toggle-slider"></span></label
                          >{:else}<span
                            class="wifi-field-value wifi-bool"
                            class:yes={!!wifiEditState.macFilterEnabled}
                            >{wifiEditState.macFilterEnabled
                              ? "Yes"
                              : "No"}</span
                          >{/if}
                      </div>
                      {#if wifiEditState.macFilterEnabled}
                        <div class="wifi-sub-section">
                          <div class="wifi-field">
                            <div class="wifi-field-label-row">
                              <span class="wifi-field-label">Filter Type</span>
                            </div>
                            {#if canEditWifi}<div class="wifi-bubble-select">
                                <button
                                  type="button"
                                  class="wifi-bubble"
                                  class:active={wifiEditState.macFilterPolicy ===
                                    "allow"}
                                  on:click={() =>
                                    updateWifiField("macFilterPolicy", "allow")}
                                  >Allow</button
                                ><button
                                  type="button"
                                  class="wifi-bubble"
                                  class:active={wifiEditState.macFilterPolicy ===
                                    "deny"}
                                  on:click={() =>
                                    updateWifiField("macFilterPolicy", "deny")}
                                  >Deny</button
                                >
                              </div>{:else}<span class="wifi-field-value"
                                >{wifiEditState.macFilterPolicy === "allow"
                                  ? "Allow List"
                                  : "Deny List"}</span
                              >{/if}
                          </div>
                          {#if canEditWifi}<div class="wifi-mac-add">
                              <input
                                type="text"
                                class="wifi-field-input mono"
                                bind:value={macFilterNewMac}
                                placeholder="AA:BB:CC:DD:EE:FF"
                                on:keydown={(e) => {
                                  if (e.key === "Enter") addMacToFilterList();
                                }}
                              /><button
                                class="wifi-btn wifi-btn-primary"
                                type="button"
                                on:click={addMacToFilterList}
                                disabled={!macFilterNewMac.trim()}>Add</button
                              >
                            </div>{/if}
                          {#if Array.isArray(wifiEditState.macFilterList) && (wifiEditState.macFilterList as string[]).length > 0}<div
                              class="wifi-mac-list"
                            >
                              {#each wifiEditState.macFilterList as string[] as mac}<div
                                  class="wifi-mac-item"
                                >
                                  <span class="mono">{mac}</span
                                  >{#if canEditWifi}<button
                                      class="wifi-mac-remove"
                                      type="button"
                                      on:click={() =>
                                        removeMacFromFilterList(mac)}
                                      title="Remove">×</button
                                    >{/if}
                                </div>{/each}
                            </div>{:else}<div class="wifi-ppsk-empty">
                              No MAC addresses added
                            </div>{/if}
                        </div>
                      {/if}
                      <!-- RADIUS MAC Authentication -->
                      <div class="wifi-field wifi-field-inline">
                        <div class="wifi-field-label-row">
                          <span class="wifi-field-label"
                            >RADIUS MAC Authentication</span
                          ><span class="wifi-field-hint"
                            >Authenticate clients by MAC address via RADIUS</span
                          >
                        </div>
                        {#if canEditWifi}<label class="wifi-toggle"
                            ><input
                              type="checkbox"
                              checked={!!wifiEditState.radiusMacAuthEnabled}
                              on:change={(e) =>
                                updateWifiField(
                                  "radiusMacAuthEnabled",
                                  e.currentTarget.checked,
                                )}
                            /><span class="wifi-toggle-slider"></span></label
                          >{:else}<span
                            class="wifi-field-value wifi-bool"
                            class:yes={!!wifiEditState.radiusMacAuthEnabled}
                            >{wifiEditState.radiusMacAuthEnabled
                              ? "Yes"
                              : "No"}</span
                          >{/if}
                      </div>
                      {#if wifiEditState.radiusMacAuthEnabled}<div
                          class="wifi-sub-section"
                        >
                          <div class="wifi-field">
                            <div class="wifi-field-label-row">
                              <span class="wifi-field-label"
                                >MAC Address Format</span
                              ><span class="wifi-field-hint"
                                >Format used when sending MAC to RADIUS</span
                              >
                            </div>
                            {#if canEditWifi}<select
                                class="wifi-field-select"
                                value={String(
                                  wifiEditState.radiusMacaclFormat ??
                                    "none_lower",
                                )}
                                on:change={(e) =>
                                  updateWifiField(
                                    "radiusMacaclFormat",
                                    e.currentTarget.value,
                                  )}
                                ><option value="none_lower">aabbccddeeff</option
                                ><option value="colon_lower"
                                  >aa:bb:cc:dd:ee:ff</option
                                ><option value="dash_lower"
                                  >aa-bb-cc-dd-ee-ff</option
                                ><option value="colon_upper"
                                  >AA:BB:CC:DD:EE:FF</option
                                ><option value="dash_upper"
                                  >AA-BB-CC-DD-EE-FF</option
                                ></select
                              >{:else}<span class="wifi-field-value mono"
                                >{wifiEditState.radiusMacaclFormat ?? "—"}</span
                              >{/if}
                          </div>
                        </div>{/if}
                      <!-- WiFi Speed Limit -->
                      <div class="wifi-field wifi-field-inline">
                        <div class="wifi-field-label-row">
                          <span class="wifi-field-label">WiFi Speed Limit</span
                          ><span class="wifi-field-hint"
                            >Apply a bandwidth profile to clients on this
                            network</span
                          >
                        </div>
                        {#if canEditWifi}<label class="wifi-toggle"
                            ><input
                              type="checkbox"
                              checked={!!wifiEditState.usergroupId &&
                                wifiEditState.usergroupId !==
                                  unifiSpeedProfiles.find(
                                    (p) => p.downloadLimitKbps === -1,
                                  )?.id}
                              on:change={(e) => {
                                if (!e.currentTarget.checked) {
                                  const defaultProfile =
                                    unifiSpeedProfiles.find(
                                      (p) => p.downloadLimitKbps === -1,
                                    );
                                  updateWifiField(
                                    "usergroupId",
                                    defaultProfile?.id ?? "",
                                  );
                                } else {
                                  const firstLimited = unifiSpeedProfiles.find(
                                    (p) => p.downloadLimitKbps !== -1,
                                  );
                                  if (firstLimited)
                                    updateWifiField(
                                      "usergroupId",
                                      firstLimited.id,
                                    );
                                }
                              }}
                            /><span class="wifi-toggle-slider"></span></label
                          >{:else}{@const profile = unifiSpeedProfiles.find(
                            (p) => p.id === String(wifiEditState.usergroupId),
                          )}<span
                            class="wifi-field-value wifi-bool"
                            class:yes={profile &&
                              profile.downloadLimitKbps !== -1}
                            >{profile && profile.downloadLimitKbps !== -1
                              ? "Yes"
                              : "No"}</span
                          >{/if}
                      </div>
                      {#if wifiEditState.usergroupId && wifiEditState.usergroupId !== unifiSpeedProfiles.find((p) => p.downloadLimitKbps === -1)?.id}<div
                          class="wifi-sub-section"
                        >
                          <div class="wifi-field">
                            <div class="wifi-field-label-row">
                              <span class="wifi-field-label">Speed Profile</span
                              >
                            </div>
                            {#if canEditWifi}<div class="wifi-speed-row">
                                <select
                                  class="wifi-field-select"
                                  value={String(
                                    wifiEditState.usergroupId ?? "",
                                  )}
                                  on:change={(e) =>
                                    updateWifiField(
                                      "usergroupId",
                                      e.currentTarget.value,
                                    )}
                                  >{#each unifiSpeedProfiles.filter((p) => p.downloadLimitKbps !== -1) as profile}<option
                                      value={profile.id}
                                      >{profile.name} (↓{profile.downloadLimitKbps}
                                      / ↑{profile.uploadLimitKbps} Kbps)</option
                                    >{/each}</select
                                ><button
                                  class="wifi-btn wifi-btn-ghost"
                                  type="button"
                                  on:click={() => {
                                    showSpeedProfileModal = true;
                                  }}
                                  title="Create new speed profile">+</button
                                >
                              </div>{:else}{@const profile =
                                unifiSpeedProfiles.find(
                                  (p) =>
                                    p.id === String(wifiEditState.usergroupId),
                                )}<span class="wifi-field-value"
                                >{profile ? profile.name : "—"}</span
                              >{/if}
                          </div>
                        </div>{/if}
                      <!-- Auto DTIM Period -->
                      <div class="wifi-field wifi-field-inline">
                        <div class="wifi-field-label-row">
                          <span class="wifi-field-label">Auto DTIM Period</span
                          ><span class="wifi-field-hint"
                            >When enabled, DTIM is automatically managed</span
                          >
                        </div>
                        {#if canEditWifi}<label class="wifi-toggle"
                            ><input
                              type="checkbox"
                              checked={wifiEditState.dtimMode === "default"}
                              on:change={(e) =>
                                updateWifiField(
                                  "dtimMode",
                                  e.currentTarget.checked
                                    ? "default"
                                    : "custom",
                                )}
                            /><span class="wifi-toggle-slider"></span></label
                          >{:else}<span
                            class="wifi-field-value wifi-bool"
                            class:yes={wifiEditState.dtimMode === "default"}
                            >{wifiEditState.dtimMode === "default"
                              ? "Auto"
                              : "Custom"}</span
                          >{/if}
                      </div>
                      {#if wifiEditState.dtimMode !== "default"}<div
                          class="wifi-sub-section"
                        >
                          <div class="wifi-dtim-inline">
                            <label class="wifi-dtim-field"
                              ><span>2.4 GHz</span><input
                                type="number"
                                class="wifi-field-input"
                                value={wifiEditState.dtimNg ?? 1}
                                on:input={(e) =>
                                  updateWifiField(
                                    "dtimNg",
                                    Number(e.currentTarget.value),
                                  )}
                                min="1"
                              /></label
                            ><label class="wifi-dtim-field"
                              ><span>5 GHz</span><input
                                type="number"
                                class="wifi-field-input"
                                value={wifiEditState.dtimNa ?? 3}
                                on:input={(e) =>
                                  updateWifiField(
                                    "dtimNa",
                                    Number(e.currentTarget.value),
                                  )}
                                min="1"
                              /></label
                            ><label class="wifi-dtim-field"
                              ><span>6 GHz</span><input
                                type="number"
                                class="wifi-field-input"
                                value={wifiEditState.dtim6e ?? 3}
                                on:input={(e) =>
                                  updateWifiField(
                                    "dtim6e",
                                    Number(e.currentTarget.value),
                                  )}
                                min="1"
                              /></label
                            >
                          </div>
                        </div>{/if}
                      <!-- Group Key Interval -->
                      <div class="wifi-field wifi-field-inline">
                        <div class="wifi-field-label-row">
                          <span class="wifi-field-label"
                            >Group Key Interval</span
                          ><span class="wifi-field-hint"
                            >Periodic group key rotation for enhanced security</span
                          >
                        </div>
                        {#if canEditWifi}{@const gkiValue =
                            Number(wifiEditState.groupRekey) || 0}
                          <div class="wifi-gki-row">
                            {#if gkiValue > 0}<div class="wifi-inline-number">
                                <input
                                  type="number"
                                  class="wifi-field-input"
                                  value={wifiEditState.groupRekey}
                                  on:input={(e) =>
                                    updateWifiField(
                                      "groupRekey",
                                      Number(e.currentTarget.value),
                                    )}
                                  min="1"
                                /><span class="wifi-inline-unit">sec</span>
                              </div>{/if}<label class="wifi-toggle"
                              ><input
                                type="checkbox"
                                checked={gkiValue > 0}
                                on:change={(e) => {
                                  updateWifiField(
                                    "groupRekey",
                                    e.currentTarget.checked ? 3600 : 0,
                                  );
                                }}
                              /><span class="wifi-toggle-slider"></span></label
                            >
                          </div>{:else}{@const gkiValue =
                            Number(wifiEditState.groupRekey) || 0}<span
                            class="wifi-field-value wifi-bool"
                            class:yes={gkiValue > 0}
                            >{gkiValue > 0
                              ? `${wifiEditState.groupRekey}s`
                              : "Off"}</span
                          >{/if}
                      </div>
                      <!-- Multicast Enhancement -->
                      <div class="wifi-field wifi-field-inline">
                        <div class="wifi-field-label-row">
                          <span class="wifi-field-label"
                            >Multicast Enhancement</span
                          ><span class="wifi-field-hint"
                            >Converts multicast to unicast for better
                            performance</span
                          >
                        </div>
                        {#if canEditWifi}<label class="wifi-toggle"
                            ><input
                              type="checkbox"
                              checked={!!wifiEditState.mcastenhanceEnabled}
                              on:change={(e) =>
                                updateWifiField(
                                  "mcastenhanceEnabled",
                                  e.currentTarget.checked,
                                )}
                            /><span class="wifi-toggle-slider"></span></label
                          >{:else}<span
                            class="wifi-field-value wifi-bool"
                            class:yes={!!wifiEditState.mcastenhanceEnabled}
                            >{wifiEditState.mcastenhanceEnabled
                              ? "Yes"
                              : "No"}</span
                          >{/if}
                      </div>
                      <!-- WiFi Blackout Schedule -->
                      <div
                        class="wifi-field wifi-field-inline wifi-field-disabled"
                        title="WiFi Blackout Schedule is not yet implemented"
                      >
                        <div class="wifi-field-label-row">
                          <span class="wifi-field-label"
                            >WiFi Blackout Schedule</span
                          ><span class="wifi-field-hint"
                            >Schedule times when this network is disabled <span
                              class="wifi-info-bubble"
                              title="This feature is not yet implemented in the UI. Contact your administrator to configure via the UniFi controller."
                              >ℹ️</span
                            ></span
                          >
                        </div>
                        <span class="wifi-todo-badge">TODO</span>
                      </div>
                    </div>
                  </div>
                </div>
              {:else}
                <div class="wifi-detail-placeholder">
                  <svg
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    stroke-width="1.5"
                    width="40"
                    height="40"
                    ><path d="M5 12.55a11 11 0 0114.08 0" /><path
                      d="M1.42 9a16 16 0 0121.16 0"
                    /><path d="M8.53 16.11a6 6 0 016.95 0" /><line
                      x1="12"
                      y1="20"
                      x2="12.01"
                      y2="20"
                    /></svg
                  >
                  <p>Select a network to view and edit settings</p>
                </div>
              {/if}
            </div>
          </div>
        {/if}
      {:else if unifiManagementTab === "networks"}
        {#if isLoadingUnifiNetworks}
          <div class="unifi-loading">
            <svg viewBox="0 0 24 24" width="20" height="20" class="spin-icon"
              ><circle
                cx="12"
                cy="12"
                r="10"
                stroke="currentColor"
                stroke-width="3"
                fill="none"
                opacity="0.25"
              /><path
                d="M12 2a10 10 0 0 1 10 10"
                stroke="currentColor"
                stroke-width="3"
                fill="none"
                stroke-linecap="round"
              /></svg
            >
            <span>Loading networks…</span>
          </div>
        {:else if unifiSiteNetworks.length === 0}
          <div class="unifi-empty-state">
            <svg
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="1.5"
              width="32"
              height="32"
              ><rect x="1" y="4" width="22" height="16" rx="2" ry="2" /><line
                x1="1"
                y1="10"
                x2="23"
                y2="10"
              /></svg
            >
            <p>No networks found</p>
          </div>
        {:else}
          <div class="unifi-networks-list">
            {#each unifiSiteNetworks as network (network.id)}
              <div class="unifi-network-card">
                <div class="unifi-network-header">
                  <span class="unifi-network-name">{network.name}</span>
                  <div class="unifi-network-badges">
                    <span class="unifi-wifi-badge">{network.purpose}</span>
                    {#if network.vlanId}<span class="unifi-wifi-badge"
                        >VLAN {network.vlanId}</span
                      >{/if}
                    {#if !network.enabled}<span
                        class="unifi-wifi-badge disabled-badge">Disabled</span
                      >{/if}
                  </div>
                </div>
                <div class="unifi-network-details">
                  {#if network.subnet}<div class="unifi-device-detail">
                      <span class="unifi-device-label">Subnet</span><span
                        class="unifi-device-value mono">{network.subnet}</span
                      >
                    </div>{/if}
                  {#if network.dhcpEnabled}<div class="unifi-device-detail">
                      <span class="unifi-device-label">DHCP Range</span><span
                        class="unifi-device-value mono"
                        >{network.dhcpStart} – {network.dhcpStop}</span
                      >
                    </div>{/if}
                </div>
              </div>
            {/each}
          </div>
        {/if}
      {/if}
    </div>
  </div>
{:else}
  <!-- Site cards grid -->
  {#if unifiSites.length === 0}
    <div class="tab-empty">
      <svg
        viewBox="0 0 24 24"
        fill="none"
        stroke="currentColor"
        stroke-width="1.5"
        class="tab-empty-icon"
        ><path d="M12 2L2 7l10 5 10-5-10-5z" /><path d="M2 17l10 5 10-5" /><path
          d="M2 12l10 5 10-5"
        /></svg
      >
      <p>No UniFi sites linked to this company</p>
      <button
        type="button"
        class="create-credential-btn"
        on:click={() => (isLinkUnifiOpen = true)}
      >
        <svg
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          stroke-width="2"
          width="14"
          height="14"
          ><path
            d="M10 13a5 5 0 007.54.54l3-3a5 5 0 00-7.07-7.07l-1.72 1.71"
          /><path
            d="M14 11a5 5 0 00-7.54-.54l-3 3a5 5 0 007.07 7.07l1.71-1.71"
          /></svg
        >
        Link Site
      </button>
    </div>
  {:else}
    <div class="unifi-sites-grid">
      {#each unifiSites as site (site.id)}
        <!-- svelte-ignore a11y_no_static_element_interactions -->
        <div
          class="unifi-site-card"
          on:click={() => selectUnifiSite(site)}
          on:keydown={(e) => e.key === "Enter" && selectUnifiSite(site)}
          role="button"
          tabindex="0"
        >
          <div class="unifi-site-card-top">
            <div class="unifi-site-card-info">
              <span class="unifi-site-card-name">{site.name}</span><span
                class="unifi-site-card-id">{site.siteId}</span
              >
            </div>
            {#if siteOverviews[site.id]}
              {@const health = getCardHealthStatus(site.id)}
              <span
                class="unifi-site-card-status"
                class:status-ok={health === "ok"}
                class:status-warn={health === "warn"}
                class:status-error={health === "error"}
                class:status-unknown={health === "unknown"}
              >
                <span class="status-dot"></span>
                {health === "ok"
                  ? "Healthy"
                  : health === "warn"
                    ? "Warning"
                    : health === "error"
                      ? "Error"
                      : "Unknown"}
              </span>
            {:else}
              <span class="unifi-site-card-status status-loading"
                ><svg
                  viewBox="0 0 24 24"
                  width="12"
                  height="12"
                  class="spin-icon"
                  ><circle
                    cx="12"
                    cy="12"
                    r="10"
                    stroke="currentColor"
                    stroke-width="3"
                    fill="none"
                    opacity="0.25"
                  /><path
                    d="M12 2a10 10 0 0 1 10 10"
                    stroke="currentColor"
                    stroke-width="3"
                    fill="none"
                    stroke-linecap="round"
                  /></svg
                ></span
              >
            {/if}
          </div>
          <div class="unifi-site-card-stats">
            {#if siteOverviews[site.id]}
              <div class="unifi-card-stat">
                <span class="unifi-card-stat-value"
                  >{getCardDeviceCount(site.id)}</span
                ><span class="unifi-card-stat-label">Devices</span>
              </div>
              <div class="unifi-card-stat">
                <span class="unifi-card-stat-value"
                  >{getCardGatewayCount(site.id)}</span
                ><span class="unifi-card-stat-label">Gateways</span>
              </div>
              <div class="unifi-card-stat">
                <span class="unifi-card-stat-value"
                  >{siteOverviews[site.id]?.health?.length ?? 0}</span
                ><span class="unifi-card-stat-label">Subsystems</span>
              </div>
            {:else}
              <div class="unifi-card-stats-loading">
                <span class="unifi-card-stat-placeholder"></span><span
                  class="unifi-card-stat-placeholder"
                ></span><span class="unifi-card-stat-placeholder"></span>
              </div>
            {/if}
          </div>
          <div class="unifi-site-card-arrow">
            <svg
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="2"
              width="14"
              height="14"><polyline points="9 18 15 12 9 6" /></svg
            >
          </div>
        </div>
      {/each}
    </div>
  {/if}
{/if}
