// Options page script for Chameleon extension

const form = document.getElementById("optionsForm");
const hubUrlInput = document.getElementById("hubUrl");
const userTokenInput = document.getElementById("userToken");
const statusDiv = document.getElementById("status");

// Load saved options
chrome.storage.local.get(["hubUrl", "userToken"], (result) => {
  if (result.hubUrl) {
    hubUrlInput.value = result.hubUrl;
  }
  if (result.userToken) {
    userTokenInput.value = result.userToken;
  }
});

// Save options
form.addEventListener("submit", async (e) => {
  e.preventDefault();

  const hubUrl = hubUrlInput.value.trim();
  const userToken = userTokenInput.value.trim();

  // Basic validation
  if (!hubUrl || !userToken) {
    showStatus("Please fill in all fields", "error");
    return;
  }

  // Remove trailing slash from URL
  const cleanUrl = hubUrl.replace(/\/$/, "");

  try {
    // Save to storage
    await chrome.storage.local.set({
      hubUrl: cleanUrl,
      userToken: userToken,
    });

    // Notify background script to refresh preferences
    chrome.runtime.sendMessage({
      type: "REFRESH_PREFERENCES",
    });

    showStatus("Settings saved successfully! ✓", "success");

    // Clear status after 3 seconds
    setTimeout(() => {
      statusDiv.classList.remove("show");
    }, 3000);
  } catch (error) {
    console.error("Error saving options:", error);
    showStatus("Failed to save settings. Please try again.", "error");
  }
});

function showStatus(message, type) {
  statusDiv.textContent = message;
  statusDiv.className = `status ${type} show`;
}
