export default async function sendPing(shadowRoot) {
  try {
    const productId = document.querySelector(".spectator-views-placeholder")
      ?.dataset.productId;

    if (!productId) {
      throw new Error("Product ID not found");
    }

    const location = window.location.origin;
    const endpoint = "/wp-json/firevert/v1/spectator-views/ping";

    const response = await fetch(
      `${location}${endpoint}?product_id=${productId}`,
      {
        method: "GET",
        headers: {
          "Content-Type": "application/json",
        },
      }
    );

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const data = await response.json();

    const viewsText = shadowRoot.querySelector(
      ".firevert-spectator-views__text"
    );

    const accentColor = shadowRoot.querySelector(
      ".firevert-spectator-views__text > span"
    )?.style.color;

    const stateText = data.text.replace(
      /<span([^>]*)>/g,
      `<span$1 style="color: ${accentColor}; font-weight: 700;">`
    );

    viewsText.innerHTML = `${stateText} `;
  } catch (error) {
    console.error("Error sending ping:", error);
    throw error;
  }
}
