document.addEventListener("DOMContentLoaded", () => {
  const form = document.querySelector("[data-scorecard]");
  const result = document.querySelector("[data-scorecard-result]");
  if (!form || !result) return;

  const steps = [...form.querySelectorAll("[data-audit-step]")];
  const progressLabel = form.querySelector("[data-progress-label]");
  const progressPercent = form.querySelector("[data-progress-percent]");
  const progressBar = form.querySelector("[data-progress-bar]");
  const messageInput = result.querySelector("[data-scorecard-message]");
  const leadForm = result.querySelector(".scorecard-lead-form");
  let currentStep = 0;
  let currentResultMessage = "";

  const showStep = (index) => {
    currentStep = Math.max(0, Math.min(index, steps.length - 1));
    steps.forEach((step, stepIndex) => {
      step.hidden = stepIndex !== currentStep;
    });
    const percent = Math.round(((currentStep + 1) / steps.length) * 100);
    progressLabel.textContent = `Category ${currentStep + 1} of ${steps.length}`;
    progressPercent.textContent = `${percent}%`;
    progressBar.style.width = `${percent}%`;
  };

  const incompleteQuestion = (step) =>
    [...step.querySelectorAll(".audit-question")].find(
      (question) => !question.querySelector("input:checked"),
    );

  const requireCurrentStep = () => {
    const incomplete = incompleteQuestion(steps[currentStep]);
    if (!incomplete) return true;

    incomplete.classList.remove("needs-answer");
    window.requestAnimationFrame(() =>
      incomplete.classList.add("needs-answer"),
    );
    incomplete.scrollIntoView({ behavior: "smooth", block: "center" });
    incomplete.querySelector("input").focus({ preventScroll: true });
    return false;
  };

  const categoryTotals = () => {
    const totals = {};
    steps.forEach((step) => {
      totals[step.dataset.category] = [
        ...step.querySelectorAll("input:checked"),
      ].reduce((sum, input) => sum + Number(input.value), 0);
    });
    return totals;
  };

  const recommendationFor = (score) => {
    if (score >= 80) {
      return {
        title: "Retain and refine",
        copy: "Your logo has useful equity. Protect its recognisable features and correct only specific consistency, usability, or technical gaps.",
      };
    }
    if (score >= 60) {
      return {
        title: "Strategic refresh",
        copy: "The foundation is working, but the identity needs simplification or modernisation. Preserve recognition while improving flexibility and polish.",
      };
    }
    if (score >= 40) {
      return {
        title: "Logo redesign",
        copy: "Your current logo is limiting trust, usability, or growth. Revisit its idea, structure, and execution with a clear business strategy.",
      };
    }
    return {
      title: "Rebuild from strategy",
      copy: "Very little existing visual equity is working. Start with audience, positioning, and brand personality before developing a new identity.",
    };
  };

  const calculateResult = () => {
    const totals = categoryTotals();
    const total = Object.values(totals).reduce((sum, score) => sum + score, 0);
    const recommendation = recommendationFor(total);

    result.querySelector("[data-total-score]").textContent = total;
    result.querySelector("[data-result-title]").textContent =
      recommendation.title;
    result.querySelector("[data-result-copy]").textContent =
      recommendation.copy;
    result.querySelector("[data-result-meter]").style.width = `${total}%`;

    Object.entries(totals).forEach(([category, score]) => {
      const output = result.querySelector(
        `[data-category-score="${category}"]`,
      );
      if (output) output.textContent = `${score}/25`;
    });

    currentResultMessage = [
      `Interactive logo redesign audit: ${total}/100 - ${recommendation.title}.`,
      `Recognition ${totals.recognition}/25;`,
      `Flexibility ${totals.flexibility}/25;`,
      `Differentiation ${totals.relevance}/25;`,
      `Trust ${totals.trust}/25.`,
      "Requested the full Logo Redesign Scorecard PDF on WhatsApp.",
    ].join(" ");
    messageInput.value = currentResultMessage;

    form.hidden = true;
    result.hidden = false;
    result.scrollIntoView({ behavior: "smooth", block: "start" });
  };

  form.querySelectorAll("[data-audit-next]").forEach((button, index) => {
    button.addEventListener("click", () => {
      if (!requireCurrentStep()) return;
      if (index === steps.length - 1) {
        calculateResult();
        return;
      }
      showStep(currentStep + 1);
      form.scrollIntoView({ behavior: "smooth", block: "start" });
    });
  });

  form.querySelectorAll("[data-audit-back]").forEach((button) => {
    button.addEventListener("click", () => {
      showStep(currentStep - 1);
      form.scrollIntoView({ behavior: "smooth", block: "start" });
    });
  });

  form.querySelectorAll(".audit-question input").forEach((input) => {
    input.addEventListener("change", () => {
      input.closest(".audit-question").classList.remove("needs-answer");
    });
  });

  result
    .querySelector("[data-scorecard-restart]")
    .addEventListener("click", () => {
      form.reset();
      currentResultMessage = "";
      messageInput.value = "";
      result.hidden = true;
      form.hidden = false;
      showStep(0);
      form.scrollIntoView({ behavior: "smooth", block: "start" });
    });

  if (leadForm) {
    leadForm.addEventListener("reset", () => {
      window.requestAnimationFrame(() => {
        messageInput.value = currentResultMessage;
      });
    });
  }

  showStep(0);
});
