document.addEventListener("DOMContentLoaded", function() {
  const generateBtn   = document.getElementById("boxyfy-singleproduct-ai-generate-questions");
  const questionInput = document.getElementById("boxyfy-singleproduct-aichat-question");
  const suggestedBox  = document.getElementById("boxyfy-singleproduct-ai-suggested-questions");
  const submitBtn     = document.getElementById("boxyfy-singleproduct-aichat-submit");
  const responseBox   = document.getElementById("boxyfy-singleproduct-aichat-response");
  const { ajax_url, nonce } = boxyfyData;

  if (generateBtn && suggestedBox) {
    generateBtn.addEventListener("click", () => {
      const title = document.querySelector(".tsprodukt-box-header a")?.innerText || "";
      suggestedBox.innerHTML = '<p class="boxyfy-ai-loading">Warte kurz, die KI generiert Fragen...</p>';

      fetch(ajax_url, {
        method: "POST",
        headers: { "Content-Type": "application/x-www-form-urlencoded" },
        body: new URLSearchParams({
          action:        "boxyfy_ai_generate_questions",
          nonce:         nonce,
          product_title: title
        })
      })
      .then(r => r.json())
      .then(json => {
        suggestedBox.innerHTML = "";
        if (!json.success) {
          suggestedBox.textContent = "❌ Fehler: " + json.data.message;
          return;
        }
        let arr = [];
        try {
          arr = JSON.parse(json.data.choices[0].message.content || "[]");
        } catch {
          arr = ["Fehler beim Parsen", json.data.choices[0].message.content];
        }
        const label = document.createElement("p");
        label.classList.add("boxyfy-ai-label");
        label.textContent = "Beispiel-Fragen:";
        suggestedBox.appendChild(label);
        arr.forEach(q => {
          const btn = document.createElement("button");
          btn.textContent = q;
          btn.className = "boxyfy-chat-question-button";
          btn.addEventListener("click", () => questionInput.value = q);
          suggestedBox.appendChild(btn);
        });
      })
      .catch(err => {
        suggestedBox.innerHTML = '<p class="boxyfy-ai-error">❌ ' + err.message + "</p>";
      });
    });
  }

  if (submitBtn && responseBox) {
    submitBtn.addEventListener("click", () => {
      const userQuestion = questionInput.value;
      responseBox.innerHTML = '<p class="boxyfy-ai-loading">Bitte warte, die KI antwortet...</p>';

      fetch(ajax_url, {
        method: "POST",
        headers: { "Content-Type": "application/x-www-form-urlencoded" },
        body: new URLSearchParams({
          action:        "boxyfy_ai_ask_question",
          nonce:         nonce,
          user_question: userQuestion
        })
      })
      .then(r => r.json())
      .then(json => {
        responseBox.innerHTML = "";
        if (!json.success) {
          responseBox.textContent = "❌ Fehler: " + json.data.message;
          return;
        }
        const reply = json.data.choices?.[0]?.message?.content || "❌ Keine Antwort erhalten.";
        responseBox.innerHTML = '<div class="boxyfy-ai-answer"><strong>Antwort:</strong><br><br>' + reply + "</div>";
      })
      .catch(err => {
        responseBox.innerHTML = '<p class="boxyfy-ai-error">❌ ' + err.message + "</p>";
      });
    });
  }
});