$(document).ready(function () {

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

  const modal = new bootstrap.Modal(document.getElementById("faqModal"));

  // ==========================
  // RESET DATATABLE
  // ==========================
  if ($.fn.DataTable.isDataTable("#zero_config")) {
    $("#zero_config").DataTable().clear().destroy();
  }

  // ==========================
  // DATATABLE
  // ==========================
  const table = $("#zero_config").DataTable({
    responsive: true,
    autoWidth: false,
    ajax: { url: "/faqjson", dataSrc: "data" },
    columns: [
      { data: "question" },
      {
        data: null,
        className: "text-center",
        render: (row) => `
          <div class="dropdown dropstart">
            <button class="btn btn-sm btn-light rounded-circle" data-bs-toggle="dropdown">
              <i class="fa-solid fa-ellipsis-vertical"></i>
            </button>
            <ul class="dropdown-menu dropdown-menu-end shadow">
              <li>
                <button class="dropdown-item edit-btn" data-id="${row._id}">
                  <i class="fa-solid fa-pen-to-square me-2 text-primary"></i>Edit
                </button>
              </li>
              <li>
                <button class="dropdown-item delete-btn" data-id="${row._id}">
                  <i class="fa-solid fa-trash me-2 text-danger"></i>Delete
                </button>
              </li>
            </ul>
          </div>`
      }
    ],
    order: []
  });

  // ==========================
  // ADD FAQ
  // ==========================
  $("#addFaqBtn").click(() => {
    $("#faqForm")[0].reset();
    $("#faqId").val("");
    $("#faqModalLabel").text("Add FAQ");
    modal.show();
  });

  // ==========================
  // GENERATE FAQ ANSWER (AI)
  // ==========================
  $("#generateFaqAI").click(function () {
    const question = $("#question").val().trim();

    if (!question) {
      toastr.warning("Please enter Question first");
      return;
    }

  const loadingToast = toastr.info(
        "AI is writing description...",
        "Please wait",
        { timeOut: 0, extendedTimeOut: 0 }
    );

    $.ajax({
      url: "/generateDescription",
      type: "POST",
      contentType: "application/json",
      data: JSON.stringify({ name: question, prompt: 'Answer in only 2 concise sentences (max 20 words total). No examples, no extra details.' }),
      success: (res) => {
              toastr.clear(loadingToast);

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

        $("#answer").val(res.description || "");
        toastr.success("Answer generated by AI");
      },
      error: () =>{
        toastr.clear(loadingToast);
        toastr.error("AI generation failed")
      }
    });
  });

  // ==========================
  // EDIT FAQ
  // ==========================
  $("#zero_config").on("click", ".edit-btn", function () {
    const row = table.row($(this).closest("tr")).data();
    if (!row) {
      toastr.error("Data not found");
      return;
    }

    $("#faqForm")[0].reset();
    $("#faqId").val(row._id);
    $("#question").val(row.question);
    $("#answer").val(row.answer);

    $("#faqModalLabel").text("Edit FAQ");
    modal.show();
  });

  // ==========================
  // SAVE FAQ (ADD / UPDATE)
  // ==========================
  $("#faqForm").submit(function (e) {
    e.preventDefault();

    const $submitBtn = $("#faqForm button[type='submit']");
    const originalBtnContent = $submitBtn.html();
    $submitBtn.prop("disabled", true);
    $submitBtn.html(`
      <span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
    `);

    $.ajax({
      url: "/faqsave",
      type: "POST",
      data: {
        id: $("#faqId").val(),
        question: $("#question").val(),
        answer: $("#answer").val()
      },
      success: (res) => {
        if (res.success) {
          toastr.success(res.message || "Saved successfully");
          modal.hide();
          table.ajax.reload(null, false);
        } else {
          toastr.error(res.message || "Save failed");
        }
      },
      error: () => toastr.error("Server error!"),
      complete: () => {
        //  Restore button
        $submitBtn.prop("disabled", false);
        $submitBtn.html(originalBtnContent);
      }
    });
  });

  // ==========================
  // DELETE FAQ (NO CONFIRM)
  // ==========================
  $("#zero_config").on("click", ".delete-btn", function () {
    const id = $(this).data("id");


      Swal.fire({
    title: "Are you sure?",
    text: "This Faq will be deleted permanently!",
    icon: "warning",
    showCancelButton: true,
    confirmButtonText: "Yes, Delete",
    cancelButtonText: "Cancel"
  }).then((result) => {

    if (!result.isConfirmed) return;

    $.ajax({
      url: `/faqdelete/${id}`,
      type: "DELETE",
      success: (res) => {
        if (res.success) {
          toastr.success(res.message || "Deleted successfully");
          table.ajax.reload(null, false);
        } else {
          toastr.error(res.message || "Delete failed");
        }
      },
      error: () => toastr.error("Failed to delete")
    });
      });
  });

});
