const scriptUrl = "https://script.google.com/macros/s/AKfycbzmzTtW3v01Clj11IoMZDUi_R9X4vIPjnQ5f87UDfZpZTP3jHIWzzE5arFEQTzocGND/exec";
const ACCESS_KEY = "leadway_landing_access";

const questions = [
  {
    id: "status",
    fieldName: "employment",
    prompt: "What best describes your current work status?",
    options: [
      { label: "Employed", hint: "Suitable for salary earners and formal employment." },
      { label: "Self-employed / business owner", hint: "For business owners and independent earners." },
      { label: "Freelancer / consultant", hint: "For project-based and independent professionals." },
      { label: "Not currently earning regularly", hint: "A more informational path may be more helpful first." }
    ]
  },
  {
    id: "timeline",
    fieldName: "timeline",
    prompt: "When would you like to start your RSA?",
    options: [
      { label: "I’m ready to start now", hint: "You are prepared to move forward immediately." },
      { label: "Within the next 1 month", hint: "You are close to beginning." },
      { label: "Within 3 months", hint: "You are interested but not yet immediate." },
      { label: "Just exploring for now", hint: "You may want more context first." }
    ]
  },
  {
    id: "income",
    fieldName: "income",
    prompt: "Do you currently earn regular monthly income?",
    options: [
      { label: "Yes", hint: "A steady income usually supports easier contribution planning." },
      { label: "Somewhat / varies", hint: "Some flexibility may be helpful." },
      { label: "No", hint: "You may benefit from learning more first." }
    ]
  },
  {
    id: "purpose",
    fieldName: "purpose",
    prompt: "What are you looking to do?",
    options: [
      { label: "Start a new RSA", hint: "You are looking to open a new account." },
      { label: "Transfer my existing RSA", hint: "You already have an RSA and want to move it." },
      { label: "Get guidance before opening", hint: "You want a clearer understanding before proceeding." },
      { label: "Just learning about pensions", hint: "An educational next step may be more appropriate." }
    ]
  },
  {
    id: "commitment",
    fieldName: "commitment",
    prompt: "Are you ready to begin a structured retirement savings plan?",
    options: [
      { label: "Yes, I’m ready", hint: "You appear ready to move to the next stage." },
      { label: "I need more information first", hint: "A guided explanation may help before proceeding." }
    ]
  }
];

const jobSectorOptions = [
  "Agriculture",
  "Chemical industries",
  "Construction",
  "Education",
  "Financial services",
  "Food",
  "Health services",
  "Hotels & Tourism",
  "Mechanical and electrical engineering",
  "Media",
  "Oil and Gas Production",
  "Postal and telecommunications services",
  "Shipping",
  "Textiles",
  "Transport",
  "Utilities",
  "Unemployed",
  "Others"
];

const formStage = document.getElementById("formStage");
const formStageLabel = document.getElementById("form-stage-label");
const progressCopy = document.getElementById("progressCopy");
const progressFill = document.getElementById("progressFill");
const backButton = document.getElementById("backButton");
const nextButton = document.getElementById("nextButton");

let currentStep = 0;
let isSubmitting = false;
const responses = {
  qualification: {},
  contact: {
    full_name: "",
    email: "",
    phone: "",
    state: "",
    job_sector: "",
    has_rsa: ""
  }
};

function renderStep() {
  updateNavigation();

  if (currentStep < questions.length) {
    renderQuestionStep(questions[currentStep], currentStep);
    return;
  }

  renderContactStep();
}

function updateNavigation() {
  if (currentStep < questions.length) {
    formStageLabel.textContent = "Qualification";
    progressCopy.textContent = "Step " + (currentStep + 1) + " of 5";
    progressFill.style.width = ((currentStep + 1) / questions.length) * 100 + "%";
    backButton.hidden = currentStep === 0;
    nextButton.hidden = true;
    return;
  }

  if (currentStep === questions.length) {
    formStageLabel.textContent = "Contact details";
    progressCopy.textContent = "Final details";
    progressFill.style.width = "100%";
    backButton.hidden = false;
    nextButton.hidden = false;
    nextButton.textContent = "Submit Application";
    nextButton.disabled = false;
  }
}

function renderQuestionStep(question, index) {
  const selected = responses.qualification[question.id];
  const optionsMarkup = question.options.map((option) => {
    const isSelected = selected && selected.label === option.label;
    return (
      '<button type="button" class="option-btn' + (isSelected ? " is-selected" : "") + '" data-option="' + escapeHtml(option.label) + '">' +
        '<span class="option-copy">' +
          '<strong>' + escapeHtml(option.label) + '</strong>' +
          '<span>' + escapeHtml(option.hint) + '</span>' +
        '</span>' +
        '<span class="option-mark" aria-hidden="true"></span>' +
      "</button>"
    );
  }).join("");

  formStage.innerHTML =
    '<div class="question-panel">' +
      '<span class="question-lead">Qualification step ' + (index + 1) + "</span>" +
      '<h2 class="question-title">' + escapeHtml(question.prompt) + "</h2>" +
      '<div class="option-list">' + optionsMarkup + "</div>" +
    "</div>";

  formStage.querySelectorAll(".option-btn").forEach((button) => {
    button.addEventListener("click", () => {
      const selectedLabel = button.getAttribute("data-option");
      const selectedOption = question.options.find((option) => option.label === selectedLabel);
      responses.qualification[question.id] = {
        label: selectedOption.label
      };

      formStage.querySelectorAll(".option-btn").forEach((item) => item.classList.remove("is-selected"));
      button.classList.add("is-selected");

      window.setTimeout(() => {
        if (currentStep < questions.length - 1) {
          currentStep += 1;
          renderStep();
        } else {
          currentStep = questions.length;
          renderStep();
        }
      }, 180);
    });
  });
}

function renderContactStep() {
  const stateOptions = ['<option value="">Select your state / city</option>']
    .concat(jobSectorOptions.map((option) => '<option value="' + escapeHtml(option) + '">' + escapeHtml(option) + "</option>"))
    .join("");

  formStage.innerHTML =
    '<div class="contact-panel">' +
      '<span class="contact-helper">Contact details</span>' +
      '<h2 class="contact-title">Share your details so we can guide you to the most suitable next step.</h2>' +
      '<p class="field-note">Once you submit, your answers and contact details will move through the existing Leadway submission flow already connected to Google Sheets.</p>' +
      '<div class="contact-grid">' +
        '<div class="field span-2">' +
          '<label for="fullName">Full name</label>' +
          '<input id="fullName" name="full_name" type="text" autocomplete="name" placeholder="Enter your full name" value="' + escapeHtml(responses.contact.full_name) + '" required>' +
        "</div>" +
        '<div class="field">' +
          '<label for="email">Email address</label>' +
          '<input id="email" name="email" type="email" autocomplete="email" placeholder="you@example.com" value="' + escapeHtml(responses.contact.email) + '" required>' +
        "</div>" +
        '<div class="field">' +
          '<label for="phone">Phone number</label>' +
          '<input id="phone" name="phone" type="tel" inputmode="tel" autocomplete="tel" placeholder="08012345678" value="' + escapeHtml(responses.contact.phone) + '" required>' +
        "</div>" +
        '<div class="field">' +
          '<label for="state">State / city <span style="font-weight: 500; color: var(--ink-500);">(optional)</span></label>' +
          '<input id="state" name="state" type="text" autocomplete="address-level1" placeholder="Lagos" value="' + escapeHtml(responses.contact.state) + '">' +
        "</div>" +
        '<div class="field">' +
          '<label for="jobSector">Job sector</label>' +
          '<select id="jobSector" name="job_sector" required>' + stateOptions + "</select>" +
        "</div>" +
        '<div class="field span-2">' +
          '<label for="hasRsa">Do you currently have an RSA with Leadway Pensure PFA?</label>' +
          '<select id="hasRsa" name="has_rsa" required>' +
            '<option value="">Select an option</option>' +
            '<option value="yes">Yes</option>' +
            '<option value="no">No</option>' +
          "</select>" +
        "</div>" +
      "</div>" +
      '<p class="status-note" id="formStatus">By continuing, you agree to be contacted by Leadway Pensure.</p>' +
    "</div>";

  const jobSector = document.getElementById("jobSector");
  const hasRsa = document.getElementById("hasRsa");
  jobSector.value = responses.contact.job_sector || "";
  hasRsa.value = responses.contact.has_rsa || "";

  ["fullName", "email", "phone", "state", "jobSector", "hasRsa"].forEach((id) => {
    const field = document.getElementById(id);
    field.addEventListener("input", syncContactValues);
    field.addEventListener("change", syncContactValues);
  });
}

function syncContactValues() {
  responses.contact.full_name = document.getElementById("fullName").value.trim();
  responses.contact.email = document.getElementById("email").value.trim();
  responses.contact.phone = document.getElementById("phone").value.trim();
  responses.contact.state = document.getElementById("state").value.trim();
  responses.contact.job_sector = document.getElementById("jobSector").value;
  responses.contact.has_rsa = document.getElementById("hasRsa").value;
}

function validateContactStep() {
  syncContactValues();

  if (!responses.contact.full_name || !responses.contact.email || !responses.contact.phone || !responses.contact.job_sector || !responses.contact.has_rsa) {
    updateStatus("Please complete the required contact fields before continuing.", "error");
    return false;
  }

  const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  if (!emailPattern.test(responses.contact.email)) {
    updateStatus("Please enter a valid email address.", "error");
    return false;
  }

  updateStatus("Your details look good. Ready to submit.", "");
  return true;
}

function updateStatus(message, type) {
  const statusNode = document.getElementById("formStatus");
  if (!statusNode) return;
  statusNode.textContent = message;
  statusNode.classList.remove("error", "success");
  if (type) statusNode.classList.add(type);
}

function splitFullName(fullName) {
  const cleanName = fullName.replace(/\s+/g, " ").trim();
  if (!cleanName) {
    return { firstname: "", lastname: "" };
  }

  const parts = cleanName.split(" ");
  if (parts.length === 1) {
    return { firstname: parts[0], lastname: parts[0] };
  }

  return {
    firstname: parts.shift(),
    lastname: parts.join(" ")
  };
}

function buildSubmissionData() {
  const nameParts = splitFullName(responses.contact.full_name);
  const payload = new FormData();

  payload.set("firstname", nameParts.firstname);
  payload.set("lastname", nameParts.lastname);
  payload.set("email", responses.contact.email.trim().toLowerCase());
  payload.set("phone", responses.contact.phone.trim());
  payload.set("job_sector", responses.contact.job_sector);
  payload.set("has_rsa", responses.contact.has_rsa);

  payload.set("state", responses.contact.state);
  payload.set("score", "");

  questions.forEach((question) => {
    const answer = responses.qualification[question.id];
    payload.set(question.fieldName, answer ? answer.label : "");
  });

  return payload;
}

function submitExistingFlow() {
  if (isSubmitting) return;

  const payload = buildSubmissionData();
  const submitButton = nextButton;
  isSubmitting = true;

  if (submitButton) {
    submitButton.disabled = true;
    submitButton.textContent = "Submitting...";
  }

  updateStatus("Submitting your details...", "");

  /*
    Preserved Google Apps Script submission flow:
    - same scriptUrl
    - duplicate handling based on backend response code
    - same sessionStorage access token behavior
    - same success redirect to the thank-you page
  */
  fetch(scriptUrl, {
    method: "POST",
    body: payload
  })
    .then(async (response) => {
      if (!response.ok) {
        throw new Error("Network response was not ok.");
      }
      return response.json();
    })
    .then((data) => {
      if (data && data.ok === false && data.code === "DUPLICATE") {
        updateStatus(data.message || "This email or phone number has already been submitted.", "error");
        isSubmitting = false;
        if (submitButton) {
          submitButton.disabled = false;
          submitButton.textContent = "Submit Application";
        }
        return;
      }

      if (!data || data.ok !== true) {
        throw new Error("Unexpected response from submission endpoint.");
      }

      updateStatus("Submission successful. Redirecting...", "success");
      sessionStorage.setItem(ACCESS_KEY, String(Date.now()));
      window.location.href = "thank-you";
    })
    .catch((error) => {
      console.error(error);
      updateStatus("Could not submit form. Please try again in a moment.", "error");
      isSubmitting = false;
      if (submitButton) {
        submitButton.disabled = false;
        submitButton.textContent = "Submit Application";
      }
    });
}

backButton.addEventListener("click", () => {
  if (currentStep === 0) return;
  currentStep -= 1;
  renderStep();
});

nextButton.addEventListener("click", () => {
  if (currentStep === questions.length && validateContactStep()) {
    submitExistingFlow();
  }
});

document.querySelectorAll(".faq-trigger").forEach((button) => {
  button.addEventListener("click", () => {
    const item = button.closest(".faq-item");
    const isOpen = item.classList.contains("is-open");

    document.querySelectorAll(".faq-item").forEach((faqItem) => {
      faqItem.classList.remove("is-open");
      faqItem.querySelector(".faq-trigger").setAttribute("aria-expanded", "false");
    });

    if (!isOpen) {
      item.classList.add("is-open");
      button.setAttribute("aria-expanded", "true");
    }
  });
});

function escapeHtml(value) {
  return String(value)
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;")
    .replace(/'/g, "&#39;");
}

renderStep();
