import "./rgb-slider.js";

const ws = new WebSocket("ws://localhost:8000/ws");

ws.onopen = () => {
  console.log("WebSocket connection established");
};

ws.onclose = () => {
  console.log("WebSocket connection closed");
};

ws.onerror = (error) => {
  console.error("WebSocket error:", error);
};

// Number of sliders (tabs) you want to create
const numTabs = 3;

// Select the container for tabs and content
const tabsContainer = document.querySelector(".tabs");
const tabContentContainer = document.querySelector(".tab-content");

// Create tabs dynamically
for (let i = 1; i <= numTabs; i++) {
  // Create the tab button
  const tabButton = document.createElement("button");
  tabButton.classList.add("tab");
  tabButton.id = `tab${i}`;
  tabButton.textContent = `Tab ${i}`;

  // Add the tab button to the container
  tabsContainer.appendChild(tabButton);

  // Create the corresponding tab content (RGB slider)
  const tabContent = document.createElement("div");
  tabContent.classList.add("tab-pane");
  tabContent.id = `content${i}`;
  const slider = document.createElement("rgb-slider");
  slider.id = i;
  tabContent.appendChild(slider);

  // Add the tab content to the container
  tabContentContainer.appendChild(tabContent);

  // Listen for color change on each RGB slider
  slider.addEventListener("color-change", (e) => {
    const { r, g, b } = e.detail;
    console.log(`Color changed in tab ${i}:`, e.detail);
    // Send RGB data to WebSocket server
    if (ws.readyState === WebSocket.OPEN) {
      const colorData = { r, g, b };
      ws.send(JSON.stringify(colorData));
    }
  });
}

// Function to switch tabs
function switchTab(tabId) {
  const tabs = document.querySelectorAll(".tab");
  const tabContents = document.querySelectorAll(".tab-pane");

  tabs.forEach((tab) => tab.classList.remove("active"));
  tabContents.forEach((content) => content.classList.remove("active"));

  // Activate the clicked tab and corresponding content
  document.getElementById(tabId).classList.add("active");
  document
    .getElementById("content" + tabId.replace("tab", ""))
    .classList.add("active");
}

// Add event listeners to tabs
tabsContainer.addEventListener("click", (e) => {
  if (e.target.classList.contains("tab")) {
    switchTab(e.target.id);
  }
});

// Initially set the first tab as active
switchTab("tab1");
