function showToast(type = "info", message = "Something happened") {
  const toastEl = document.getElementById("appToast");

  // Remove all type classes
  toastEl.classList.remove(
    "toast-success",
    "toast-error",
    "toast-warning",
    "toast-info"
  );

  // Add the appropriate type class
  switch (type) {
    case "success":
      toastEl.classList.add("toast-success");
      break;
    case "error":
      toastEl.classList.add("toast-error");
      break;
    case "warning":
      toastEl.classList.add("toast-warning");
      break;
    case "info":
    default:
      toastEl.classList.add("toast-info");
      break;
  }

  // Update message
  toastEl.querySelector(".toast-body").textContent = message;

  // Show toast using Bootstrap
  const toast = new bootstrap.Toast(toastEl, {
    autohide: true,
    delay: 3000,
  });
  toast.show();
}

// Registration form submission
document
  .getElementById("registerForm")
  .addEventListener("submit", async function (e) {
    e.preventDefault();

    const form = e.target;

    const formData = {
      name: form.name.value.trim(),
      email: form.email.value.trim(),
      password: form.password.value,
      phone: form.phone.value.trim(),
      user_type: form.user_type.value,
    };

    try {
      const res = await fetch(
        `${window.BASE_URL}/api/frontend/user-registration.php`,
        {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(formData),
          credentials: "same-origin",
        }
      );

      const data = await res.json();

      showToast(data.status ? "success" : "error", data.message);

      if (data.status) {
        form.reset();

        bootstrap.Modal.getInstance(
          document.getElementById("registerModal")
        )?.hide();

        setTimeout(() => {
          location.reload();
        }, 1200);
      }
    } catch (err) {
      console.error(err);
      showToast("error", "Something went wrong. Please try again.");
    }
  });

// Login form submission
document
  .getElementById("loginForm")
  .addEventListener("submit", async function (e) {
    e.preventDefault();

    const form = e.target;

    const formData = {
      email: form.email.value.trim(),
      password: form.password.value,
    };

    try {
      const res = await fetch(
        `${window.BASE_URL}/api/frontend/user-login.php`,
        {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(formData),
          credentials: "same-origin",
        }
      );

      const data = await res.json();

      showToast(data.status ? "success" : "error", data.message);

      if (data.status) {
        form.reset();

        bootstrap.Modal.getInstance(
          document.getElementById("loginModal")
        )?.hide();

        setTimeout(() => {
          location.reload();
        }, 1200);
      }
    } catch (err) {
      console.error(err);
      showToast("error", "Login failed. Try again.");
    }
  });

// Save Job
async function saveJob(jobId) {
  try {
    const res = await fetch(
      `${window.BASE_URL}/api/frontend/user-job-save.php`,
      {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ job_id: jobId }),
        credentials: "same-origin",
      }
    );

    const data = await res.json();

    showToast(data.success ? "success" : "error", data.message);

    setTimeout(() => {
      location.reload();
    }, 1200);
  } catch (err) {
    console.error(err);
    showToast("error", "Saving job failed. Try again.");
  }
}

// Unsave Job
async function unSaveJob(jobId) {
  try {
    const res = await fetch(
      `${window.BASE_URL}/api/frontend/user-job-unsave.php`,
      {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ job_id: jobId }),
        credentials: "same-origin",
      }
    );

    const data = await res.json();

    showToast(data.success ? "success" : "error", data.message);

    setTimeout(() => {
      location.reload();
    }, 1200);
  } catch (err) {
    console.error(err);
    showToast("error", "Unsaving job failed. Try again.");
  }
}

// Apply Job
function jobApply(jobId) {
  const modal = new bootstrap.Modal(
    document.getElementById("confirmApplyModal")
  );
  modal.show();

  const btn = document.getElementById("confirmApplyBtn");
  btn.onclick = async () => {
    modal.hide();
    // Call your original fetch logic here
    try {
      const res = await fetch(
        `${window.BASE_URL}/api/frontend/user-job-apply.php`,
        {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ job_id: jobId }),
          credentials: "same-origin",
        }
      );

      const data = await res.json();
      showToast(data.success ? "success" : "error", data.message);

      setTimeout(() => {
        location.reload();
      }, 1200);
    } catch (err) {
      console.error(err);
      showToast("error", "Applying job failed. Try again.");
    }
  };
}

// Account Page Sidebar Navigation
document
  .querySelectorAll(".account-sidebar .list-group-item:not(#logoutBtn)")
  .forEach((item) => {
    item.addEventListener("click", function () {
      // Remove active from all
      document
        .querySelectorAll(".account-sidebar .list-group-item")
        .forEach((el) => {
          el.classList.remove("active");
        });

      // Add active to clicked
      this.classList.add("active");

      // Hide all sections
      document.querySelectorAll(".content-section").forEach((section) => {
        section.classList.add("d-none");
      });

      // Show target section
      const target = this.getAttribute("data-target");
      const targetSection = document.getElementById(target);
      if (targetSection) {
        targetSection.classList.remove("d-none");
      }
    });
  });

// Logout functionality with API call
document
  .getElementById("logoutBtn")
  ?.addEventListener("click", async function (e) {
    e.preventDefault();

    // Show confirmation modal (optional)
    const modal = new bootstrap.Modal(
      document.getElementById("logoutConfirmModal")
    );
    modal.show();

    const confirmBtn = document.getElementById("confirmLogoutBtn");
    confirmBtn.onclick = async () => {
      modal.hide();

      try {
        const res = await fetch(
          `${window.BASE_URL}/api/frontend/user-logout.php`,
          {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            credentials: "same-origin",
          }
        );

        const data = await res.json();

        if (data.success) {
          showToast("success", "Logged out successfully!");
          setTimeout(() => {
            window.location.replace("/carrier_job_admin/");
          }, 800);
        } else {
          showToast("error", data.message || "Logout failed. Try again.");
        }
      } catch (err) {
        console.error(err);
        showToast("error", "Logout failed. Try again.");
      }
    };
  });

// Profile Image Upload
const cameraBtn = document.querySelector(".camera-btn");

if (cameraBtn) {
  cameraBtn.addEventListener("click", function () {
    const fileInput = document.createElement("input");
    fileInput.type = "file";
    fileInput.accept = "image/*";

    fileInput.onchange = function (e) {
      const file = e.target.files[0];

      if (!file) return;

      // Preview image instantly
      const reader = new FileReader();
      reader.onload = function (event) {
        document.querySelector(".profile-img").src = event.target.result;
      };
      reader.readAsDataURL(file);

      // Upload to server
      uploadProfileImage(file);
    };

    fileInput.click();
  });
}

function uploadProfileImage(file) {
  const formData = new FormData();
  formData.append("profile_image", file);

  fetch(`${window.BASE_URL}/api/frontend/upload-profile.php`, {
    method: "POST",
    body: formData,
    credentials: "same-origin",
  })
    .then((res) => res.json())
    .then((data) => {
      if (data.success) {
        showToast("success", data.message);

        // Optional: replace preview with server image
        document.querySelector(".profile-img").src = data.image_url;
      } else {
        showToast("error", data.message);
      }
    })
    .catch(() => {
      showToast("error", "Image upload failed");
    });
}

// Edit Profile Button
const editProfileBtn = document.querySelector(".btn-primary.rounded-pill");
if (editProfileBtn) {
  editProfileBtn.addEventListener("click", function () {
    // Switch to account settings
    const accountItem = document.querySelector('[data-target="account"]');
    if (accountItem) {
      accountItem.click();
    }
  });
}

// Handle Logout
async function handleLogout() {
  try {
    const res = await fetch(`${window.BASE_URL}/api/frontend/user-logout.php`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      credentials: "same-origin",
    });

    const data = await res.json();

    if (typeof showToast === "function") {
      showToast(data.status ? "success" : "error", data.message);
    } else {
      alert(data.message);
    }

    if (data.status) {
      setTimeout(() => {
        window.location.href = `${window.BASE_URL}/index.php`;
      }, 1000);
    }
  } catch (err) {
    console.error(err);
    if (typeof showToast === "function") {
      showToast("error", "Logout failed. Try again.");
    } else {
      alert("Logout failed. Try again.");
    }
  }
}

// Match heights on window resize
function matchHeights() {
  if (window.innerWidth >= 992) {
    const leftColumn = document.querySelector(".col-lg-3");
    const rightColumn = document.querySelector(".col-lg-9");

    if (leftColumn && rightColumn) {
      const leftHeight = leftColumn.offsetHeight;
      const rightCard = rightColumn.querySelector(".card");

      if (rightCard) {
        rightCard.style.minHeight = leftHeight + "px";
      }
    }
  }
}

// Call on load and resize
matchHeights();
window.addEventListener("resize", matchHeights);

// Add CSS animations
const style = document.createElement("style");
style.textContent = `
  @keyframes slideIn {
    from {
      transform: translateX(100%);
      opacity: 0;
    }
    to {
      transform: translateX(0);
      opacity: 1;
    }
  }
  
  @keyframes slideOut {
    from {
      transform: translateX(0);
      opacity: 1;
    }
    to {
      transform: translateX(100%);
      opacity: 0;
    }
  }
  
  .content-section.show {
    animation: fadeIn 0.3s ease;
  }
`;
document.head.appendChild(style);

// Toggle password visibility
document.querySelectorAll(".toggle-password").forEach((button) => {
  button.addEventListener("click", function () {
    const input = this.closest(".input-group").querySelector("input");
    const icon = this.querySelector("i");

    if (input.type === "password") {
      input.type = "text";
      icon.classList.remove("fa-eye");
      icon.classList.add("fa-eye-slash");
    } else {
      input.type = "password";
      icon.classList.remove("fa-eye-slash");
      icon.classList.add("fa-eye");
    }
  });
});

// Form validation
document
  .getElementById("profileForm")
  ?.addEventListener("submit", async function (e) {
    e.preventDefault();

    if (!this.checkValidity()) {
      this.classList.add("was-validated");
      return;
    }

    const form = e.target;
    const submitBtn = form.querySelector('button[type="submit"]');
    const originalBtnText = submitBtn.innerHTML;

    // Disable button and show loading
    submitBtn.disabled = true;
    submitBtn.innerHTML =
      '<i class="fa fa-spinner fa-spin me-1"></i> Updating...';

    const formData = {
      name: form.name.value.trim(),
      email: form.email.value.trim(),
      phone: form.phone.value.trim(),
    };

    try {
      const res = await fetch(
        `${window.BASE_URL}/api/frontend/user-profile-update.php`,
        {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(formData),
          credentials: "same-origin",
        }
      );

      const data = await res.json();

      if (typeof showToast === "function") {
        showToast(data.status ? "success" : "error", data.message);
      } else {
        alert(data.message);
      }

      if (data.status) {
        // Update sidebar profile name if exists
        const sidebarName = document.querySelector(
          ".profile-card h5, .col-lg-3 h5"
        );
        if (sidebarName && data.data?.user_name) {
          sidebarName.textContent = data.data.user_name;
        }

        // Remove validation classes
        this.classList.remove("was-validated");
      }
    } catch (err) {
      console.error(err);
      if (typeof showToast === "function") {
        showToast("error", "Something went wrong. Please try again.");
      } else {
        alert("Something went wrong. Please try again.");
      }
    } finally {
      // Re-enable button
      submitBtn.disabled = false;
      submitBtn.innerHTML = originalBtnText;
    }
  });

document
  .getElementById("passwordForm")
  ?.addEventListener("submit", async function (e) {
    e.preventDefault();

    const newPass = this.querySelector('[name="new_password"]').value;
    const confirmPass = this.querySelector('[name="confirm_password"]').value;

    if (newPass !== confirmPass) {
      if (typeof showToast === "function") {
        showToast("error", "New password and confirm password do not match!");
      } else {
        alert("New password and confirm password do not match!");
      }
      return;
    }

    if (!this.checkValidity()) {
      this.classList.add("was-validated");
      return;
    }

    const form = e.target;
    const submitBtn = form.querySelector('button[type="submit"]');
    const originalBtnText = submitBtn.innerHTML;

    // Disable button and show loading
    submitBtn.disabled = true;
    submitBtn.innerHTML =
      '<i class="fa fa-spinner fa-spin me-1"></i> Updating...';

    const formData = {
      old_password: form.old_password.value,
      new_password: form.new_password.value,
      confirm_password: form.confirm_password.value,
    };

    try {
      const res = await fetch(
        `${window.BASE_URL}/api/frontend/user-password-change.php`,
        {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(formData),
          credentials: "same-origin",
        }
      );

      const data = await res.json();

      if (typeof showToast === "function") {
        showToast(data.status ? "success" : "error", data.message);
      } else {
        alert(data.message);
      }

      if (data.status) {
        // Reset form on success
        form.reset();
        this.classList.remove("was-validated");
      }
    } catch (err) {
      console.error(err);
      if (typeof showToast === "function") {
        showToast("error", "Something went wrong. Please try again.");
      } else {
        alert("Something went wrong. Please try again.");
      }
    } finally {
      // Re-enable button
      submitBtn.disabled = false;
      submitBtn.innerHTML = originalBtnText;
    }
  });

const baseURL = "<?= $baseURL ?>";
// COUNTRY → STATES
document
  .getElementById("add_country_id")
  ?.addEventListener("change", function () {
    const countryId = this.value;

    const stateSelect = document.getElementById("add_state_id");
    const citySelect = document.getElementById("add_city_id");

    stateSelect.innerHTML = '<option value="">Loading...</option>';
    citySelect.innerHTML = '<option value="">Select City</option>';

    if (!countryId) {
      stateSelect.innerHTML = '<option value="">Select State</option>';
      return;
    }

    fetch(
      `${window.BASE_URL}/api/frontend/get-state.php?country_id=${countryId}`,
      { credentials: "same-origin" }
    )
      .then((res) => res.json())
      .then((data) => {
        stateSelect.innerHTML = '<option value="">Select State</option>';
        data.forEach((state) => {
          stateSelect.innerHTML += `
            <option value="${state.id}">
              ${state.state_name}
            </option>`;
        });
      })
      .catch((err) => {
        console.error(err);
        stateSelect.innerHTML =
          '<option value="">Failed to load states</option>';
      });
  });

// STATE → CITIES
document
  .getElementById("add_state_id")
  ?.addEventListener("change", function () {
    const stateId = this.value;

    const citySelect = document.getElementById("add_city_id");
    citySelect.innerHTML = '<option value="">Loading...</option>';

    if (!stateId) {
      citySelect.innerHTML = '<option value="">Select City</option>';
      return;
    }

    fetch(`${window.BASE_URL}/api/frontend/get-city.php?state_id=${stateId}`, {
      credentials: "same-origin",
    })
      .then((res) => res.json())
      .then((data) => {
        citySelect.innerHTML = '<option value="">Select City</option>';
        data.forEach((city) => {
          citySelect.innerHTML += `
            <option value="${city.id}">
              ${city.city_name}
            </option>`;
        });
      })
      .catch((err) => {
        console.error(err);
        citySelect.innerHTML =
          '<option value="">Failed to load cities</option>';
      });
  });

document.addEventListener("change", function (e) {
  /* ===== EDIT MODAL: COUNTRY → STATES ===== */
  if (e.target && e.target.id === "edit_country_id") {
    const countryId = e.target.value;
    const stateSelect = document.getElementById("edit_state_id");
    const citySelect = document.getElementById("edit_city_id");

    stateSelect.innerHTML = '<option value="">Loading...</option>';
    citySelect.innerHTML = '<option value="">Select City</option>';

    if (!countryId) {
      stateSelect.innerHTML = '<option value="">Select State</option>';
      return;
    }

    fetch(
      `${window.BASE_URL}/api/frontend/get-state.php?country_id=${countryId}`
    )
      .then((res) => res.json())
      .then((data) => {
        stateSelect.innerHTML = '<option value="">Select State</option>';
        data.forEach((state) => {
          stateSelect.innerHTML += `
            <option value="${state.id}">${state.state_name}</option>
          `;
        });
      })
      .catch(() => {
        stateSelect.innerHTML =
          '<option value="">Failed to load states</option>';
      });
  }

  /* ===== EDIT MODAL: STATE → CITIES ===== */
  if (e.target && e.target.id === "edit_state_id") {
    const stateId = e.target.value;
    const citySelect = document.getElementById("edit_city_id");

    citySelect.innerHTML = '<option value="">Loading...</option>';

    if (!stateId) {
      citySelect.innerHTML = '<option value="">Select City</option>';
      return;
    }

    fetch(`${window.BASE_URL}/api/frontend/get-city.php?state_id=${stateId}`)
      .then((res) => res.json())
      .then((data) => {
        citySelect.innerHTML = '<option value="">Select City</option>';
        data.forEach((city) => {
          citySelect.innerHTML += `
            <option value="${city.id}">${city.city_name}</option>
          `;
        });
      })
      .catch(() => {
        citySelect.innerHTML =
          '<option value="">Failed to load cities</option>';
      });
  }
});

document.addEventListener("DOMContentLoaded", function () {
  /* ===============================
     Init Summernote
  =============================== */
  $("#job_description, #job_apply").summernote({
    height: 150,
    placeholder: "Minimum 10 characters required",
    toolbar: [
      ["style", ["bold", "italic", "underline"]],
      ["para", ["ul", "ol"]],
      ["view", ["codeview"]],
    ],
  });

  const form = document.getElementById("addJobForm");

  /* ===============================
     Helper: Validate Summernote
  =============================== */
  function validateSummernote(id) {
    const text = $(id)
      .summernote("code")
      .replace(/<\/?[^>]+(>|$)/g, "")
      .trim();

    const editor = $(id).next(".note-editor");
    const feedback = $(id).parent().find(".invalid-feedback");

    if (text.length < 10) {
      editor.addClass("is-invalid");
      feedback.show();
      return false;
    } else {
      editor.removeClass("is-invalid");
      feedback.hide();
      return true;
    }
  }

  /* ===============================
     Form Submit
  =============================== */
  form.addEventListener("submit", async function (e) {
    e.preventDefault();

    let isValid = true;

    /* ---------- Bootstrap validation ---------- */
    form.querySelectorAll("input, select").forEach((field) => {
      if (!field.checkValidity()) {
        field.classList.add("is-invalid");
        isValid = false;
      } else {
        field.classList.remove("is-invalid");
      }
    });

    /* ---------- Summernote validation ---------- */
    const descValid = validateSummernote("#job_description");
    const applyValid = validateSummernote("#job_apply");

    if (!descValid || !applyValid) {
      isValid = false;
    }

    if (!isValid) {
      form.classList.add("was-validated");
      return;
    }

    /* ===============================
       AJAX Submit
    =============================== */
    const submitBtn = form.querySelector('button[type="submit"]');
    const originalBtnText = submitBtn.innerHTML;

    submitBtn.disabled = true;
    submitBtn.innerHTML =
      '<i class="fa fa-spinner fa-spin me-1"></i> Saving...';

    const formData = new FormData(form);
    formData.set("description", $("#job_description").summernote("code"));
    formData.set("apply", $("#job_apply").summernote("code"));

    try {
      const res = await fetch(`${window.BASE_URL}/api/frontend/add-job.php`, {
        method: "POST",
        body: formData,
        credentials: "same-origin",
      });

      const data = await res.json();

      if (typeof showToast === "function") {
        showToast(data.status ? "success" : "error", data.message);

        setTimeout(() => {
          location.reload();
        }, 1500); // 1.5 seconds
      } else {
        showt(data.status ? "success" : "error", data.message);
      }

      if (data.status) {
        /* ---------- Reset form ---------- */
        form.reset();
        $("#job_description, #job_apply").summernote("reset");
        form.classList.remove("was-validated");

        document
          .querySelectorAll(".is-invalid")
          .forEach((el) => el.classList.remove("is-invalid"));

        /* ---------- Close modal ---------- */
        const modalEl = document.getElementById("addJobModal");
        const modal = bootstrap.Modal.getInstance(modalEl);
        modal.hide();

        // OPTIONAL: refresh job list
        // loadJobs();
      }
    } catch (err) {
      console.error(err);
      if (typeof showToast === "function") {
        showToast("error", "Something went wrong. Please try again.");
      } else {
        alert("Something went wrong. Please try again.");
      }
    } finally {
      submitBtn.disabled = false;
      submitBtn.innerHTML = originalBtnText;
    }
  });
});

document.addEventListener("DOMContentLoaded", function () {
  /* ===============================
     Init Summernote (Edit)
  =============================== */
  $("#edit_description, #edit_apply").summernote({
    height: 150,
    placeholder: "Minimum 10 characters required",
    toolbar: [
      ["style", ["bold", "italic", "underline"]],
      ["para", ["ul", "ol"]],
      ["view", ["codeview"]],
    ],
  });

  const editForm = document.getElementById("editJobForm");

  /* ===============================
     Helper: Validate Summernote
  =============================== */
  function validateEditSummernote(id) {
    const text = $(id)
      .summernote("code")
      .replace(/<\/?[^>]+(>|$)/g, "")
      .trim();

    const editor = $(id).next(".note-editor");
    const feedback = $(id).closest(".col-12").find(".invalid-feedback");

    if (text.length < 10) {
      editor.addClass("is-invalid");
      feedback.show();
      return false;
    } else {
      editor.removeClass("is-invalid");
      feedback.hide();
      return true;
    }
  }

  /* ===============================
     Edit Form Submit
  =============================== */
  editForm.addEventListener("submit", async function (e) {
    e.preventDefault();

    let isValid = true;

    /* ---------- Bootstrap validation ---------- */
    editForm.querySelectorAll("input, select").forEach((field) => {
      if (!field.checkValidity()) {
        field.classList.add("is-invalid");
        isValid = false;
      } else {
        field.classList.remove("is-invalid");
      }
    });

    /* ---------- Summernote validation ---------- */
    const descValid = validateEditSummernote("#edit_description");
    const applyValid = validateEditSummernote("#edit_apply");

    if (!descValid || !applyValid) {
      isValid = false;
    }

    if (!isValid) {
      editForm.classList.add("was-validated");
      return;
    }

    /* ===============================
       AJAX Submit
    =============================== */
    const submitBtn = editForm.querySelector('button[type="submit"]');
    const originalBtnText = submitBtn.innerHTML;

    submitBtn.disabled = true;
    submitBtn.innerHTML =
      '<i class="fa fa-spinner fa-spin me-1"></i> Updating...';

    const formData = new FormData(editForm);
    formData.set("description", $("#edit_description").summernote("code"));
    formData.set("apply", $("#edit_apply").summernote("code"));

    try {
      const res = await fetch(
        `${window.BASE_URL}/api/frontend/update-job.php`,
        {
          method: "POST",
          body: formData,
          credentials: "same-origin",
        }
      );

      const data = await res.json();

      if (typeof showToast === "function") {
        showToast(data.status ? "success" : "error", data.message);

        setTimeout(() => {
          location.reload();
        }, 1500); // 1.5 seconds
      } else {
        showt(data.status ? "success" : "error", data.message);
      }

      if (data.status) {
        /* ---------- Reset form ---------- */
        editForm.reset();
        $("#edit_description, #edit_apply").summernote("reset");
        editForm.classList.remove("was-validated");

        document
          .querySelectorAll("#editJobForm .is-invalid")
          .forEach((el) => el.classList.remove("is-invalid"));

        /* ---------- Close modal ---------- */
        const modalEl = document.getElementById("editJobModal");
        const modal = bootstrap.Modal.getInstance(modalEl);
        modal.hide();

        // OPTIONAL: reload jobs list
        // loadJobs();
      }
    } catch (err) {
      console.error(err);
      if (typeof showToast === "function") {
        showToast("error", "Something went wrong. Please try again.");
      } else {
        alert("Something went wrong. Please try again.");
      }
    } finally {
      submitBtn.disabled = false;
      submitBtn.innerHTML = originalBtnText;
    }
  });
});

document.addEventListener("DOMContentLoaded", function () {
  const form = document.querySelector("#contact form");

  form.addEventListener("submit", async function (e) {
    e.preventDefault();

    let isValid = true;

    // ---------- Bootstrap validation ----------
    form.querySelectorAll("input, textarea").forEach((field) => {
      if (!field.checkValidity()) {
        field.classList.add("is-invalid");
        isValid = false;
      } else {
        field.classList.remove("is-invalid");
      }
    });

    if (!isValid) {
      form.classList.add("was-validated");
      return;
    }

    // ---------- AJAX Submit ----------
    const submitBtn = form.querySelector('button[type="submit"]');
    const originalBtnText = submitBtn.innerHTML;

    submitBtn.disabled = true;
    submitBtn.innerHTML =
      '<i class="fa fa-spinner fa-spin me-1"></i> Sending...';

    const formData = new FormData(form);

    try {
      const res = await fetch(
        `${window.BASE_URL}/api/frontend/send-contact.php`,
        {
          method: "POST",
          body: formData,
          credentials: "same-origin",
        }
      );

      const contentType = res.headers.get("content-type");
      if (!contentType || !contentType.includes("application/json")) {
        throw new Error("Server returned non-JSON response");
      }

      const data = await res.json();

      if (data.status) {
        if (typeof showToast === "function") {
          showToast("success", data.message);
        } else {
          alert(data.message);
        }

        form.reset();
        form.classList.remove("was-validated");
        form
          .querySelectorAll(".is-invalid")
          .forEach((el) => el.classList.remove("is-invalid"));
      } else {
        if (typeof showToast === "function") {
          showToast("error", data.message);
        } else {
          alert(data.message);
        }
      }
    } catch (err) {
      console.error("Contact form error:", err);
      if (typeof showToast === "function") {
        showToast("error", "Something went wrong. Please try again.");
      } else {
        alert("Something went wrong. Please try again.");
      }
    } finally {
      submitBtn.disabled = false;
      submitBtn.innerHTML = originalBtnText;
    }
  });
});
