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

/* ============================================================
   Partners Page
   ============================================================ */
function PartnersPage({ navigate, onCTA }) {
  return (
    <div className="route">
      {/* Hero */}
      <section className="hero" style={{ paddingBottom: 80 }}>
        <BgGear style={{ top: -160, right: -180 }} size={620} opacity={0.05}/>
        <div className="container" style={{ position: "relative", zIndex: 1 }}>
          <div style={{ maxWidth: 880 }}>
            <div className="t-label eyebrow" style={{ color: "var(--color-yellow)" }}>Partners & Ecosystem</div>
            <h1 className="t-hero fade-up fade-up-delay-1" style={{ marginTop: 24 }}>
              Better outcomes through<br/>
              the <em style={{ fontStyle: "italic", color: "var(--color-yellow)" }}>right partnerships.</em>
            </h1>
            <p className="t-body-lg hero__lead fade-up fade-up-delay-2" style={{ marginTop: 32, maxWidth: 680 }}>
              People Cake works alongside a curated network of technology providers, HR
              platforms, and specialist practitioners, so the advice we give is always
              connected to what actually gets implemented.
            </p>
            <div className="cta-row fade-up fade-up-delay-3">
              <button className="btn btn--primary btn--lg" onClick={onCTA}>
                Interested in partnering? <IconArrow/>
              </button>
            </div>
          </div>
        </div>
      </section>

      {/* Partner logo grid, placeholder */}
      <section className="section-sm bg-off-white">
        <div className="container">
          <div className="t-label eyebrow text-center" style={{ color: "var(--color-mid-grey)", marginBottom: 48 }}>
            Selected partner network · more to be added
          </div>
          <div className="partner-grid">
            {[
              "HRIS Platform", "Performance OS", "Engagement Suite", "People Analytics",
              "Employment Law", "L&D Specialist", "Org Design Studio", "Talent Network"
            ].map(p => (
              <div key={p} className="partner-tile partner-tile--placeholder">
                {p}
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* Partnership types */}
      <section className="section bg-white">
        <div className="container">
          <div style={{ marginBottom: 64, maxWidth: 720 }}>
            <div className="t-label eyebrow">Partnership types</div>
            <h2 className="t-h1">Three ways we work with the network.</h2>
          </div>
          <div className="problem-grid">
            {[
              {
                title: "HR Tech Partners",
                body: "Platforms and tools we recommend and implement, covering HRIS, performance, engagement, and people analytics.",
                accent: "var(--color-purple)"
              },
              {
                title: "Specialist Practitioners",
                body: "A network of trusted specialists, employment law, L&D, organisational design, who complement People Cake's core offer.",
                accent: "var(--color-violet)"
              },
              {
                title: "Associate Coaching Partners",
                body: "Corporate clients working with People Cake via third-party partnership programmes, for scaled coaching delivery.",
                accent: "var(--color-yellow)"
              },
            ].map((c, i) => (
              <div key={i} className="problem-card" style={{ borderTopColor: c.accent }}>
                <div className="problem-card__num" style={{ color: c.accent === "var(--color-yellow)" ? "var(--color-black)" : c.accent, opacity: 1 }}>
                  0{i + 1}
                </div>
                <h3 className="problem-card__title">{c.title}</h3>
                <p className="problem-card__body">{c.body}</p>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* Become a partner CTA */}
      <section className="bg-black" style={{ padding: "80px 0", textAlign: "center" }}>
        <div className="container">
          <h2 className="t-h1" style={{ marginBottom: 24, maxWidth: 720, margin: "0 auto 24px" }}>
            Building something complementary?
          </h2>
          <p className="t-body-lg" style={{ color: "rgba(255,255,255,0.8)", maxWidth: 560, margin: "0 auto 40px" }}>
            We're always open to conversations with platforms, practitioners,
            and partners who share our standards.
          </p>
          <button className="btn btn--primary btn--lg" onClick={onCTA}>
            Get in touch <IconArrow/>
          </button>
        </div>
      </section>
    </div>
  );
}

/* ============================================================
   Diagnostic Page, People Performance Taster (6 questions)
   ============================================================ */
const DX_QUESTIONS = [
  { area: "Goals",    q: "Your team has clear, documented goals, and everyone knows what they are." },
  { area: "Goals",    q: "When priorities shift, goals are updated quickly and consistently across the business." },
  { area: "Feedback", q: "Managers give regular, structured feedback, not just at annual review time." },
  { area: "Feedback", q: "People feel genuinely safe raising issues upward, without fear of consequence." },
  { area: "Culture",  q: "Leaders in your organisation model the behaviours they expect from others." },
  { area: "Culture",  q: "When feedback is given, something actually changes as a result." },
];

const DX_AREA_MAP = {
  Goals:    [0, 1],
  Feedback: [2, 3],
  Culture:  [4, 5],
};

function DiagnosticPage({ navigate, onCTA }) {
  const [stage, setStage] = useStateExtras("intro"); // intro | questions | gate | results
  const [step, setStep] = useStateExtras(0);
  const [answers, setAnswers] = useStateExtras({});
  const [form, setForm] = useStateExtras({ name: "", email: "" });
  const [submitting, setSubmitting] = useStateExtras(false);
  const [submitError, setSubmitError] = useStateExtras("");

  const setAnswer = (i, n) => {
    setAnswers(a => ({ ...a, [i]: n }));
    setTimeout(() => {
      if (i < DX_QUESTIONS.length - 1) setStep(i + 1);
      else setStage("gate");
    }, 320);
  };

  // Per-area %s
  const areaScores = {};
  Object.entries(DX_AREA_MAP).forEach(([area, idxs]) => {
    const vals = idxs.map(i => answers[i] || 3);
    areaScores[area] = Math.round((vals.reduce((s, v) => s + v, 0) / (vals.length * 5)) * 100);
  });
  const overall = Math.round(
    Object.values(areaScores).reduce((s, v) => s + v, 0) / Object.keys(areaScores).length
  );
  const band = overall <= 45 ? "red" : overall <= 69 ? "amber" : "green";

  const verdicts = {
    red:   ["Your performance foundations are at risk",
            "Most organisations at this score are firefighting, not leading. The gaps here are costing you in ways you may not yet see clearly."],
    amber: ["You have the foundations, but they\u2019re not holding",
            "Some things are working. Others are masking problems. Without intervention, the gaps tend to widen."],
    green: ["Strong foundations, now it\u2019s about consistency",
            "Your basics are in place. The question is whether they\u2019re embedded deeply enough to survive growth and change."],
  };

  const submitGate = async (e) => {
    e.preventDefault();
    setSubmitting(true);
    setSubmitError("");

    const answersText = DX_QUESTIONS.map((q, i) => {
      const v = answers[i] || "-";
      return `Q${i + 1} (${q.area}): ${v}/5, ${q.q}`;
    }).join("\n");

    const payload = {
      access_key: "185359e5-9b58-4947-b399-87d2906c57b6",
      subject: `People Performance Taster result: ${form.name}, ${overall}%`,
      from_name: "People Cake diagnostic",
      name: form.name,
      email: form.email,
      replyto: form.email,
      overall_score: `${overall}%`,
      band: band.toUpperCase(),
      verdict: verdicts[band][0],
      goals_score: `${areaScores.Goals}%`,
      feedback_score: `${areaScores.Feedback}%`,
      culture_score: `${areaScores.Culture}%`,
      answers: answersText,
      botcheck: "",
    };

    try {
      const res = await fetch("https://api.web3forms.com/submit", {
        method: "POST",
        headers: { "Content-Type": "application/json", "Accept": "application/json" },
        body: JSON.stringify(payload),
      });
      const data = await res.json();
      if (data.success) {
        setStage("results");
      } else {
        setSubmitError(data.message || "Couldn't send your results. Please try again, or email sarah@peoplecake.com.");
      }
    } catch (err) {
      setSubmitError("Couldn't reach the server. Please try again, or email sarah@peoplecake.com.");
    } finally {
      setSubmitting(false);
    }
  };

  /* ============ INTRO ============ */
  if (stage === "intro") {
    return (
      <div className="route">
        <section style={{ padding: "220px 0 64px", background: "var(--color-off-white)" }}>
          <div className="container">
            <div style={{ maxWidth: 720, margin: "0 auto", textAlign: "center" }}>
              <div className="t-label eyebrow eyebrow--purple">Free diagnostic</div>
              <h1 className="t-hero" style={{ marginBottom: 24 }}>
                Is your team <em style={{ fontStyle: "italic", color: "var(--color-purple)" }}>performing</em>,<br/>
                or just busy?
              </h1>
              <p className="t-body-lg text-mid" style={{ marginBottom: 16 }}>
                6 questions. 2 minutes. Find out where the cracks are
                before they become crises.
              </p>
              <div style={{ marginTop: 40 }}>
                <button className="btn btn--primary btn--lg" onClick={() => { setStep(0); setStage("questions"); }}>
                  Start the diagnostic <IconArrow/>
                </button>
              </div>
              <div className="diagnostic-cta__trust" style={{ marginTop: 40, color: "var(--color-mid-grey)" }}>
                <span><IconCheck size={14}/> No credit card required</span>
                <span><IconCheck size={14}/> Takes 2 minutes</span>
                <span><IconCheck size={14}/> Results sent by email</span>
              </div>
            </div>
          </div>
        </section>

        {/* What you'll uncover */}
        <section className="section bg-white">
          <div className="container">
            <div style={{ marginBottom: 48, maxWidth: 640 }}>
              <div className="t-label eyebrow">What you'll uncover</div>
              <h2 className="t-h2">Three foundations of team performance.</h2>
            </div>
            <div style={{
              display: "grid",
              gridTemplateColumns: "repeat(3, 1fr)",
              gap: 24,
            }} className="dx-pyramid">
              {[
                { n: "01", title: "Goals",    body: "Whether your team has clear, shared direction, and whether it survives a change of priority." },
                { n: "02", title: "Feedback", body: "Whether feedback flows in both directions, often enough, and safely enough, to actually shift behaviour." },
                { n: "03", title: "Culture",  body: "Whether leaders model what they expect, and whether feedback translates into anything actually changing." },
              ].map((c, i) => (
                <div key={i} style={{
                  padding: 32,
                  background: "var(--color-off-white)",
                  borderRadius: "var(--r-card)",
                  borderTop: "3px solid var(--color-purple)",
                }}>
                  <div className="t-label" style={{ color: "var(--color-purple)", marginBottom: 16 }}>{c.n}</div>
                  <h3 className="t-h3" style={{ fontSize: 20, marginBottom: 12 }}>{c.title}</h3>
                  <p className="t-small text-mid">{c.body}</p>
                </div>
              ))}
            </div>
          </div>
        </section>
      </div>
    );
  }

  /* ============ QUESTIONS ============ */
  if (stage === "questions") {
    const q = DX_QUESTIONS[step];
    const progressPct = ((step) / DX_QUESTIONS.length) * 100;
    return (
      <div className="route">
        <section style={{ padding: "200px 0 64px", background: "var(--color-off-white)", minHeight: "80vh" }}>
          <div className="container">
            <div style={{ maxWidth: 640, margin: "0 auto" }}>
              <div className="dx2-progress-wrap">
                <div className="dx2-progress-fill" style={{ width: `${progressPct}%` }}/>
              </div>
              <p className="t-small text-mid" style={{ marginBottom: 24 }}>
                Question {step + 1} of {DX_QUESTIONS.length}
              </p>
              <div className="dx2-q-card">
                <div className="t-label" style={{ color: "var(--color-purple)", marginBottom: 8 }}>
                  {q.area}
                </div>
                <p className="dx2-q-text">{q.q}</p>
                <div className="dx2-opts">
                  {[1, 2, 3, 4, 5].map(n => {
                    const selected = answers[step] === n;
                    const tone = selected ? (n <= 2 ? "red" : n === 3 ? "amber" : "green") : "";
                    return (
                      <button key={n}
                        className={"dx2-opt" + (selected ? " dx2-opt--" + tone : "")}
                        onClick={() => setAnswer(step, n)}>
                        {n}
                      </button>
                    );
                  })}
                </div>
                <div className="dx2-opt-labels">
                  <span>Not at all</span>
                  <span>Absolutely</span>
                </div>
              </div>
              <div className="dx-actions">
                <button className="btn btn--text"
                  disabled={step === 0}
                  style={{ opacity: step === 0 ? 0.3 : 1 }}
                  onClick={() => setStep(s => Math.max(0, s - 1))}>
                  ← Back
                </button>
                <button className="btn btn--text" onClick={() => navigate("home")}>
                  Exit diagnostic
                </button>
              </div>
            </div>
          </div>
        </section>
      </div>
    );
  }

  /* ============ LEAD GATE ============ */
  if (stage === "gate") {
    return (
      <div className="route">
        <section style={{ padding: "200px 0 64px", background: "var(--color-off-white)", minHeight: "80vh" }}>
          <div className="container">
            <div style={{ maxWidth: 520, margin: "0 auto" }}>
              <div className="t-label eyebrow eyebrow--purple">Your results are ready</div>
              <h2 className="t-h1" style={{ marginBottom: 16 }}>
                Where do you want them sent?
              </h2>
              <p className="t-body text-mid" style={{ marginBottom: 32 }}>
                Enter your details and we'll show your score instantly, no spam, no pitch, just your results.
              </p>
              <form className="form" onSubmit={submitGate}>
                <div className="form__field">
                  <label className="form__label">Your first name</label>
                  <input className="form__input" required value={form.name}
                    onChange={e => setForm({ ...form, name: e.target.value })}/>
                </div>
                <div className="form__field">
                  <label className="form__label">Work email address</label>
                  <input className="form__input" type="email" required value={form.email}
                    onChange={e => setForm({ ...form, email: e.target.value })}/>
                </div>
                <button type="submit" disabled={submitting} className="btn btn--primary btn--lg">
                  {submitting ? "Sending\u2026" : <React.Fragment>Show my results <IconArrow/></React.Fragment>}
                </button>
                {submitError ? (
                  <p className="t-small" style={{ color: "#A32D2D", textAlign: "center", marginTop: 4 }}>{submitError}</p>
                ) : null}
                <p className="t-small text-mid">
                  We'll email a copy to you and to Sarah. You can unsubscribe at any time.
                </p>
              </form>
            </div>
          </div>
        </section>
      </div>
    );
  }

  /* ============ RESULTS ============ */
  return (
    <div className="route">
      <section style={{ padding: "200px 0 64px", background: "var(--color-off-white)" }}>
        <div className="container">
          <div style={{ maxWidth: 640, margin: "0 auto" }}>
            <div className="t-label eyebrow eyebrow--purple">Your result</div>
            <h2 className="t-h1" style={{ marginBottom: 32 }}>
              Hi {form.name || "there"}, here's what came out.
            </h2>

            <div className={"dx2-result-band dx2-result-band--" + band}>
              <div className="dx2-result-score">{overall}%</div>
              <div className="dx2-result-verdict">{verdicts[band][0]}</div>
              <p className="dx2-result-desc">{verdicts[band][1]}</p>
            </div>

            <div className="dx2-area-card">
              <div className="t-label" style={{ color: "var(--color-mid-grey)", marginBottom: 16 }}>
                Area breakdown
              </div>
              {Object.entries(areaScores).map(([area, pct]) => {
                const tone = pct <= 45 ? "red" : pct <= 69 ? "amber" : "green";
                return (
                  <div key={area} className="dx2-area-row">
                    <span className="dx2-area-name">{area}</span>
                    <div className="dx2-area-bar-wrap">
                      <div className={"dx2-area-bar dx2-area-bar--" + tone} style={{ width: `${pct}%` }}/>
                    </div>
                    <span className={"dx2-area-pct dx2-area-pct--" + tone}>{pct}%</span>
                  </div>
                );
              })}
            </div>

            <div className="dx2-cta-card">
              <h3 className="t-h3" style={{ marginBottom: 8 }}>Want to know exactly what's driving this?</h3>
              <p className="text-mid" style={{ marginBottom: 24 }}>
                {band === "red"
                  ? "These results suggest real underlying issues that a 30-minute diagnostic call could map clearly, so you know exactly what to fix, and in what order."
                  : band === "amber"
                  ? "A targeted diagnostic will pinpoint which gaps matter most for your business and give you a clear, prioritised plan to address them."
                  : "A deeper diagnostic confirms where you're genuinely solid, and surfaces the hidden vulnerabilities that only show under pressure."}
              </p>
              <div style={{ display: "flex", gap: 12, flexWrap: "wrap" }}>
                <button className="btn btn--primary btn--lg" onClick={onCTA}>
                  Book a free 30-minute call <IconArrow/>
                </button>
                <button className="btn btn--ghost btn--lg" onClick={() => navigate("home")}>
                  Back to People Cake
                </button>
              </div>
              <p className="t-small text-mid" style={{ marginTop: 12, textAlign: "center" }}>
                No obligation. Just clarity.
              </p>
            </div>
          </div>
        </div>
      </section>
    </div>
  );
}

const extrasStyle = document.createElement("style");
extrasStyle.textContent = `
  @media (max-width: 920px) {
    .dx-pyramid { grid-template-columns: repeat(2, 1fr) !important; }
    .dx-form-row { grid-template-columns: 1fr !important; }
  }

  /* ============ Performance Taster (dx2) ============ */
  .dx2-progress-wrap {
    background: var(--color-border);
    border-radius: 99px;
    height: 4px;
    margin-bottom: 12px;
    overflow: hidden;
  }
  .dx2-progress-fill {
    background: var(--color-purple);
    border-radius: 99px;
    height: 4px;
    transition: width 400ms ease;
  }
  .dx2-q-card {
    background: var(--color-white);
    border: 1px solid var(--color-border);
    border-radius: var(--r-card);
    padding: 32px;
    margin-bottom: 24px;
  }
  .dx2-q-text {
    font-family: var(--font-display);
    font-size: 24px;
    line-height: 1.35;
    color: var(--color-black);
    margin: 0 0 24px;
  }
  .dx2-opts {
    display: flex;
    gap: 8px;
  }
  .dx2-opt {
    flex: 1;
    padding: 14px 4px;
    border: 1px solid var(--color-border);
    border-radius: var(--r-card);
    background: var(--color-white);
    color: var(--color-mid-grey);
    font-size: 16px;
    font-weight: 500;
    cursor: pointer;
    text-align: center;
    transition: all 150ms ease;
  }
  .dx2-opt:hover {
    background: var(--color-off-white);
    color: var(--color-black);
  }
  .dx2-opt--red    { background: #FCEBEB; border-color: #F09595; color: #791F1F; }
  .dx2-opt--amber  { background: #FAEEDA; border-color: #EF9F27; color: #633806; }
  .dx2-opt--green  { background: #EAF3DE; border-color: #97C459; color: #27500A; }
  .dx2-opt-labels {
    display: flex;
    justify-content: space-between;
    margin-top: 8px;
    font-size: 12px;
    color: var(--color-mid-grey);
  }

  .dx2-result-band {
    border-radius: var(--r-card);
    padding: 32px;
    margin-bottom: 24px;
  }
  .dx2-result-band--red    { background: #FCEBEB; border: 1px solid #F09595; }
  .dx2-result-band--amber  { background: #FAEEDA; border: 1px solid #EF9F27; }
  .dx2-result-band--green  { background: #EAF3DE; border: 1px solid #97C459; }
  .dx2-result-score {
    font-family: var(--font-display);
    font-size: 72px;
    line-height: 1;
    font-weight: 500;
    margin-bottom: 12px;
  }
  .dx2-result-band--red .dx2-result-score    { color: #A32D2D; }
  .dx2-result-band--amber .dx2-result-score  { color: #633806; }
  .dx2-result-band--green .dx2-result-score  { color: #27500A; }
  .dx2-result-verdict {
    font-size: 20px;
    font-weight: 500;
    margin-bottom: 8px;
  }
  .dx2-result-band--red .dx2-result-verdict    { color: #791F1F; }
  .dx2-result-band--amber .dx2-result-verdict  { color: #854F0B; }
  .dx2-result-band--green .dx2-result-verdict  { color: #3B6D11; }
  .dx2-result-desc {
    font-size: 15px;
    margin: 0;
    line-height: 1.6;
  }
  .dx2-result-band--red .dx2-result-desc    { color: #A32D2D; }
  .dx2-result-band--amber .dx2-result-desc  { color: #854F0B; }
  .dx2-result-band--green .dx2-result-desc  { color: #3B6D11; }

  .dx2-area-card {
    background: var(--color-white);
    border: 1px solid var(--color-border);
    border-radius: var(--r-card);
    padding: 24px 32px;
    margin-bottom: 24px;
  }
  .dx2-area-row {
    display: flex;
    align-items: center;
    gap: 16px;
    padding: 12px 0;
    border-bottom: 1px solid var(--color-border);
  }
  .dx2-area-row:last-child { border-bottom: none; }
  .dx2-area-name {
    font-size: 15px;
    color: var(--color-black);
    flex: 1;
    font-weight: 500;
  }
  .dx2-area-bar-wrap {
    width: 160px;
    background: var(--color-off-white);
    border-radius: 99px;
    height: 8px;
    overflow: hidden;
  }
  .dx2-area-bar { height: 8px; border-radius: 99px; transition: width 800ms ease; }
  .dx2-area-bar--red    { background: #E24B4A; }
  .dx2-area-bar--amber  { background: #EF9F27; }
  .dx2-area-bar--green  { background: #639922; }
  .dx2-area-pct { font-size: 14px; font-weight: 500; min-width: 44px; text-align: right; }
  .dx2-area-pct--red    { color: #A32D2D; }
  .dx2-area-pct--amber  { color: #633806; }
  .dx2-area-pct--green  { color: #3B6D11; }

  .dx2-cta-card {
    background: var(--color-off-white);
    border-radius: var(--r-card);
    padding: 32px;
  }

  @media (max-width: 640px) {
    .dx2-q-card { padding: 24px; }
    .dx2-q-text { font-size: 20px; }
    .dx2-opt { padding: 12px 4px; font-size: 14px; }
    .dx2-area-bar-wrap { width: 100px; }
    .dx2-result-score { font-size: 56px; }
  }
`;
document.head.appendChild(extrasStyle);

Object.assign(window, { PartnersPage, DiagnosticPage });
