/* ===================== INDUSTRY PICKER + QUIZ ===================== */
function Industries() {
  const [mode, setMode] = React.useState("industry"); // industry | quiz
  const switchToQuiz = () => {
    setMode("quiz");
    setTimeout(() => {
      const el = document.getElementById("industries");
      if (el) el.scrollIntoView({ behavior: "smooth", block: "start" });
    }, 0);
  };
  return (
    <section id="industries" className="industries" data-screen-label="03 Industries">
      <div className="container">
        <div className="industries-head">
          <div>
            <span className="eyebrow">Which one sounds like you?</span>
            <h2 className="h-1">Start where you are.</h2>
            <p className="lede" style={{marginTop: "14px"}}>Pick your industry or take the 30-second quiz. We'll point you in the right direction — no pressure, no sales-y stuff.</p>
          </div>
          <div className="seg-toggle" role="tablist">
            <button onClick={() => setMode("industry")} className={mode === "industry" ? "on" : ""}>By industry</button>
            <button onClick={() => setMode("quiz")} className={mode === "quiz" ? "on" : ""}>30-sec quiz</button>
          </div>
        </div>
        {mode === "industry" ? <IndustryGrid onStart={switchToQuiz} /> : <Quiz />}
      </div>
    </section>
  );
}

function IndustryGrid({ onStart }) {
  const [hovered, setHovered] = React.useState(null);
  const tierFor = (id) => TIERS.find((t) => t.id === id);
  return (
    <div className="industry-grid">
      {INDUSTRIES.map((ind) => {
        const tier = tierFor(ind.tier);
        return (
          <div
            key={ind.id}
            className="industry-card"
            onMouseEnter={() => setHovered(ind.id)}
            onMouseLeave={() => setHovered(null)}
            onClick={onStart}
            role="button"
            tabIndex={0}
          >
            <div className="industry-art">
              <div className="industry-glyph" style={{ color: tier.color }}>
                {ind.img
                  ? <img src={ind.img} alt={ind.label} style={{ width: "104px", height: "104px", objectFit: "contain" }} />
                  : React.createElement(Icon[ind.icon])}
              </div>
              <div className="industry-pattern" />
            </div>
            <div className="industry-body">
              <h3 className="h-3">{ind.label}</h3>
              <p className="industry-sub">{ind.sub}</p>
              <div className="industry-foot">
                <span className="chip chip-green"><span className="dot" /> Likely fit · {tier.label}</span>
                <button type="button" className="industry-link" onClick={(e) => { e.stopPropagation(); onStart && onStart(); }}>
                  Start here <Icon.arrow />
                </button>
              </div>
            </div>
          </div>
        );
      })}
    </div>
  );
}

const QUIZ_QUESTIONS = [
  {
    q: "Where are you today?",
    options: [
      { l: "Don't have a website (or it's awful)", v: { launch: 3 } },
      { l: "Have a site but it's not bringing customers", v: { grow: 3, launch: 1 } },
      { l: "Drowning in admin / spreadsheets", v: { scale: 3 } },
      { l: "Doing fine — looking for an edge", v: { "adopt-ai": 3, scale: 1 } },
    ],
  },
  {
    q: "What would help most right now?",
    options: [
      { l: "Be findable on Google", v: { launch: 2, grow: 1 } },
      { l: "More leads / bookings", v: { grow: 3 } },
      { l: "Less paperwork", v: { scale: 3 } },
      { l: "Save hours every week", v: { "adopt-ai": 3, scale: 1 } },
    ],
  },
  {
    q: "Budget you're comfortable with?",
    options: [
      { l: "Under £1,000", v: { launch: 2 } },
      { l: "£1,000–£3,000", v: { grow: 2, "adopt-ai": 1 } },
      { l: "£3,000–£7,500", v: { scale: 2, "adopt-ai": 1 } },
      { l: "Whatever it takes — get it right", v: { scale: 2, "adopt-ai": 2 } },
    ],
  },
];

function Quiz() {
  const [step, setStep] = React.useState(0);
  const [scores, setScores] = React.useState({ launch: 0, grow: 0, scale: 0, "adopt-ai": 0 });

  const choose = (opt) => {
    const next = { ...scores };
    Object.entries(opt.v).forEach(([k, v]) => (next[k] = (next[k] || 0) + v));
    setScores(next);
    setStep(step + 1);
  };

  // Persist result so the contact form can pre-fill — must be before any early return
  React.useEffect(() => {
    if (step >= QUIZ_QUESTIONS.length) {
      const winner = Object.entries(scores).sort((a, b) => b[1] - a[1])[0][0];
      const tier = TIERS.find((t) => t.id === winner);
      try {
        localStorage.setItem("smbe_quiz", JSON.stringify({ id: winner, label: tier.label, ts: Date.now() }));
      } catch(e) {}
    }
  }, [step]);

  if (step >= QUIZ_QUESTIONS.length) {
    const winner = Object.entries(scores).sort((a, b) => b[1] - a[1])[0][0];
    const tier = TIERS.find((t) => t.id === winner);
    return (
      <div className="quiz-result">
        <div className="qr-card">
          <span className="chip chip-orange"><Icon.sparkle /> Your recommended starting point</span>
          <h3 className="h-1" style={{marginTop: "20px"}}>Start with <span style={{color: "var(--green-deep)"}}>{tier.label}</span>.</h3>
          <p className="lede" style={{marginTop: "14px"}}>{tier.headline} {tier.blurb}</p>
          <div className="qr-actions">
            <a className="btn btn-accent btn-lg" href={`tiers/${tier.id}.html`}>See {tier.label} plan <Icon.arrow /></a>
            <button className="btn btn-ghost btn-lg" onClick={() => { setStep(0); setScores({ launch: 0, grow: 0, scale: 0, "adopt-ai": 0 }); }}>
              Retake quiz
            </button>
          </div>
        </div>
        <div className="qr-side">
          <div className="qr-side-h">How you scored</div>
          {Object.entries(scores).map(([k, v]) => {
            const t = TIERS.find((t) => t.id === k);
            const max = Math.max(...Object.values(scores));
            return (
              <div key={k} className="qr-bar">
                <div className="qr-bar-label">
                  <span>{t.label}</span>
                  <span style={{color: "var(--ink-3)"}}>{v}</span>
                </div>
                <div className="qr-bar-track">
                  <div className="qr-bar-fill" style={{width: `${(v / Math.max(1, max)) * 100}%`, background: t.color}} />
                </div>
              </div>
            );
          })}
        </div>
      </div>
    );
  }

  const cur = QUIZ_QUESTIONS[step];
  return (
    <div className="quiz">
      <div className="quiz-progress">
        {QUIZ_QUESTIONS.map((_, i) => (
          <div key={i} className={"qp-dot" + (i <= step ? " on" : "")} />
        ))}
        <span className="qp-label">Question {step + 1} of {QUIZ_QUESTIONS.length}</span>
      </div>
      <h3 className="h-1 quiz-q">{cur.q}</h3>
      <div className="quiz-options">
        {cur.options.map((opt, i) => (
          <button key={i} className="quiz-opt" onClick={() => choose(opt)}>
            <span className="quiz-opt-marker">{String.fromCharCode(65 + i)}</span>
            <span>{opt.l}</span>
            <Icon.arrow />
          </button>
        ))}
      </div>
    </div>
  );
}

window.Industries = Industries;
