document.addEventListener("DOMContentLoaded", function () {
  const loadingRowHtml = `<tr><td colspan="5" class="text-center"><div class="spinner-border text-primary" role="status"><span class="visually-hidden">Loading...</span></div></td></tr>`;
  document.getElementById("dampenedTableBodyIpv4").innerHTML = loadingRowHtml;
  document.getElementById("dampenedTableBodyIpv6").innerHTML = loadingRowHtml;
  fetchDampenedData();
});

function filterTable(searchInputId, tableId) {
  const filter = document.getElementById(searchInputId).value.toUpperCase();
  const rows = document.getElementById(tableId).tBodies[0].rows;

  for (let i = 0; i < rows.length; i++) {
    let display = "none";
    for (const cell of rows[i].getElementsByTagName("td")) {
      if (cell.textContent.toUpperCase().includes(filter)) {
        display = "";
        break;
      }
    }
    rows[i].style.display = display;
  }
}

function sortTable(tableId, columnIndex, th) {
  const tbody = document.getElementById(tableId).tBodies[0];
  const rows = Array.from(tbody.rows);
  const headers = Array.from(th.parentNode.children);

  headers.forEach((h) => {
    if (h !== th) {
      h.classList.remove("asc", "desc");
      h.dataset.sortState = "none";
    }
  });

  const currentState = th.dataset.sortState || "none";
  const newState = currentState === "none" ? "asc" : currentState === "asc" ? "desc" : "none";
  th.dataset.sortState = newState;

  th.classList.remove("asc", "desc");
  if (newState !== "none") {
    th.classList.add(newState);
  }

  if (newState === "none") {
    rows.sort((a, b) => a.dataset.index - b.dataset.index);
  } else {
    rows.sort((a, b) => {
      const aText = a.cells[columnIndex].textContent.trim();
      const bText = b.cells[columnIndex].textContent.trim();
      let compare;
      
      if (!isNaN(aText) && !isNaN(bText)) {
        compare = parseFloat(aText) - parseFloat(bText);
      } else {
        compare = aText.localeCompare(bText, undefined, { numeric: true });
      }
      return newState === "asc" ? compare : -compare;
    });
  }

  rows.forEach((row) => tbody.appendChild(row));
}

function toggleRefresh(loading) {
  const buttons = [
    { btn: "refreshButton", icon: "refreshIcon", spinner: "refreshSpinner" },
    { btn: "refreshButton2", icon: "refreshIcon2", spinner: "refreshSpinner2" }
  ];

  buttons.forEach(b => {
    const btnEl = document.getElementById(b.btn);
    const iconEl = document.getElementById(b.icon);
    const spinnerEl = document.getElementById(b.spinner);

    if (btnEl) btnEl.disabled = loading;
    if (iconEl) iconEl.classList.toggle("d-none", loading);
    if (spinnerEl) spinnerEl.classList.toggle("d-none", !loading);
  });
}

function refreshDampenedTable() {
  document.getElementById("dampenedSearchIpv4").value = "";
  document.getElementById("dampenedSearchIpv6").value = "";
  filterTable('dampenedSearchIpv4', 'dampenedTableIpv4');
  filterTable('dampenedSearchIpv6', 'dampenedTableIpv6');

  toggleRefresh(true);
  fetchDampenedData().finally(() => {
    toggleRefresh(false);
  });
}

function populateTable(tableBodyId, summaryId, data) {
  const tableBody = document.getElementById(tableBodyId);
  const summaryElement = document.getElementById(summaryId);
  
  tableBody.innerHTML = "";
  summaryElement.textContent = data.summary || "";

  const paths = data.paths;
  if (paths && paths.length > 0) {
    paths.forEach((path, index) => {
      let row = tableBody.insertRow();
      row.dataset.index = index;
      
      row.insertCell(0).textContent = path.status;

      const prefixCell = row.insertCell(1);
      prefixCell.innerHTML = `<a href="https://bgp.tools/search?q=${path.prefix}" target="_blank">${path.prefix}</a>`;
      
      row.insertCell(2).textContent = path.from;
      row.insertCell(3).textContent = path.suppress_remain;

      const pathCell = row.insertCell(4);
      const pathLinks = path.path.split(' ').map(part => {
        if (!isNaN(parseInt(part, 10))) {
          return `<a href="https://bgp.tools/search?q=${part}" target="_blank">${part}</a>`;
        }
        return part;
      }).join(' ');
      pathCell.innerHTML = pathLinks;
      pathCell.style.wordBreak = "break-all";
    });
  } else {
    let row = tableBody.insertRow();
    let cell = row.insertCell(0);
    cell.colSpan = 5;
    cell.textContent = "No dampened routes found.";
    cell.className = "text-center";
  }
}

async function fetchDampenedData() {
  try {
    const response = await fetch("/bgp/dampened/json");
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    const data = await response.json();
    
    populateTable("dampenedTableBodyIpv4", "dampened-summary-ipv4", data.ipv4);
    populateTable("dampenedTableBodyIpv6", "dampened-summary-ipv6", data.ipv6);

  } catch (error) {
    console.error("Error fetching dampened routes:", error);
    const errorRowHtml = `<tr><td colspan="5" class="text-center text-danger">Error loading data. Please try again.</td></tr>`;
    document.getElementById("dampenedTableBodyIpv4").innerHTML = errorRowHtml;
    document.getElementById("dampenedTableBodyIpv6").innerHTML = errorRowHtml;
  }
}