document.addEventListener("DOMContentLoaded", () => {

  // ==========================
  // TOASTR CONFIG
  // ==========================
  toastr.options = {
    closeButton: true,
    progressBar: true,
    positionClass: "toast-top-right",
    timeOut: "3000"
  };

  // Load SEO when tab opened
  document.querySelectorAll('.nav-link[data-type]').forEach(tab => {
    tab.addEventListener('shown.bs.tab', e => {
      const type = e.target.getAttribute('data-type');
      loadSeo(type);
    });
  });

  // First load (home)
  loadSeo("home");

  // ==========================
  // SUBMIT HANDLER (UPDATE)
  // ==========================
  document.querySelectorAll('.seoForm').forEach(form => {
    form.addEventListener('submit', async e => {
      e.preventDefault();

      const formData = new FormData(form);
      const payload = Object.fromEntries(formData.entries());

      try {
        const res = await fetch('/seo/save', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(payload)
        });

        const data = await res.json();

        if (data.success === false) {
          toastr.error(data.message || "SEO update failed");
        } else {
          toastr.success(data.message || "SEO Updated Successfully");
        }

      } catch (err) {
        toastr.error("Server error while saving SEO");
      }
    });
  });

  // ==========================
  // GENERATE AI META (TOASTR)
  // ==========================
  document.querySelectorAll('.seoForm').forEach(form => {
    const generateBtn = form.querySelector('.generateSEO');

    generateBtn.addEventListener('click', async () => {
      const type = form.getAttribute('data-type');

      if (!type) {
        toastr.error("Page type not defined");
        return;
      }

const loadingToast = toastr.info(
  "AI is generating meta data...",
  "Please wait",
  {
    timeOut: 0,
    extendedTimeOut: 0,
    closeButton: false,
    tapToDismiss: false
  }
);
      try {
        const response = await fetch("/generateMetaAll", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ page: type })
        });

        const data = await response.json();

        
  toastr.clear(loadingToast);

        if (!data.success) {
          toastr.error(data.message || "AI generation failed");
          return;
        }

        // Fill fields
        form.querySelector('[name="metaTitle"]').value = data.metaTitle || "";
        form.querySelector('[name="metaKeywords"]').value = data.metaKeywords || "";
        form.querySelector('[name="metaDescription"]').value = data.metaDescription || "";

        toastr.success("Meta fields generated by AI");

      } catch (err) {
          toastr.clear(loadingToast);
        toastr.error("AI generation failed");
      }
    });
  });

});


// ==========================
// LOAD SEO DATA
// ==========================
async function loadSeo(type) {
  try {
    const res = await fetch(`/seo/${type}`);
    const data = await res.json();

    const form = document.querySelector(`.seoForm[data-type="${type}"]`);
    if (!form) return;

    form.metaTitle.value = data?.metaTitle || "";
    form.metaKeywords.value = data?.metaKeywords || "";
    form.metaDescription.value = data?.metaDescription || "";

  } catch (err) {
    toastr.error("Failed to load SEO data");
  }
}
