jQuery(document).ready(function($){
  const questions = [
    {
      q: "Why Do You Usually Place a Bet?",
      a: {A: "For Fun", B: "I’ve Researched", C: "Big Payday", D: "Tested Strategy", E: "Gut Feeling"}
    },
    {
      q: "How Do You Pick Your Bets?",
      a: {A: "Feels Right", B: "Analyze Data", C: "Big Odds", D: "Use System", E: "Momentum"}
    },
    {
      q: "What’s Your Betting Style?",
      a: {A: "Casual", B: "Calculated", C: "Aggressive", D: "Disciplined", E: "Intuitive"}
    },
    {
      q: "How Often Do You Track Your Bets?",
      a: {A: "Never", B: "Every Bet", C: "Big Wins Only", D: "With Notes and Trends", E: "Sometimes"}
    },
    {
      q: "What Would Your Dream Win Look Like?",
      a: {A: "Fun Parlay", B: "5% ROI", C: "Huge Underdog", D: "Beat Market", E: "Buzzer-Beater"}
    },
    {
      q: "What Frustrates You Most About Betting?",
      a: {A: "Complicated Odds", B: "Missed Value", C: "1 Leg Short", D: "Emotions", E: "Bad Luck"}
    },
    {
      q: "Pick a Motto:",
      a: {A: "For the Buzz", B: "Data Never Lies", C: "Go Big", D: "Steady Wins", E: "Trust Instinct"}
    }
  ];

  let current = 0;
  let answers = [];

  function showQuestion(index) {
    let q = questions[index];
    let html = `<h3>${q.q}</h3>`;
    for (let [key, value] of Object.entries(q.a)) {
      html += `<label><input type="radio" name="question" value="${key}"> ${value}</label><br>`;
    }
    $('#bppq-steps').html(html);
    if (answers[index]) {
      $(`input[name="question"][value="${answers[index]}"]`).prop('checked', true);
    }
  }

  $('#bppq-next').click(function(){
    let val = $('input[name="question"]:checked').val();
    if (!val) return alert("Please select an answer");
    answers[current] = val;

    if (current + 1 < questions.length) {
      current++;
      showQuestion(current);
      $('#bppq-prev').prop('disabled', false);
    } else {
      const counts = answers.reduce((acc, letter) => {
        acc[letter] = (acc[letter] || 0) + 1;
        return acc;
      }, {});
      const topLetter = Object.entries(counts).sort((a, b) => b[1] - a[1])[0][0];

      const typeLabels = {
        A: 'The Casual Bettor',
        B: 'The Analyst',
        C: 'The Risk-Taker',
        D: 'The Grinder',
        E: 'The Gut-Player'
      };
      const result = typeLabels[topLetter] || 'Unknown';

      window.finalPersonality = result;
      $('#bppq-quiz-form').hide();
      $('#bppq-personality').text(result);

      // Force PDF link as button
      const pdfUrl = `${bppq_ajax_obj.ajax_url}?action=generate_pdf&personality=${topLetter}`;
      const pdfLinkHtml = `<div style="margin: 15px 0;"><a href="${pdfUrl}" target="_blank" style="background-color:#004aad; color:white; padding:10px 20px; text-decoration:none; border-radius:5px; display:inline-block;">📄 Download Your Full Betting Style Report</a></div>`;
      $('#bppq-result').prepend(pdfLinkHtml);

      $('#bppq-result').show();
    }
  });

  $('#bppq-prev').click(function(){
    if (current > 0) {
      current--;
      showQuestion(current);
      if (current === 0) $(this).prop('disabled', true);
    }
  });

  $('#bppq-submit').click(function(){
    let email = $('#bppq-email').val();
    if (!email) return alert("Please enter an email");
    $.post(bppq_ajax_obj.ajax_url, {
      action: 'bppq_submit_quiz',
      answers: answers,
      personality: window.finalPersonality,
      email: email
    }, function(response){
      if (response.success) {
        alert("Your full report is on the way!");
      } else {
        alert("Submission failed. " + (response.data?.message || ""));
      }
    });
  });

  showQuestion(current);
});
