document.addEventListener("DOMContentLoaded", () => {
  const auditBtn = document.querySelector(".wptech-run-audit");
  const statusMsg = document.querySelector(".audit-status");

  if (auditBtn) {
    auditBtn.addEventListener("click", () => {
      auditBtn.disabled = true;
      statusMsg.style.display = "block";
      statusMsg.textContent = "Trwa wykonywanie audytu...";

      fetch(wptech_ajax.ajax_url, {
        method: "POST",
        credentials: "same-origin",
        headers: { "Content-Type": "application/x-www-form-urlencoded" },
        body: new URLSearchParams({
          action: "wptech_run_audit",
          _ajax_nonce: wptech_ajax.nonce
        })
      })
      .then(response => response.json())
      .then(data => {
        if (data.success) {
          // zamiast komunikatu - przeładuj stronę
          location.reload();
        } else {
          statusMsg.textContent = "Wystąpił błąd podczas audytu.";
        }
      })
      .catch(() => {
        statusMsg.textContent = "Wystąpił błąd sieci.";
      })
      .finally(() => {
        auditBtn.disabled = false;
      });
    });
  }
});



document.addEventListener("DOMContentLoaded", () => {
  const form = document.querySelector(".wptech-cta form");
  const formContainer = document.querySelector(".wptech-form-container");
  const thankYou = document.querySelector(".wptech-thankyou");
  const thankYouEmail = thankYou ? thankYou.querySelector("strong") : null;
  const closeBtn = thankYou ? thankYou.querySelector(".wptech-thankyou-close") : null;
  const textarea = form ? form.querySelector("textarea") : null;
  const editBtn = document.querySelector(".wptech-edit-email");
  const emailInput = document.querySelector(".wptech-email-input");
  const emailDisplayContainer = document.querySelector(".wptech-email-display");
  const emailDisplay = emailDisplayContainer ? emailDisplayContainer.querySelector("strong") : null;
  const errorBox = document.createElement("div");

  // Dodaj div na błędy pod formularzem
  if (form) {
    errorBox.className = "cta-error";
    errorBox.style.display = "none";
    errorBox.style.color = "#d63638";
    errorBox.style.fontWeight = "bold";
    errorBox.style.marginTop = "10px";
    form.appendChild(errorBox);
  }

  if (form) {
    form.addEventListener("submit", (e) => {
      e.preventDefault();

      errorBox.style.display = "none";
      errorBox.textContent = "";

      const message = textarea ? textarea.value.trim() : '';
      const emailToSend = emailInput && emailInput.style.display === "block" && emailInput.value.trim() !== ""
        ? emailInput.value.trim()
        : (emailDisplay ? emailDisplay.textContent.trim() : '');

      fetch(wptech_ajax.ajax_url, {
        method: "POST",
        headers: {
          "Content-Type": "application/x-www-form-urlencoded"
        },
        body: new URLSearchParams({
          action: "wptech_submit_help",
          message: message,
          email: emailToSend,
          _ajax_nonce: wptech_ajax.nonce
        })
      })
      .then(res => res.json())
      .then(response => {
        if (response.success) {
          if (!response.data.smtp) {
            errorBox.innerHTML = "⚠️ Twoja strona nie korzysta z SMTP. Wiadomość mogła nie zostać dostarczona. Skonfiguruj SMTP lub napisz do nas na <a href=\"mailto:pawel.deluga@gmail.com\">pawel.deluga@gmail.com</a>.";
            errorBox.style.display = "block";
          } else {
            if (formContainer && thankYou && thankYouEmail) {
              formContainer.style.display = "none";
              thankYou.style.display = "block";
              thankYouEmail.textContent = response.data.email;
              thankYou.scrollIntoView({ behavior: "smooth", block: "center" });
            }
          }
        }
      })
      .catch(() => {
        errorBox.innerHTML = "❌ Błąd połączenia z serwerem. Spróbuj ponownie lub napisz na <a href=\"mailto:pawel.deluga@gmail.com\">pawel.deluga@gmail.com</a>";
        errorBox.style.display = "block";
      });
    });
  }

  if (closeBtn) {
    closeBtn.addEventListener("click", () => {
      if (thankYou && formContainer) {
        thankYou.style.display = "none";
        formContainer.style.display = "block";
      }
      if (textarea) {
        textarea.value = "";
      }
      errorBox.style.display = "none";
      errorBox.textContent = "";
    });
  }

  if (editBtn) {
    editBtn.addEventListener("click", () => {
      if (emailInput && emailDisplayContainer) {
        if (emailInput.style.display === "none" || emailInput.style.display === "") {
          emailInput.style.display = "block";
          if (emailDisplay) {
            emailInput.value = emailDisplay.textContent.trim();
          }
          emailDisplayContainer.style.display = "none";
          editBtn.innerHTML = `
            <i><svg width="14" height="14" fill="currentColor"><path d="M6 6l6 6M6 12L12 6"/></svg></i>
            Anuluj
          `;
        } else {
          emailInput.style.display = "none";
          emailDisplayContainer.style.display = "inline";
          editBtn.innerHTML = `
            <i><svg width="14" height="14" fill="currentColor"><path d="M12.3 2.3a1 1 0 0 0-1.4 0L5 8.2V9h.8l5.9-5.9a1 1 0 0 0 0-1.4zM4 9v1h1l6-6-1-1-6 6z"/></svg></i>
            Zmień
          `;
        }
      }
    });
  }
});