// Store Settings Page JavaScript

// Back button functionality
function goBack() {
  if (window.history.length > 1) {
    window.history.back();
  } else {
    window.location.href = "";
  }
}

// Search functionality
document.addEventListener("DOMContentLoaded", function () {
  const searchInput = document.getElementById("searchInput");

  if (searchInput) {
    searchInput.addEventListener("input", function (e) {
      const searchQuery = e.target.value.toLowerCase().trim();

      // Get all settings cards
      const settingsCards = document.querySelectorAll(".settings-grid .col-12");
      // Get all integration cards
      const integrationCards = document.querySelectorAll(
        ".integrations-grid .col-12"
      );

      // Filter settings cards
      settingsCards.forEach((cardCol) => {
        const card = cardCol.querySelector(".settings-card");
        const title = card
          .querySelector(".card-title")
          .textContent.toLowerCase();
        const description = card
          .querySelector(".card-description")
          .textContent.toLowerCase();

        if (
          title.includes(searchQuery) ||
          description.includes(searchQuery) ||
          searchQuery === ""
        ) {
          cardCol.style.display = "";
        } else {
          cardCol.style.display = "none";
        }
      });

      // Filter integration cards
      integrationCards.forEach((cardCol) => {
        const card = cardCol.querySelector(".integration-card");
        const title = card
          .querySelector(".integration-name")
          .textContent.toLowerCase();
        const description = card
          .querySelector(".integration-description")
          .textContent.toLowerCase();

        if (
          title.includes(searchQuery) ||
          description.includes(searchQuery) ||
          searchQuery === ""
        ) {
          cardCol.style.display = "";
        } else {
          cardCol.style.display = "none";
        }
      });
    });
  }

  // Integration connect/disconnect functionality
  const integrationCards = document.querySelectorAll(".integration-card");

  integrationCards.forEach((card) => {
    const connectBtn = card.querySelector(".connect-btn");
    const disconnectBtn = card.querySelector(".disconnect-btn");

    // Handle Connect button click
    if (connectBtn) {
      connectBtn.addEventListener("click", function () {
        // Create connected status elements
        const connectedStatus = document.createElement("div");
        connectedStatus.className = "connected-status";

        const badge = document.createElement("span");
        badge.className = "badge connected-badge mb-2";
        badge.innerHTML =
          '<i class="fas fa-circle me-1" style="font-size: 0.5rem"></i> Connected';

        const newDisconnectBtn = document.createElement("button");
        newDisconnectBtn.className = "btn disconnect-btn";
        newDisconnectBtn.textContent = "Disconnect";

        connectedStatus.appendChild(badge);
        connectedStatus.appendChild(newDisconnectBtn);

        // Replace connect button with connected status
        connectBtn.replaceWith(connectedStatus);

        // Add event listener to new disconnect button
        newDisconnectBtn.addEventListener("click", function () {
          // Show confirmation dialog
          const integrationName =
            card.querySelector(".integration-name").textContent;
          if (
            confirm(`Are you sure you want to disconnect ${integrationName}?`)
          ) {
            // Create new connect button
            const newConnectBtn = document.createElement("button");
            newConnectBtn.className = "btn connect-btn";
            newConnectBtn.innerHTML =
              'Connect <i class="fas fa-arrow-right ms-2"></i>';

            // Replace connected status with connect button
            connectedStatus.replaceWith(newConnectBtn);

            // Add event listener to new connect button
            newConnectBtn.addEventListener("click", function () {
              // Recursively handle connect (reuse the same logic)
              newConnectBtn.click();
            });

            // Re-attach the connect handler
            attachConnectHandler(newConnectBtn, card);
          }
        });
      });
    }

    // Handle Disconnect button click
    if (disconnectBtn) {
      disconnectBtn.addEventListener("click", function () {
        const integrationName =
          card.querySelector(".integration-name").textContent;
        if (
          confirm(`Are you sure you want to disconnect ${integrationName}?`)
        ) {
          const connectedStatus = card.querySelector(".connected-status");

          // Create new connect button
          const newConnectBtn = document.createElement("button");
          newConnectBtn.className = "btn connect-btn";
          newConnectBtn.innerHTML =
            'Connect <i class="fas fa-arrow-right ms-2"></i>';

          // Replace connected status with connect button
          connectedStatus.replaceWith(newConnectBtn);

          // Add event listener to new connect button
          attachConnectHandler(newConnectBtn, card);
        }
      });
    }
  });

  // Helper function to attach connect handler
  function attachConnectHandler(button, card) {
    button.addEventListener("click", function () {
      // Create connected status elements
      const connectedStatus = document.createElement("div");
      connectedStatus.className = "connected-status";

      const badge = document.createElement("span");
      badge.className = "badge connected-badge mb-2";
      badge.innerHTML =
        '<i class="fas fa-circle me-1" style="font-size: 0.5rem"></i> Connected';

      const newDisconnectBtn = document.createElement("button");
      newDisconnectBtn.className = "btn disconnect-btn";
      newDisconnectBtn.textContent = "Disconnect";

      connectedStatus.appendChild(badge);
      connectedStatus.appendChild(newDisconnectBtn);

      // Replace connect button with connected status
      button.replaceWith(connectedStatus);

      // Add event listener to new disconnect button
      newDisconnectBtn.addEventListener("click", function () {
        const integrationName =
          card.querySelector(".integration-name").textContent;
        if (
          confirm(`Are you sure you want to disconnect ${integrationName}?`)
        ) {
          // Create new connect button
          const newConnectBtn = document.createElement("button");
          newConnectBtn.className = "btn connect-btn";
          newConnectBtn.innerHTML =
            'Connect <i class="fas fa-arrow-right ms-2"></i>';

          // Replace connected status with connect button
          connectedStatus.replaceWith(newConnectBtn);

          // Re-attach the connect handler
          attachConnectHandler(newConnectBtn, card);
        }
      });
    });
  }

  // Settings card click navigation
  const settingsCards = document.querySelectorAll(".settings-card");

  settingsCards.forEach((card) => {
    card.style.cursor = "pointer";

    card.addEventListener("click", function () {
      const title = card.querySelector(".card-title").textContent;
      console.log(title);
      // let cleaned = title.replace(/\s+/g, '');
      // title = title.trim();
      
      if (title === 'User Group Matrix') {
        window.location.href = "/admin/permissions";
      }
      else if(title === 'Fee Fixing'){
        window.location.href = "/admin/feefixing";
      }
      else if(title === 'District Settings'){
        window.location.href = "/admin/districtsettings";
      }
      else{
        console.log('no show');
        return false;
      }
      // Map settings to placeholder pages (can be updated later)
      // const settingsMap = {
      //   General: "#general-settings",
      //   "Billing Plan": "#billing-settings",
      //   Team: "#team-settings",
      //   "SMS Settings": "#sms-settings",
      //   "Web Tracking Installation": "#tracking-settings",
      // };

      // const targetPage = settingsMap[title];
      // if (targetPage) {
      //   // For now, just show an alert (can be replaced with actual navigation)
      //   console.log(`Navigating to ${title} settings...`);
      //   // Uncomment the line below when actual pages are created
      //   // window.location.href = targetPage;
      // }
    });
  });
});
