/* =============================================================
   UPPAL CONSTRUCTION — Contact
   1. Project Inquiry form → POST ./api/contact.php (saves to MySQL
      + emails admin@uppalgroup.ae). Validated, anti-spam, states.
   2. "Enquire" / email buttons → open Gmail compose (mailto fallback).
   ============================================================= */

const ENDPOINT = "./api/contact.php";
const COMPANY_EMAIL = "admin@uppalgroup.ae";

const form = document.getElementById("enquiryForm");
if (form) initForm(form);
initGmailButtons();

/* -------------------------------------------------------------
   FORM
------------------------------------------------------------- */
function initForm(form) {
  const statusEl = form.querySelector("#formStatus");
  const submit = form.querySelector(".form__submit");
  const submitLabel = submit.querySelector(".btn__label");
  const honeypot = form.querySelector('input[name="botcheck"]');
  const loadedAt = Date.now();
  let sending = false;

  const required = [
    ["f-name",     (v) => v.length >= 2 || "Please enter your full name."],
    ["f-email",    (v) => isEmail(v) || "Please enter a valid email address."],
    ["f-phone",    (v) => isPhone(v) || "Please enter a valid phone number."],
    ["f-type",     (v) => !!v || "Please select a project type."],
    ["f-location", (v) => v.length >= 2 || "Please enter the project location."],
    ["f-message",  (v) => v.length >= 10 || "Please add a little more detail (10+ characters)."],
  ];

  required.forEach(([id]) => {
    const el = document.getElementById(id);
    el.addEventListener("input", () => clearError(el));
    el.addEventListener("change", () => clearError(el));
  });
  const consent = document.getElementById("f-consent");
  consent.addEventListener("change", () => clearError(consent));

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

    // Honeypot + time-trap: accept silently, never send
    if (honeypot.checked || Date.now() - loadedAt < 1200) {
      showSuccess();
      return;
    }

    // Validate
    let firstInvalid = null;
    for (const [id, validate] of required) {
      const el = document.getElementById(id);
      const val = (el.value || "").trim();
      el.value = val;
      const res = validate(val);
      if (res !== true) { setError(el, res); firstInvalid = firstInvalid || el; }
      else clearError(el);
    }
    if (!consent.checked) {
      setError(consent, "Please confirm you agree to be contacted.");
      firstInvalid = firstInvalid || consent;
    }
    if (firstInvalid) {
      setStatus("Please complete the highlighted fields.", "err");
      firstInvalid.focus();
      return;
    }

    const val = (id) => (document.getElementById(id).value || "").trim();
    const payload = {
      full_name: val("f-name"),
      company_name: val("f-company"),
      email: val("f-email"),
      phone: val("f-phone"),
      project_type: val("f-type"),
      estimated_budget: val("f-budget"),
      project_location: val("f-location"),
      preferred_contact_method: val("f-contact"),
      message: val("f-message"),
      botcheck: honeypot.checked ? "1" : "",
    };

    setSending(true);
    setStatus("Sending your inquiry…", "");
    try {
      const res = await fetch(ENDPOINT, {
        method: "POST",
        headers: { "Content-Type": "application/json", "Accept": "application/json" },
        body: JSON.stringify(payload),
      });
      const data = await res.json().catch(() => ({}));
      if (res.ok && data.success) {
        showSuccess(data.message);
      } else {
        // Surface the server's specific reason (e.g. "Server not configured…")
        setSending(false);
        setStatus(
          (data && data.message)
            ? data.message
            : `We couldn't send your inquiry. Please try again or contact us directly at ${COMPANY_EMAIL}.`,
          "err"
        );
      }
    } catch (err) {
      // Network / non-JSON response (e.g. PHP fatal error page)
      setSending(false);
      setStatus(
        `We couldn't reach the server. Please try again or contact us directly at ${COMPANY_EMAIL}.`,
        "err"
      );
    }
  });

  function setSending(on) {
    sending = on;
    submit.disabled = on;
    submit.classList.toggle("is-sending", on);
    submit.setAttribute("aria-busy", on ? "true" : "false");
    submitLabel.textContent = on ? "Sending Inquiry" : "Send Inquiry";
  }
  function showSuccess(msg) {
    setSending(false);
    submit.disabled = true;
    form.classList.add("sent");
    setStatus(msg || "Thank you. Your inquiry has been received. Our team will contact you shortly.", "ok");
  }
  function setStatus(msg, kind) {
    statusEl.textContent = msg;
    statusEl.classList.remove("ok", "err");
    if (kind) statusEl.classList.add(kind);
  }
  function setError(el, msg) {
    const field = el.closest(".field");
    if (!field) return;
    field.classList.add("invalid");
    el.setAttribute("aria-invalid", "true");
    const err = field.querySelector("[data-err]");
    if (err) err.textContent = msg;
  }
  function clearError(el) {
    const field = el.closest(".field");
    if (!field) return;
    field.classList.remove("invalid");
    el.removeAttribute("aria-invalid");
    const err = field.querySelector("[data-err]");
    if (err) err.textContent = "";
  }
}

function isEmail(v) {
  return /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(v);
}
function isPhone(v) {
  const digits = v.replace(/[^\d]/g, "");
  return /^[+\d][\d\s().-]{6,}$/.test(v) && digits.length >= 7 && digits.length <= 15;
}

/* -------------------------------------------------------------
   GMAIL BUTTONS  (data-gmail) — with mailto fallback
------------------------------------------------------------- */
function initGmailButtons() {
  const TO = "admin@uppalgroup.ae";
  const gmailUrl =
    "https://mail.google.com/mail/?view=cm&fs=1&to=" + encodeURIComponent(TO) +
    "&su=" + encodeURIComponent("Project Inquiry — Uppal Construction");
  document.querySelectorAll("[data-gmail]").forEach((el) => {
    el.addEventListener("click", (e) => {
      e.preventDefault();
      const win = window.open(gmailUrl, "_blank", "noopener,noreferrer");
      if (!win || win.closed || typeof win.closed === "undefined") {
        window.location.href = el.getAttribute("href") || ("mailto:" + TO);
      }
    });
  });
}
