/* Quiz - 10 questions, focus-area output. */
const { useState, useEffect, useMemo } = React;

const QUESTIONS = [
  {
    q: "How do you feel about using AI in your organisation?",
    options: ["Ready to start", "Curious but cautious", "Concerned about the risks", "Sceptical it will work"]
  },
  {
    q: "Do you have leadership buy-in?",
    options: ["Actively pushing for it", "Open to a concrete proposal", "Cautious, not opposed", "Not a priority right now"]
  },
  {
    q: "Are there people who would resist change?",
    options: ["No, the team is open", "A few individuals", "Significant resistance expected", "We have not thought about it"]
  },
  {
    q: "Is there an internal champion who could own this?",
    options: ["Yes, ready to lead", "Possibly, needs support", "No one obvious", "Not yet discussed"]
  },
  {
    q: "What is the level of overall digital and data literacy on your team?",
    options: [
      "Staff are experienced with data analysis and familiar with tools such as Python, R, PowerBI or AI tools for data analysis.",
      "Staff have some familiarity with data analysis and work well in Excel.",
      "Staff do a lot of qualitative work but do not have much experience with data analysis, interpretation, or working with tools such as Excel.",
      "Staff mostly work with PDFs or paper files and do not have a strong understanding of digital tools."
    ]
  },
  {
    q: "Do you have engineers or technical staff?",
    options: ["Yes, in-house team", "Some technical capacity", "We rely on external help", "No technical capacity"]
  },
  {
    q: "Have you built any AI projects before?",
    options: ["Yes, successfully", "Tried with mixed results", "Small experiments only", "This would be our first"]
  },
  {
    q: "What is your biggest concern about AI?",
    options: ["Data privacy and security", "Bias or unfair outcomes", "Staff losing jobs", "I do not have major concerns"]
  },
  {
    q: "How good and available is your data?",
    options: ["Clean, structured, and accessible", "Exists but needs cleaning or consolidation", "Incomplete or mostly undigitised", "We do not have relevant data"]
  },
  {
    q: "How clear are you on the problem you want to solve?",
    options: ["Very clear", "A few ideas, not decided", "Something needs to change but not sure what", "Have not identified problems"]
  }
];

// answers is array of indices 0..3 (or -1 for unanswered)
function computeFocus(answers) {
  const a = answers; // q1 = a[0], q2 = a[1], ...
  const get = (i) => a[i - 1];

  const buyIn = get(2) >= 2 || get(3) === 2 || get(4) === 2;
  const concerns = get(1) >= 2 || (get(8) >= 0 && get(8) <= 2);
  const partner = get(6) >= 2 || get(7) === 3;
  const data = get(9) >= 2;
  const ready = [2,3,4,5,6,7,9].every((i) => {
    const v = get(i); return v === 0 || v === 1;
  });

  return [
    {
      key: "buy-in", active: buyIn,
      title: "Build buy-in first",
      why: "Triggered by Q2 (cautious / not a priority), Q3 (significant resistance), or Q4 (no obvious champion).",
      actions: [
        "Identify your champion and get their commitment before starting anything else.",
        "Book 30 minutes with leadership to discuss one specific problem AI could solve.",
        "Share a relevant case study from the AI menu with leadership."
      ]
    },
    {
      key: "concerns", active: concerns,
      title: "Address concerns before starting",
      why: "Triggered by Q1 (concerned / sceptical) or Q8 (privacy, bias, or jobs).",
      actions: [
        "Run a short \u201cwhat worries us about AI\u201d session with your team to bring concerns into the open.",
        "Map which data is sensitive vs. safe to use before choosing a solution.",
        "Start with a low-risk use case: text summarisation or document search."
      ]
    },
    {
      key: "partner", active: partner,
      title: "Find a technical partner",
      why: "Triggered by Q6 (rely on external / no capacity) or Q7 (first project).",
      actions: [
        "Be clear on the problem before approaching any technical partner. They should fit your needs.",
        "Contact IGC to explore support options.",
        "Scope a small proof of concept with a partner before committing to a full build."
      ]
    },
    {
      key: "data", active: data,
      title: "Sort your data first",
      why: "Triggered by Q9 (incomplete or no relevant data).",
      actions: [
        "Spend one hour mapping where your data lives: who has it, in what format.",
        "Identify the one dataset you would most want to use and find out how to access it.",
        "Consider digitisation, text analysis or AI-powered search \u2014 these need less data to start."
      ]
    },
    {
      key: "ready", active: ready,
      title: "You\u2019re ready! Go to Step 2",
      why: "Most answers in the first two options across Q2\u2013Q9.",
      actions: [
        "Run Step 2 with your team: identify your top one or two problems.",
        "Set a 3-month goal: what do you want to have piloted?",
        "Connect with IGC to identify potential support."
      ]
    }
  ];
}

function readinessScore(answers) {
  // score = average of (3 - index) across answered Qs, normalised to 0..100
  const scored = answers.filter((v) => v >= 0);
  if (!scored.length) return 0;
  const total = scored.reduce((s, v) => s + (3 - v), 0);
  return Math.round((total / (scored.length * 3)) * 100);
}

function readinessLabel(score) {
  if (score >= 75) return "Strong";
  if (score >= 50) return "Developing";
  if (score >= 25) return "Early";
  return "Not yet";
}

function Quiz() {
  const [answers, setAnswers] = useState(() => {
    try {
      const saved = JSON.parse(localStorage.getItem("igc.quiz.v1") || "null");
      if (Array.isArray(saved) && saved.length === 10) return saved;
    } catch {}
    return new Array(10).fill(-1);
  });
  const [current, setCurrent] = useState(0);
  const [showResult, setShowResult] = useState(false);
  const [pacing, setPacing] = useState(() => (window.IGC && window.IGC.getTweaks().quizPacing) || "one");

  useEffect(() => {
    const onChange = (e) => setPacing(e.detail.quizPacing);
    document.addEventListener("igc:tweakschange", onChange);
    document.documentElement.dataset.quizPacing = pacing;
    return () => document.removeEventListener("igc:tweakschange", onChange);
  }, [pacing]);
  useEffect(() => { document.documentElement.dataset.quizPacing = pacing; }, [pacing]);

  useEffect(() => {
    localStorage.setItem("igc.quiz.v1", JSON.stringify(answers));
  }, [answers]);

  const setAnswer = (qi, oi) => {
    const next = answers.slice(); next[qi] = oi; setAnswers(next);
    if (pacing === "one" && qi === current && current < 9) {
      setTimeout(() => setCurrent(qi + 1), 220);
    }
  };

  const allAnswered = answers.every((v) => v >= 0);
  const focus = useMemo(() => computeFocus(answers), [answers]);
  const score = useMemo(() => readinessScore(answers), [answers]);

  if (showResult) {
    return <Result answers={answers} focus={focus} score={score} onRedo={() => { setShowResult(false); setCurrent(0); }} />;
  }

  if (pacing === "all") {
    return (
      <div className="quiz-shell">
        <div className="quiz-card">
          <h2 style={{color: "var(--igc-purple)", marginBottom: "8px"}}>Answer all ten questions</h2>
          <p className="muted">Your answers are saved automatically. When you reach the end, generate your action plan.</p>
          {QUESTIONS.map((q, qi) => (
            <div key={qi} className="quiz-q-block">
              <div className="quiz-q-num">Question {qi + 1} of 10</div>
              <h3 className="quiz-q-text">{q.q}</h3>
              <div className="quiz-options">
                {q.options.map((opt, oi) => (
                  <button key={oi}
                    className={"quiz-option" + (answers[qi] === oi ? " is-selected" : "")}
                    onClick={() => setAnswer(qi, oi)}>
                    <span className="quiz-option-mark"></span><span>{opt}</span>
                  </button>
                ))}
              </div>
            </div>
          ))}
          <div className="quiz-actions" style={{marginTop: "var(--space-5)"}}>
            <span className="muted">{answers.filter((v) => v >= 0).length} of 10 answered</span>
            <button className="btn btn--primary btn--lg" disabled={!allAnswered} onClick={() => setShowResult(true)}>
              See my focus areas <span className="arrow">→</span>
            </button>
          </div>
        </div>
      </div>
    );
  }

  // One-at-a-time
  const q = QUESTIONS[current];
  return (
    <div className="quiz-shell">
      <aside className="quiz-rail">
        <h4>Your progress</h4>
        <div className="quiz-progress">
          {QUESTIONS.map((_, i) => (
            <div key={i} className={"quiz-progress-tick" + (answers[i] >= 0 ? " is-done" : "") + (i === current ? " is-current" : "")}></div>
          ))}
        </div>
        <div className="quiz-counter"><strong>{current + 1}</strong> of 10 &nbsp; <span style={{color:"var(--igc-grey-500)"}}>{answers.filter((v) => v >= 0).length} answered</span></div>
        <div style={{marginTop: "var(--space-4)"}}>
          <p className="muted" style={{fontSize: "13px", margin: 0}}>Answer honestly. There are no right or wrong answers - the goal is to know where to focus your energy first.</p>
        </div>
      </aside>
      <div className="quiz-card">
        <div className="quiz-q-num">Question {current + 1} of 10</div>
        <h3 className="quiz-q-text">{q.q}</h3>
        <div className="quiz-options">
          {q.options.map((opt, oi) => (
            <button key={oi}
              className={"quiz-option" + (answers[current] === oi ? " is-selected" : "")}
              onClick={() => setAnswer(current, oi)}>
              <span className="quiz-option-mark"></span><span>{opt}</span>
            </button>
          ))}
        </div>
        <div className="quiz-actions">
          <button className="btn btn--ghost" disabled={current === 0} onClick={() => setCurrent(current - 1)}>← Back</button>
          {current < 9 ? (
            <button className="btn btn--primary" disabled={answers[current] < 0} onClick={() => setCurrent(current + 1)}>
              Next <span className="arrow">→</span>
            </button>
          ) : (
            <button className="btn btn--primary btn--lg" disabled={!allAnswered} onClick={() => setShowResult(true)}>
              See my focus areas <span className="arrow">→</span>
            </button>
          )}
        </div>
      </div>
    </div>
  );
}

function Result({ answers, focus, score, onRedo }) {
  const activeCount = focus.filter((f) => f.active).length;
  const label = readinessLabel(score);
  return (
    <div>
      <div className="result-hero">
        <span className="eyebrow">Your readiness profile</span>
        <h2>{activeCount === 1 && focus.find((f) => f.active && f.key === "ready")
          ? "You\u2019re ready. Go to Step 2."
          : `Focus on ${activeCount} ${activeCount === 1 ? "area" : "areas"} before you build.`}</h2>
        <p>Based on your ten answers, the website highlighted the focus areas below. Most teams have one or two - work through those first, then move on to Step 2.</p>
        <div className="result-meter">
          <span className="result-meter-label">Readiness</span>
          <div className="result-meter-bar"><i style={{width: `${score}%`}}></i></div>
          <span className="result-meter-value">{label} &nbsp;<em style={{fontStyle:"normal",color:"var(--igc-grey-700)"}}>{score}%</em></span>
        </div>
      </div>

      <div className="row row--between mb-4 no-print">
        <div className="muted" style={{fontSize: 14}}>Print this page for a one-page action plan you can take into a workshop.</div>
        <div className="row" style={{gap: 8}}>
          <button className="btn btn--ghost btn--sm" onClick={() => window.print()}>Print one-pager</button>
          <button className="btn btn--ghost btn--sm" onClick={onRedo}>Restart quiz</button>
          <a className="btn btn--primary btn--sm" href="step-2.html">Continue to Step 2 →</a>
        </div>
      </div>

      <div className="result-grid">
        {focus.map((f) => (
          <article key={f.key} className={"focus-area " + (f.active ? "is-active" : "is-inactive")}>
            <header className="focus-area-head">
              <h3>{f.title}</h3>
              <span className={"status " + (f.active ? "on" : "off")}>{f.active ? "Apply" : "Not now"}</span>
            </header>
            <p className="why">{f.why}</p>
            <ul>
              {f.actions.map((act, i) => (
                <li key={i}><span className="arrow">→</span><span>{act}</span></li>
              ))}
            </ul>
          </article>
        ))}
      </div>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("quiz-root")).render(<Quiz />);
