// Connection Settings JavaScript

// Import loading manager
if (!window.loadingManager) {
  const script = document.createElement("script");
  script.src = "./components/loading-states.js";
  document.head.appendChild(script);
}

let connectionSettings = {
  mode: "auto",
  network: {
    port: 51823,
    bindAddress: "0.0.0.0",
    enableIPv6: true,
  },
  remoteAccess: {
    enabled: false,
    method: "cloudflare",
    externalPort: 51823,
    externalUrl: "",
  },
  security: {
    requireAuth: true,
    enableCORS: true,
    allowedOrigins: ["*"],
  },
  performance: {
    enableCompression: true,
    enableCache: true,
    maxStreams: 10,
    bufferSize: 1048576,
  },
  discovery: {
    enableMDNS: true,
    enableUPnP: true,
    broadcastName: "SOUND",
  },
};

// Initialize connection settings
async function initializeConnectionSettings() {
  console.log("Initializing connection settings...");

  // Show loading state
  if (window.loadingManager) {
    window.loadingManager.showLoader("init", "Loading connection settings...");
  }

  try {
    // Load current settings
    const settings = await window.electronAPI.getConnectionSettings();
    if (settings) {
      connectionSettings = { ...connectionSettings, ...settings };
      updateUI();
    }

    // Update status
    await updateConnectionStatus();

    // Start periodic status updates
    setInterval(updateConnectionStatus, 5000);

    // Hide loading state
    if (window.loadingManager) {
      window.loadingManager.hideLoader("init");
    }
  } catch (error) {
    console.error("Failed to initialize connection settings:", error);
    // Hide loading state on error
    if (window.loadingManager) {
      window.loadingManager.hideLoader("init");
    }
  }
}

// Update UI with current settings (Read-only mode)
function updateUI() {
  // Connection mode - Display only
  const modeText =
    connectionSettings.mode.charAt(0).toUpperCase() + connectionSettings.mode.slice(1);
  document.getElementById("connection-mode-display").textContent = modeText;

  // Network settings - Display only
  document.getElementById("server-port-display").textContent = connectionSettings.network.port;
  document.getElementById("bind-address-display").textContent =
    connectionSettings.network.bindAddress === "0.0.0.0"
      ? "All interfaces (0.0.0.0)"
      : "Localhost only (127.0.0.1)";
  document.getElementById("enable-ipv6-display").textContent = connectionSettings.network.enableIPv6
    ? "Enabled"
    : "Disabled";

  // Remote access - Display only
  document.getElementById("remote-access-display").textContent = connectionSettings.remoteAccess
    .enabled
    ? "Enabled"
    : "Disabled";
  if (connectionSettings.remoteAccess.enabled) {
    document.getElementById("remote-method-display").textContent =
      connectionSettings.remoteAccess.method;
    document.getElementById("remote-details").style.display = "block";
  } else {
    document.getElementById("remote-details").style.display = "none";
  }

  // Security - Display only
  document.getElementById("require-auth-display").textContent = connectionSettings.security
    .requireAuth
    ? "Required"
    : "Not Required";
  document.getElementById("enable-cors-display").textContent = connectionSettings.security
    .enableCORS
    ? "Enabled"
    : "Disabled";
  document.getElementById("allowed-origins-display").textContent =
    connectionSettings.security.allowedOrigins.join(", ");

  // Performance - Display only
  document.getElementById("enable-compression-display").textContent = connectionSettings.performance
    .enableCompression
    ? "Enabled"
    : "Disabled";
  document.getElementById("enable-cache-display").textContent = connectionSettings.performance
    .enableCache
    ? "Enabled"
    : "Disabled";
  document.getElementById("max-streams-display").textContent =
    connectionSettings.performance.maxStreams;
  document.getElementById("buffer-size-display").textContent = formatBufferSize(
    connectionSettings.performance.bufferSize,
  );

  // Discovery - Display only
  document.getElementById("enable-mdns-display").textContent = connectionSettings.discovery
    .enableMDNS
    ? "Enabled"
    : "Disabled";
  document.getElementById("enable-upnp-discovery-display").textContent = connectionSettings
    .discovery.enableUPnP
    ? "Enabled"
    : "Disabled";
  document.getElementById("broadcast-name-display").textContent =
    connectionSettings.discovery.broadcastName;
}

// Format buffer size for display
function formatBufferSize(bytes) {
  if (bytes >= 1048576) return bytes / 1048576 + " MB";
  if (bytes >= 1024) return bytes / 1024 + " KB";
  return bytes + " bytes";
}

// Update connection status display
async function updateConnectionStatus() {
  try {
    const status = await window.electronAPI.getConnectionStatus();

    // Local access
    document.getElementById("local-access-status").textContent =
      `http://localhost:${connectionSettings.network.port}`;

    // Remote access
    if (status.remoteUrl) {
      document.getElementById("remote-access-status").textContent = "Connected";
      document.getElementById("remote-access-status").classList.add("active");
      document.getElementById("tunnel-url").value = status.remoteUrl;
      document.getElementById("tunnel-url-group").style.display = "block";
    } else if (connectionSettings.remoteAccess.enabled) {
      document.getElementById("remote-access-status").textContent = "Configuring...";
      document.getElementById("remote-access-status").classList.remove("active", "error");
    } else {
      document.getElementById("remote-access-status").textContent = "Disabled";
      document.getElementById("remote-access-status").classList.remove("active", "error");
    }

    // Connection mode
    document.getElementById("connection-mode").textContent =
      connectionSettings.mode.charAt(0).toUpperCase() + connectionSettings.mode.slice(1);

    // Active clients
    document.getElementById("active-clients").textContent = status.activeClients || 0;
  } catch (error) {
    console.error("Failed to update connection status:", error);
  }
}

// Connection mode change - Removed in read-only mode

// Network settings - Removed in read-only mode

// Toggle remote access - Removed in read-only mode

// Update remote access method - Removed in read-only mode

// Copy remote URL
function copyRemoteUrl() {
  const url = document.getElementById("tunnel-url").value;
  if (url) {
    navigator.clipboard.writeText(url);
    showStatus("Remote URL copied to clipboard", "success");
  }
}

// Configure UPnP - Removed in read-only mode

// Security settings - Removed in read-only mode

// Performance settings - Removed in read-only mode

// Discovery settings - Removed in read-only mode

// Save all connection settings - Removed in read-only mode

// Reset to default settings - Removed in read-only mode

// Show status message
function showStatus(message, type = "info") {
  const statusEl = document.getElementById("status-message");
  if (!statusEl) return;

  statusEl.textContent = message;
  statusEl.className = `alert alert-${type}`;
  statusEl.style.display = "flex";

  if (type !== "error") {
    setTimeout(() => {
      statusEl.style.display = "none";
    }, 5000);
  }
}

// Initialize when ready
if (document.readyState === "loading") {
  document.addEventListener("DOMContentLoaded", initializeConnectionSettings);
} else {
  initializeConnectionSettings();
}
