/* global React, BgGear, IconArrow, IconCheck */
const { useState: chcUseState } = React;

const chcQuestions = [
  {
    theme: "Career fulfilment",
    text: "When you think honestly about your career in HR right now, which feels most true?",
    opts: [
      { text: "Something feels off but I can't quite name it, I just know I'm not as satisfied as I once was", profile: "a" },
      { text: "I can see where I want to go, but I feel frozen, the gap between here and there feels too big to cross alone", profile: "b" },
      { text: "I know what I want to do next, but I'm scared of leaving behind a role I'm good at for something uncertain", profile: "c" },
      { text: "I've made the move, but I'm realising the challenges don't disappear, they just change shape", profile: "d" }
    ]
  },
  {
    theme: "Strengths & direction",
    text: "When it comes to deciding what's next in your career, what feels most honest?",
    opts: [
      { text: "I know what I'm uniquely brilliant at and I'm using it as my compass for what comes next", profile: "a" },
      { text: "I have a sense of my strengths but haven't really examined them, I describe my experience more than what I'm built for", profile: "b" },
      { text: "I focus more on the gaps, the boxes I haven't ticked, than on what I genuinely bring", profile: "c" },
      { text: "I'm not sure I know my strengths well enough to use them as a guide, and that's part of what's holding me back", profile: "b" }
    ]
  },
  {
    theme: "Resilience & direction",
    text: "When you think honestly about the effort you put into your work, which feels most true right now?",
    opts: [
      { text: "The effort feels purposeful, I know what I'm working towards and it energises me", profile: "a" },
      { text: "I'm working hard but the sense of direction has quietly faded, I'm not sure what I'm building towards anymore", profile: "b" },
      { text: "I'm going through the motions, delivering what's expected but running on empty more often than I'd like to admit", profile: "c" },
      { text: "I've been here long enough to know something needs to change, I'm just not sure yet what that looks like", profile: "d" }
    ]
  },
  {
    theme: "Support & isolation",
    text: "When things get genuinely hard in your role, when the pressure is at its highest, where do you turn?",
    opts: [
      { text: "I have people around me who truly understand this level and what it demands, I don't carry it alone", profile: "a" },
      { text: "I have some support, but it doesn't quite reach the parts that are hardest, there are things I carry alone", profile: "b" },
      { text: "I mostly manage it privately, I've learned to absorb it and keep moving, because there isn't really anywhere else to go", profile: "c" },
      { text: "Honestly? There is no HR for HR. I figure it out alone, and the cost of that is starting to show", profile: "d" }
    ]
  },
  {
    theme: "Readiness",
    text: "Which of these best describes where you are right now?",
    opts: [
      { text: "I'm exploring, I want to understand my options before committing to anything", profile: "a" },
      { text: "I'm ready to invest in myself but want to start with a focused, structured programme", profile: "b" },
      { text: "I'm actively preparing for a move to a new or bigger role in the next six months", profile: "c" },
      { text: "I'm already in or stepping into a VP or CPO level role and I need the right support around me", profile: "d" }
    ]
  }
];

const chcProfiles = {
  a: {
    badge: "chc-badge--a",
    label: "The Quiet Searcher",
    headline: "You know something isn't quite right, and that feeling is worth listening to",
    body: "You're good at your job, probably very good, and from the outside everything looks fine. But there's a quiet restlessness that follows you. A sense that this can't be it. You haven't shared this with many people, perhaps anyone, because it's hard to explain a feeling you can't yet articulate. That's exactly where we start. Not with goals, but with you.",
    actions: [
      "Give yourself permission to take this seriously, the quiet feeling is data, not weakness",
      "Begin to separate what you are good at from what genuinely energises you, they are not always the same thing",
      "Consider whether you have anyone around you who truly understands the unique pressures of a senior HR career"
    ],
    pkgName: "Career Builder",
    pkgDesc: "Four focused coaching sessions with diagnostic exercises, designed to help you get clear on who you are, what you're built for, and what a fulfilling next step actually looks like for you.",
    pkgIncludes: [
      "Four coaching sessions",
      "Diagnostic exercises",
      "Clarity on your strengths and career direction"
    ],
    upgradeNote: "",
    elite: false
  },
  b: {
    badge: "chc-badge--b",
    label: "The Frozen High Achiever",
    headline: "You can see where you want to go, something is stopping you from moving",
    body: "You tell yourself you're not ready, that you need one more thing ticked off the list before you can make your move. The truth is, the gap between where you are and where you want to be feels enormous without someone to help you cross it. Staying still feels safer than falling. But the boxes are a distraction. What determines whether you can do the next role is not whether you've done it before, it's whether your strengths are the right fit. That reframe changes everything.",
    actions: [
      "Stop measuring yourself against a job description and start measuring yourself against your strengths, they are a far more accurate predictor of success",
      "Identify one person who has done the role you want and ask what actually made them successful, the answer will likely surprise you",
      "Name the single biggest thing holding you back and ask honestly whether it is real, or fear wearing the costume of reason"
    ],
    pkgName: "Career Navigator",
    pkgDesc: "You don't just need clarity, you need to understand what you're uniquely built for, evaluate whether the role you're moving toward plays to those strengths, and have a structured plan to land it successfully.",
    pkgIncludes: [
      "Six focused coaching sessions",
      "Diagnostic exercises",
      "Your individual strengths profile, report and feedback session",
      "A bespoke 90-day onboarding plan aligned to your new role"
    ],
    upgradeNote: "Already landed your new role and want to go deeper? Career Navigator can be extended or upgraded to Career Elite, which adds a full 360 report and coaching credits held for day 45 and day 90.",
    elite: false
  },
  c: {
    badge: "chc-badge--c",
    label: "The Capable but Scared",
    headline: "You know what you want, and somewhere, you know you're ready",
    body: "Leaving behind a role where you're respected and secure for something you haven't done before is genuinely frightening. The risk feels very real. But the fear you're feeling is not a signal to stop, it's a signal that this matters. The professionals who make the most significant career moves are not the ones who felt no fear. They're the ones who had the right support around them when they leapt, and beyond it.",
    actions: [
      "Build your network deliberately, identify people whose strengths complement yours, because a move into a new role means needing a new kind of team around you",
      "Have an honest conversation with someone who has made a similar leap, not to be reassured, but to be prepared",
      "Separate the practical risks from the emotional ones, they require very different responses"
    ],
    pkgName: "Career Navigator",
    pkgDesc: "Six coaching sessions, diagnostic exercises, your individual strengths profile, and a bespoke 90-day onboarding plan, structured support through the transition and into it.",
    pkgIncludes: [
      "Six coaching sessions",
      "Diagnostic exercises",
      "Your individual strengths profile, report and feedback session",
      "A bespoke 90-day onboarding plan aligned to your new role"
    ],
    upgradeNote: "",
    elite: false
  },
  d: {
    badge: "chc-badge--d",
    label: "Defining the Next Chapter",
    headline: "You've proven you can do it, now it's about doing it on your own terms",
    body: "You made the move. You did the hard thing, took the risk, and landed somewhere new. And yet here you are, still searching. The challenges didn't disappear, they changed shape. The pressure is different, the isolation perhaps more acute, and the question of what comes next is already forming. This is the chapter that most career support completely ignores. Everyone focuses on helping you get the role. Almost nobody helps you once you're in it. You don't have to figure this out alone.",
    actions: [
      "Revisit your strengths in the context of this new role, who you need to be here may be different from who you needed to be before",
      "Build your support structure intentionally, peers, mentors and thinking partners who understand this level and won't underestimate what you're carrying",
      "Consider whether a portfolio career might offer the autonomy and variety that the corporate model no longer can"
    ],
    pkgName: "Career Elite",
    pkgDesc: "Eight coaching sessions, your individual strengths profile, a full 360 report with bespoke feedback, and a customised 90-day onboarding plan, with two coaching credits held for day 45 and day 90 of your new role. Designed exclusively for those stepping into or already in VP or CPO level roles.",
    pkgIncludes: [
      "Eight coaching sessions",
      "Your individual strengths profile, report and bespoke feedback session",
      "Full 360 report combining strengths and feedback",
      "Customised 90-day onboarding plan",
      "Two coaching credits held for day 45 and day 90 of your new role"
    ],
    upgradeNote: "",
    elite: true
  }
};

function chcGetProfile(answers) {
  const votes = { a: 0, b: 0, c: 0, d: 0 };
  answers.forEach((a, i) => {
    if (a !== null) votes[chcQuestions[i].opts[a].profile]++;
  });
  return Object.entries(votes).sort((x, y) => y[1] - x[1])[0][0];
}

function CareerHealthCheckPage({ navigate, onCTA }) {
  const [view, setView] = chcUseState("quiz"); // quiz | result | thanks
  const [current, setCurrent] = chcUseState(0);
  const [answers, setAnswers] = chcUseState(() => new Array(5).fill(null));
  const [gate, setGate] = chcUseState({ name: "", email: "", level: "" });
  const [sending, setSending] = chcUseState(false);

  const q = chcQuestions[current];
  const total = chcQuestions.length;

  const select = (i) => {
    const next = answers.slice();
    next[current] = i;
    setAnswers(next);
  };

  const goNext = () => {
    if (current < total - 1) setCurrent(current + 1);
    else { setView("result"); window.scrollTo({ top: 0, behavior: "instant" }); }
  };
  const goBack = () => { if (current > 0) setCurrent(current - 1); };

  const restart = () => {
    setAnswers(new Array(5).fill(null));
    setCurrent(0);
    setGate({ name: "", email: "", level: "" });
    setView("quiz");
    window.scrollTo({ top: 0, behavior: "instant" });
  };

  const gateReady = gate.name.trim().length > 0 && gate.email.includes("@") && gate.level !== "";

  const profile = view !== "quiz" ? chcProfiles[chcGetProfile(answers)] : null;

  const handleDownload = async () => {
    if (!gateReady) return;
    setSending(true);
    const profileKey = chcGetProfile(answers);
    const levelLabel = {
      manager: "HR Manager / Senior HR Business Partner",
      director: "HR Director / Head of People",
      vp: "VP People / CPO / Chief People Officer",
      transition: "Other / In transition"
    }[gate.level] || gate.level;
    try {
      await fetch("https://api.web3forms.com/submit", {
        method: "POST",
        headers: { "Content-Type": "application/json", "Accept": "application/json" },
        body: JSON.stringify({
          access_key: "185359e5-9b58-4947-b399-87d2906c57b6",
          subject: `Career Health Check, ${gate.name} (${profile.label})`,
          from_name: "People Cake Career Health Check",
          name: gate.name,
          email: gate.email,
          level: levelLabel,
          profile: profile.label,
          recommended_programme: profile.pkgName,
          replyto: gate.email,
          botcheck: ""
        })
      });
    } catch (e) {/* show thank-you regardless */}

    // 2) Send to Kit (ConvertKit) — create/update subscriber + apply profile tag
    const kitTag = {
      a: "profile-quiet-searcher",
      b: "profile-frozen-high-achiever",
      c: "profile-capable-but-scared",
      d: "profile-defining-next-chapter"
    }[profileKey];
    try {
      await fetch("https://api.convertkit.com/v3/forms/7641aee3f1/subscribe", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          api_key: "Yg87r0_rOuaMaj0ZqiaqBw",
          email: gate.email,
          first_name: gate.name,
          fields: { seniority_level: gate.level },
          tags: [kitTag]
        })
      });
    } catch (e) {/* show thank-you regardless */}

    setSending(false);
    setView("thanks");
    window.scrollTo({ top: 0, behavior: "instant" });
  };

  return (
    <div className="route">
      <section className="section bg-off-white" style={{ minHeight: "70vh", paddingTop: 220 }}>
        <BgGear style={{ top: 120, right: -200 }} size={520} opacity={0.04} />
        <div className="container" style={{ position: "relative", zIndex: 1 }}>
          <div className="chc-shell">

            {/* Fixed intro header (persists across the quiz) */}
            <div className="chc-head">
              <div className="t-label eyebrow" style={{ color: "var(--color-violet)", marginBottom: 16 }}>
                <span className="pill pill--dot" style={{ borderColor: "var(--color-violet)" }}>Career Health Check</span>
              </div>
              <h1 className="t-h1" style={{ marginBottom: 12 }}>Where are you, really?</h1>
              <p className="t-body-lg text-mid" style={{ maxWidth: 540, margin: "0 auto" }}>
                Five honest questions for senior HR professionals. Two minutes of your time. A clearer
                picture of where you are, and what might come next.
              </p>
            </div>

            {/* ============ QUIZ ============ */}
            {view === "quiz" &&
            <div className="chc-card">
                <div className="chc-prog">
                  <div className="chc-prog__meta">
                    <span className="t-label" style={{ color: "var(--color-violet)" }}>{q.theme}</span>
                    <span className="t-label text-mid">{current + 1} of {total}</span>
                  </div>
                  <div className="chc-prog__bar">
                    <div className="chc-prog__fill" style={{ width: ((current + 1) / total * 100) + "%" }} />
                  </div>
                </div>

                <h2 className="chc-q">{q.text}</h2>

                <div className="chc-opts">
                  {q.opts.map((o, i) =>
                  <button
                    key={i}
                    className={"chc-opt" + (answers[current] === i ? " chc-opt--sel" : "")}
                    onClick={() => select(i)}>
                      <span className="chc-opt__dot" aria-hidden="true" />
                      <span>{o.text}</span>
                    </button>
                  )}
                </div>

                <div className="chc-nav">
                  <button className="btn btn--ghost" onClick={goBack} disabled={current === 0}>Back</button>
                  <button className="btn btn--coaching" onClick={goNext} disabled={answers[current] === null}>
                    {current === total - 1 ? "See my results" : "Next"} <IconArrow />
                  </button>
                </div>
              </div>
            }

            {/* ============ RESULT ============ */}
            {view === "result" && profile &&
            <div className="chc-card">
                <span className={"chc-badge " + profile.badge}>{profile.label}</span>
                <h2 className="t-h2" style={{ margin: "8px 0 20px", lineHeight: 1.25 }}>{profile.headline}</h2>
                <p className="text-mid" style={{ lineHeight: 1.8 }}>{profile.body}</p>

                <div className="chc-seclabel">Three things to consider</div>
                <ul className="chc-actions">
                  {profile.actions.map((a, i) => <li key={i}>{a}</li>)}
                </ul>

                <div className="divider" style={{ margin: "32px 0" }} />

                <div className="chc-pkg">
                  <div className="t-label" style={{ color: "var(--color-violet)" }}>Where to start</div>
                  <h3 className="t-h3" style={{ fontFamily: "var(--font-display)", fontSize: 26, marginTop: 6 }}>{profile.pkgName}</h3>
                  <p className="text-mid" style={{ margin: "12px 0 20px", lineHeight: 1.75 }}>{profile.pkgDesc}</p>
                  <ul className="chc-incl">
                    {profile.pkgIncludes.map((it, i) =>
                    <li key={i}>
                        <span className="chc-incl__check" aria-hidden="true"><IconCheck size={12} /></span>
                        <span>{it}</span>
                      </li>
                    )}
                  </ul>
                  {profile.upgradeNote &&
                  <p className="chc-upgrade">{profile.upgradeNote}</p>
                  }
                  <button
                    className="btn btn--coaching"
                    style={{ width: "100%" }}
                    onClick={() => profile.elite ? onCTA() : navigate("programmes")}>
                    {profile.elite ? "Get in touch about Career Elite" : "Explore our programmes"} <IconArrow />
                  </button>
                </div>

                {/* Lead gate */}
                <div className="chc-gate">
                  <h3 className="t-h3" style={{ fontFamily: "var(--font-display)", fontSize: 22 }}>Download your full results</h3>
                  <p className="text-mid" style={{ margin: "6px 0 20px", lineHeight: 1.75 }}>
                    Enter your details to receive your personalised People Cake Career Health Report, yours
                    to keep, return to, and share.
                  </p>
                  <div className="form" style={{ gap: 12 }}>
                    <input
                      className="form__input chc-input"
                      placeholder="First name"
                      value={gate.name}
                      onChange={(e) => setGate({ ...gate, name: e.target.value })} />
                    <input
                      className="form__input chc-input"
                      type="email"
                      placeholder="Work email address"
                      value={gate.email}
                      onChange={(e) => setGate({ ...gate, email: e.target.value })} />
                    <select
                      className="form__select chc-input"
                      value={gate.level}
                      onChange={(e) => setGate({ ...gate, level: e.target.value })}>
                      <option value="">Your current level…</option>
                      <option value="manager">HR Manager / Senior HR Business Partner</option>
                      <option value="director">HR Director / Head of People</option>
                      <option value="vp">VP People / CPO / Chief People Officer</option>
                      <option value="transition">Other / In transition</option>
                    </select>
                  </div>
                  <button
                    className="btn btn--coaching"
                    style={{ width: "100%", marginTop: 16 }}
                    disabled={!gateReady || sending}
                    onClick={handleDownload}>
                    {sending ? "Sending…" : "Download my Career Health Report"}
                  </button>
                  <p className="t-small text-mid" style={{ textAlign: "center", marginTop: 12 }}>
                    Your details are used only to send your report and relevant People Cake updates.
                    You can unsubscribe at any time.
                  </p>
                </div>

                <button className="chc-restart" onClick={restart}>Start again</button>
              </div>
            }

            {/* ============ THANK YOU ============ */}
            {view === "thanks" &&
            <div className="chc-card" style={{ textAlign: "center" }}>
                <div className="chc-tick" aria-hidden="true"><IconCheck size={28} /></div>
                <h2 className="t-h2" style={{ marginBottom: 16 }}>Thank you, {gate.name || "for getting in touch"}.</h2>
                <p className="text-mid" style={{ maxWidth: 440, margin: "0 auto 32px", lineHeight: 1.8 }}>
                  Your People Cake Career Health Report is on its way to your inbox. Take your time with it,
                  and when you're ready to take the next step, we're here.
                </p>
                <div style={{ display: "flex", gap: 12, justifyContent: "center", flexWrap: "wrap" }}>
                  <button className="btn btn--coaching" onClick={() => navigate("programmes")}>
                    Explore our programmes <IconArrow />
                  </button>
                  <button className="btn btn--ghost" onClick={restart}>Start again</button>
                </div>
              </div>
            }

          </div>
        </div>
      </section>
    </div>);

}

const chcStyle = document.createElement("style");
chcStyle.textContent = `
  .chc-shell { max-width: 620px; margin: 0 auto; }
  .chc-head { text-align: center; margin-bottom: 40px; }
  .chc-head .eyebrow { display: flex; justify-content: center; }

  .chc-card {
    background: var(--color-white);
    border: 1px solid var(--color-border);
    border-radius: var(--r-card);
    box-shadow: var(--shadow-card);
    padding: var(--s-48);
  }
  @media (max-width: 600px) { .chc-card { padding: var(--s-32) var(--s-24); } }

  /* Progress */
  .chc-prog { margin-bottom: 36px; }
  .chc-prog__meta { display: flex; justify-content: space-between; align-items: baseline; margin-bottom: 10px; }
  .chc-prog__bar { height: 3px; background: var(--color-border); border-radius: 2px; overflow: hidden; }
  .chc-prog__fill { height: 3px; background: var(--color-violet); border-radius: 2px; transition: width 0.5s cubic-bezier(0.16,1,0.3,1); }

  .chc-q {
    font-family: var(--font-display);
    font-weight: 500;
    font-size: clamp(24px, 3vw, 30px);
    line-height: 1.4;
    letter-spacing: -0.005em;
    margin-bottom: 28px;
  }

  /* Options */
  .chc-opts { display: flex; flex-direction: column; gap: 12px; }
  .chc-opt {
    display: flex; align-items: flex-start; gap: 14px;
    text-align: left;
    padding: 16px 18px;
    border: 1px solid var(--color-border);
    border-radius: var(--r-card);
    background: var(--color-white);
    color: var(--color-mid-grey);
    font-family: var(--font-body);
    font-size: 16px;
    line-height: 1.55;
    cursor: pointer;
    transition: background 160ms ease, border-color 160ms ease, color 160ms ease, box-shadow 160ms ease;
  }
  .chc-opt:hover { border-color: var(--color-violet); color: var(--color-black); background: var(--color-off-white); }
  .chc-opt--sel {
    border-color: var(--color-violet);
    background: rgba(94,92,167,0.06);
    color: var(--color-black);
    box-shadow: inset 0 0 0 1px var(--color-violet);
  }
  .chc-opt__dot {
    flex: 0 0 auto; margin-top: 4px;
    width: 16px; height: 16px; border-radius: 50%;
    border: 1.5px solid var(--color-border);
    transition: border-color 160ms ease, background 160ms ease, box-shadow 160ms ease;
  }
  .chc-opt:hover .chc-opt__dot { border-color: var(--color-violet); }
  .chc-opt--sel .chc-opt__dot {
    border-color: var(--color-violet);
    background: var(--color-violet);
    box-shadow: inset 0 0 0 3px var(--color-white);
  }

  .chc-nav { display: flex; justify-content: space-between; align-items: center; margin-top: 32px; gap: 16px; }
  .chc-nav .btn:disabled { opacity: 0.35; cursor: default; transform: none; }

  /* Result */
  .chc-badge {
    display: inline-block;
    font-size: var(--text-label); font-weight: 600;
    letter-spacing: 0.1em; text-transform: uppercase;
    padding: 6px 14px; border-radius: var(--r-pill);
  }
  .chc-badge--a { background: rgba(94,92,167,0.14); color: var(--color-violet); }
  .chc-badge--b { background: rgba(167,60,129,0.12); color: var(--color-purple); }
  .chc-badge--c { background: rgba(242,230,64,0.30); color: #6b5e06; }
  .chc-badge--d { background: var(--color-black); color: var(--color-yellow); }

  .chc-seclabel {
    font-size: var(--text-label); font-weight: 600;
    letter-spacing: 0.1em; text-transform: uppercase;
    color: var(--color-mid-grey);
    margin: 32px 0 14px;
  }
  .chc-actions { list-style: none; padding: 0; margin: 0; display: flex; flex-direction: column; gap: 12px; }
  .chc-actions li {
    position: relative; padding-left: 28px;
    line-height: 1.7; color: var(--color-mid-grey);
  }
  .chc-actions li::before {
    content: "→"; position: absolute; left: 0; top: 0;
    color: var(--color-violet); font-weight: 600;
  }

  /* Package box */
  .chc-pkg {
    background: var(--color-off-white);
    border: 1px solid var(--color-border);
    border-top: 3px solid var(--color-violet);
    border-radius: var(--r-card);
    padding: var(--s-32);
  }
  .chc-incl { list-style: none; padding: 0; margin: 0 0 20px; display: flex; flex-direction: column; gap: 10px; }
  .chc-incl li { display: flex; gap: 10px; align-items: flex-start; line-height: 1.5; font-size: 15px; color: var(--color-black); }
  .chc-incl__check {
    flex: 0 0 auto; margin-top: 2px;
    width: 20px; height: 20px; border-radius: 50%;
    display: inline-flex; align-items: center; justify-content: center;
    background: rgba(94,92,167,0.12); color: var(--color-violet);
  }
  .chc-upgrade {
    font-size: var(--text-small); color: var(--color-mid-grey); line-height: 1.7;
    border-top: 1px solid var(--color-border); padding-top: 16px; margin-bottom: 20px;
  }

  /* Gate */
  .chc-gate {
    background: var(--color-off-white);
    border: 1px solid var(--color-border);
    border-radius: var(--r-card);
    padding: var(--s-32);
    margin-top: 24px;
  }
  .chc-input:focus { border-color: var(--color-violet); box-shadow: 0 0 0 3px rgba(94,92,167,0.14); }

  .chc-restart {
    display: block; margin: 24px auto 0;
    font-size: var(--text-small); color: var(--color-mid-grey);
    text-decoration: underline; background: none; border: none; cursor: pointer;
  }
  .chc-restart:hover { color: var(--color-black); }

  .chc-tick {
    width: 64px; height: 64px; border-radius: 50%;
    background: var(--color-yellow); color: var(--color-black);
    display: inline-flex; align-items: center; justify-content: center;
    margin-bottom: 24px;
  }
`;
document.head.appendChild(chcStyle);

window.CareerHealthCheckPage = CareerHealthCheckPage;
