document.addEventListener("DOMContentLoaded", () => {
  // Note: These IDs will be used in home.php.
  // If they differ, update them here or in home.php.
  const websiteUrlInput = document.getElementById("websiteUrlToCheck");
  const checkButton = document.getElementById("checkComplianceButton");
  const resultDiv = document.getElementById("complianceResult");
  const installationLinkDiv = document.getElementById("installationLink"); // This was from original spec

  if (!checkButton) {
    // Basic check to ensure elements are found
    // console.error("ADA Checker: Check button not found. Script may not be configured correctly for the page.");
    return;
  }

  checkButton.addEventListener("click", async () => {
    const urlToCheck = websiteUrlInput.value.trim();

    // Clear previous results
    if (resultDiv) resultDiv.innerHTML = "";
    if (installationLinkDiv) installationLinkDiv.style.display = "none";

    if (!urlToCheck) {
      alert("Please enter a website URL");
      return;
    }

    // Basic URL validation (doesn't need to be perfect, server/proxy might handle more)
    let fullUrl = urlToCheck;
    if (
      !urlToCheck.startsWith("http://") &&
      !urlToCheck.startsWith("https://")
    ) {
      fullUrl = "https://" + urlToCheck; // Default to https
    }

    try {
      new URL(fullUrl); // Validate if it's a parsable URL
    } catch (_) {
      alert(
        "Please enter a valid URL (e.g., https://example.com or example.com)"
      );
      return;
    }

    // Show modal and loading state
    showComplianceModal();
    showLoadingState();

    // Use a CORS proxy to fetch the website content
    const proxyUrl = `https://api.allorigins.win/raw?url=${encodeURIComponent(
      fullUrl
    )}`;

    try {
      const response = await fetch(proxyUrl);
      if (!response.ok) {
        throw new Error(
          `HTTP error! status: ${response.status} while fetching from proxy.`
        );
      }
      const htmlContent = await response.text();

      // Check for the ADA Wizard widget script
      // Looking for a script tag with src containing "widget.adawizard.com"
      const widgetPattern =
        /<script[^>]*src=["'](https?:)?\/\/widget\.adawizard\.com(\/[^"']*)?["'][^>]*>/i;

      if (widgetPattern.test(htmlContent)) {
        // Website has ADA widget - show compliant state
        showCompliantState();
      } else {
        // Website does not have ADA widget - show non-compliant state
        showNonCompliantState();
      }
    } catch (error) {
      console.error("Error fetching website content for ADA check:", error);
      // Show error state in modal
      showErrorState();
    }
  });

  // Allow Enter key to trigger check
  if (websiteUrlInput) {
    websiteUrlInput.addEventListener("keypress", function (e) {
      if (e.key === "Enter") {
        checkButton.click();
      }
    });
  }
});

// Close modal when clicking outside
document.addEventListener("click", function (event) {
  const modal = document.getElementById("complianceModal");

  if (event.target === modal) {
    closeComplianceModal();
  }
});

// Close modal with Escape key
document.addEventListener("keydown", function (event) {
  if (event.key === "Escape") {
    closeComplianceModal();
  }
});

// Modal control functions
function showComplianceModal() {
  document.getElementById("complianceModal").style.display = "block";
  document.body.style.overflow = "hidden"; // Prevent background scrolling
}

function closeComplianceModal() {
  document.getElementById("complianceModal").style.display = "none";
  document.body.style.overflow = "auto"; // Restore scrolling
}

function showLoadingState() {
  document.getElementById("loadingState").style.display = "block";
  document.getElementById("compliantState").style.display = "none";
  document.getElementById("nonCompliantState").style.display = "none";
  document.getElementById("errorState").style.display = "none";
}

function showCompliantState() {
  document.getElementById("loadingState").style.display = "none";
  document.getElementById("compliantState").style.display = "block";
  document.getElementById("nonCompliantState").style.display = "none";
  document.getElementById("errorState").style.display = "none";
}

function showNonCompliantState() {
  document.getElementById("loadingState").style.display = "none";
  document.getElementById("compliantState").style.display = "none";
  document.getElementById("nonCompliantState").style.display = "block";
  document.getElementById("errorState").style.display = "none";
}

function showErrorState() {
  document.getElementById("loadingState").style.display = "none";
  document.getElementById("compliantState").style.display = "none";
  document.getElementById("nonCompliantState").style.display = "none";
  document.getElementById("errorState").style.display = "block";
}
