/* =====================================================================
   results2.jsx — v2 focus-first results page (8 sections)
   ===================================================================== */

const R2 = () => window.FFP2.RESULT2;

/* ---- Pathway Readiness Score — supporting benchmark (not a grade) ---- */
function ReadinessGauge({ score, bands }) {
  const W = 240, H = 138, cx = W / 2, cy = 122, R = 96, sw = 15;
  const bandColor = { rebuild_rhythm: "#b4493b", simplify_foundation: "#c9a46c", focus_pathway: "var(--p-sage)", expand_intention: "var(--p-aztek)" };
  const theta = (v) => Math.PI * (1 - v / 100);
  const pt = (v, r = R) => [cx + r * Math.cos(theta(v)), cy - r * Math.sin(theta(v))];
  const arc = (v0, v1, r = R) => {
    const [x0, y0] = pt(v0, r), [x1, y1] = pt(v1, r);
    return `M${x0},${y0} A${r},${r} 0 0 1 ${x1},${y1}`;
  };
  const [px, py] = pt(score);
  return (
    <div className="score-snap__gauge">
      <svg viewBox={`0 0 ${W} ${H}`} width="100%" role="img" aria-label={"Pathway readiness " + score + " of 100"}>
        {/* track */}
        <path d={arc(0, 100)} fill="none" stroke="var(--border-divider)" strokeOpacity="0.5" strokeWidth={sw} strokeLinecap="round" />
        {/* band boundary ticks */}
        {bands.slice(1).map(b => {
          const [ix, iy] = pt(b.min, R - sw / 2 - 1), [ox, oy] = pt(b.min, R + sw / 2 + 1);
          return <line key={b.key} x1={ix} y1={iy} x2={ox} y2={oy} stroke="var(--surface-elevated)" strokeWidth="2" />;
        })}
        {/* value fill */}
        <path d={arc(0, score)} fill="none" stroke="var(--p-sage)" strokeWidth={sw} strokeLinecap="round" />
        {/* pointer */}
        <circle cx={px} cy={py} r={sw / 2 + 3} fill="var(--surface-elevated)" />
        <circle cx={px} cy={py} r={sw / 2 - 1.5} fill="var(--p-aztek)" />
        <circle cx={px} cy={py} r={3} fill="var(--p-oatmeal)" />
      </svg>
      <div className="score-snap__center">
        <div className="score-snap__num"><span className="v">{score}</span><span className="d">/100</span></div>
      </div>
    </div>
  );
}

function ScoreSnapshot({ layout = "card" }) {
  const pr = R2().pathwayReadiness;
  const bands = window.FFP2.READINESS_BANDS;
  const bandColor = { rebuild_rhythm: "#b4493b", simplify_foundation: "#c9a46c", focus_pathway: "var(--p-sage)", expand_intention: "var(--p-aztek)" };
  return (
    <div className={"score-snap score-snap--" + layout}>
      <p className="score-snap__label">Pathway Readiness Score</p>
      <ReadinessGauge score={pr.score} bands={bands} />
      <p className="score-snap__band">{pr.label}</p>
      <ul className="score-snap__legend">
        {bands.map(b => {
          const on = pr.bandKey === b.key;
          return (
            <li key={b.key} className={on ? "on" : ""}>
              <span className="dot" style={{ background: bandColor[b.key] }}></span>
              <span className="rng">{b.min}&ndash;{b.max}</span>
              <span className="nm">{b.label}</span>
            </li>
          );
        })}
      </ul>
      <p className="score-snap__cap">{pr.caption}</p>
    </div>
  );
}

/* ---- Section 1: Result hero ---- */
function ResultHero({ variant, name }) {
  const r = R2(), p = r.primaryBusinessFocus;
  const who = name || r.firstName;
  const eyebrow = <p className="r2-hero__eyebrow"><span>{who ? "For " + who : "Your result"}</span><span className="rule"></span><span>Your next focus</span></p>;
  const title = <h1 className="r2-hero__title">{who ? who + ", your" : "Your"} next business focus is <em>tightening your message</em>.</h1>;
  const stage = (
    <div className="r2-hero__stage">
      <span className="r2-hero__stage-chip">{p.stage}</span>
      <span className="r2-hero__stage-text">stage of the Freedom Filled<span className="reg">&reg;</span> Business pathway</span>
    </div>
  );

  if (variant === "visual") {
    return (
      <section className="r2-hero"><div className="v2-wrap">
        <div className="r2-hero--split">
          <div>
            {eyebrow}{title}
            <p className="r2-hero__reassure">{p.reassurance}</p>
            <p className="r2-hero__summary">{p.summary} {p.whyThisMatters}</p>
            {stage}
          </div>
          <div className="r2-hero__mini">
            <CircularPathway result={r} size={300} />
            <p className="l2-preview__cap" style={{ margin: "8px 0 18px" }}>Message, your first focus, on the pathway</p>
            <ScoreSnapshot layout="card" />
          </div>
        </div>
      </div></section>
    );
  }

  // text-first: constrained measure, reassurance as pull-quote, summary as lead
  return (
    <section className="r2-hero"><div className="v2-wrap">
      <div className="r2-hero--text-grid">
        <div className="r2-hero__text">
          {eyebrow}
          {title}
          <blockquote className="r2-hero__pull">{p.reassurance}</blockquote>
          <p className="r2-hero__summary">{p.summary} {p.whyThisMatters}</p>
          {stage}
        </div>
        <aside className="r2-hero__aside"><ScoreSnapshot layout="card" /></aside>
      </div>
    </div></section>
  );
}

/* ---- Section 2: Top three focus areas ---- */
function TopThree({ variant }) {
  const r = R2(), p = r.primaryBusinessFocus, secs = r.secondaryBusinessFocusAreas;
  const intro = (
    <p className="focus-intro">We are starting with <em>message</em> because it is the part that will make the next moves easier. When the message is clearer, selling becomes cleaner and leadership feels lighter. These are not three emergencies, they are a sequence.</p>
  );
  if (variant === "ranked") {
    const all = [{ ...p, rank: 1, pin: "primary" }, ...secs.map((s, i) => ({ ...s, rank: i + 2, pin: "secondary" }))];
    return (
      <section className="rs"><div className="v2-wrap">
        <div className="rs__label"><span className="n">02</span><span className="t">Your top three focus areas</span></div>
        {intro}
        <div className="focus-list">
          {all.map(f => (
            <div key={f.key} className={"focus-list__item" + (f.pin === "primary" ? " focus-list__item--primary" : "")}>
              <span className="focus-list__n">{f.rank}</span>
              <div className="focus-list__body"><h4>{f.title}</h4><p>{f.summary}</p></div>
              <span className="focus-list__pin"><span className="pip" style={{ opacity: f.pin === "primary" ? 1 : 0.5 }}></span>{f.stage} <b>&middot; {f.area}</b></span>
            </div>
          ))}
        </div>
      </div></section>
    );
  }
  // stacked
  return (
    <section className="rs"><div className="v2-wrap">
      <div className="rs__label"><span className="n">02</span><span className="t">Your top three focus areas</span></div>
      {intro}
      <div className="focus-stack">
        <div className="focus-primary">
          <p className="focus-primary__rank">Start here</p>
          <h3 className="focus-primary__title">{p.title}</h3>
          <p className="focus-primary__sum">{p.summary}</p>
          <div className="focus-primary__tags"><span className="focus-tag">{p.stage} stage</span><span className="focus-tag">{p.area}</span></div>
        </div>
        <div className="focus-secondary-row">
          {secs.map((s, i) => (
            <div key={s.key} className="focus-second">
              <p className="focus-second__rank">Supporting</p>
              <h4 className="focus-second__title">{s.title}</h4>
              <p className="focus-second__sum">{s.summary}</p>
              <p className="focus-second__stage">{s.stage} <b>&middot; {s.area}</b></p>
            </div>
          ))}
        </div>
      </div>
    </div></section>
  );
}

/* ---- Section 3: Why we are starting here ---- */
function WhyHere() {
  const p = R2().primaryBusinessFocus;
  return (
    <section className="rs"><div className="v2-wrap">
      <div className="rs__label"><span className="n">03</span><span className="t">Why we are starting here</span></div>
      <div className="diag">
        <div className="diag__grid">
          <p className="diag__lead">This is insight, not criticism. The message simply needs to do more of the work first.</p>
          <p className="diag__body">{p.diagnosis}</p>
        </div>
        <div className="diag__cost"><Icon name="alert" size={18} /><p><b>What it may be costing:</b> {p.likelyCost}</p></div>
      </div>
    </div></section>
  );
}

/* ---- Section 4: First business fix ---- */
function FirstFix() {
  const f = R2().primaryBusinessFocus.firstFix;
  const parts = f.prompt.split(/(\[[^\]]+\])/g);
  return (
    <section className="rs"><div className="v2-wrap">
      <div className="rs__label"><span className="n">04</span><span className="t">Your first business fix</span></div>
      <div className="fix">
        <div>
          <h3 className="fix__title">{f.title}.</h3>
          <p className="fix__why">{f.whyItHelps} It is one clear action, not a checklist. Small enough to do today.</p>
        </div>
        <div className="fix__card">
          <p className="fix__card-label">Write this, in your words</p>
          <p className="fix__prompt">{parts.map((s, i) => s.startsWith("[") ? <b key={i}>{s.replace(/[\[\]]/g, "")}</b> : <span key={i}>{s}</span>)}</p>
          <p className="fix__hint">If a happy client cannot repeat it, she probably cannot buy it with confidence yet.</p>
        </div>
      </div>
    </div></section>
  );
}

/* ---- Section 5: Implementation support signal (F.R.E.S.H) ---- */
function SupportSignal({ variant }) {
  const s = R2().implementationSupportSignal;
  const onAreas = s.freshAreas;
  if (variant === "strip") {
    return (
      <section className="rs"><div className="v2-wrap">
        <div className="rs__label"><span className="n">05</span><span className="t">Implementation support signal</span></div>
        <div className="pw-foundation" style={{ marginTop: 0 }}>
          <span className="pw-foundation__label">{s.publicTitle}</span>
          <div className="pw-foundation__dots">
            {window.FFP2.FRESH.map(f => { const on = onAreas.includes(f.name); return <span key={f.key} className="pw-foundation__pill" style={{ background: on ? f.color : "transparent", borderColor: f.color, color: on ? "#fff" : f.color }}>{f.letter}</span>; })}
          </div>
          <span className="pw-foundation__cap">{s.summary}</span>
        </div>
      </div></section>
    );
  }
  return (
    <section className="rs"><div className="v2-wrap">
      <div className="rs__label"><span className="n">05</span><span className="t">Implementation support signal</span></div>
      <div className="signal">
        <div className="signal__inner">
          <div className="signal__aside">
            <p className="signal__eyebrow">The woman running the business</p>
            <h3 className="signal__title">{s.publicTitle}.</h3>
            <div className="signal__dots">
              {window.FFP2.FRESH.map(f => { const on = onAreas.includes(f.name); return (
                <span key={f.key} className="signal__dot"><span className="d" style={{ background: f.color, opacity: on ? 1 : 0.3 }}></span><span className="l">{f.letter}</span></span>
              ); })}
            </div>
          </div>
          <div className="signal__main">
            <p className="signal__sum">{s.summary} {s.detail}</p>
            <div className="signal__rec"><Icon name="spark" size={18} /><p>{s.recommendation}</p></div>
            <p className="signal__bridge">Inside Freedom Filled<span className="reg">&reg;</span> Business, this is part of Tracy's F.R.E.S.H system, the ongoing foundation beneath the business work.</p>
          </div>
        </div>
      </div>
    </div></section>
  );
}

/* ---- Section 6: Pathway visual (3 variations, inline switch) ---- */
function PathwaySection({ variant, setVariant }) {
  const r = R2();
  const active = window.PATHWAY_VARIANTS.find(v => v.key === variant) || window.PATHWAY_VARIANTS[0];
  return (
    <section className="rs"><div className="v2-wrap">
      <div className="rs__label" style={{ justifyContent: "space-between" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 12 }}><span className="n">06</span><span className="t">Your pathway</span></div>
        <div className="pw-switch">
          {window.PATHWAY_VARIANTS.map(v => <button key={v.key} aria-pressed={variant === v.key} onClick={() => setVariant(v.key)}>{v.label}</button>)}
        </div>
      </div>
      <div className="pwbox">{active.render(r)}</div>
      <p className="pw-note">This is not random. Your audit identified <b>Message</b> as the first place to focus, with <b>Convert</b> and <b>Leadership</b> as supporting areas to keep in view. F.R.E.S.H is the baseline beneath it all.</p>
    </div></section>
  );
}

/* ---- Section 7: FFB bridge ---- */
function FFBBridge({ variant }) {
  const b = R2().ffbBridge;
  const hard = variant === "hard";
  return (
    <section className="rs"><div className="v2-wrap">
      <div className={"bridge " + (hard ? "bridge--hard" : "bridge--soft")}>
        <div className="bridge__inner">
          <div>
            <p className="bridge__eyebrow">Where this goes next</p>
            <h3 className="bridge__title">Your audit result is the <em>starting point</em>.</h3>
            <p className="bridge__copy">{b.copy}</p>
          </div>
          <div className="bridge__side">
            <Btn variant={hard ? "light" : ""} icon="arrow" as="a" href="#" onClick={e => e.preventDefault()}>{hard ? "Get your next step" : b.cta.label}</Btn>
            <Btn variant="ghost" as="a" href="#" onClick={e => e.preventDefault()} style={hard ? { color: "var(--p-oatmeal)", borderColor: "var(--p-oatmeal)" } : {}}>{hard ? "Talk through your pathway" : "See how FFB helps with this"}</Btn>
          </div>
        </div>
      </div>
    </div></section>
  );
}

/* ---- Section 8: drawers ---- */
function Drawers() {
  const [open, setOpen] = useState(null);
  const items = [
    { q: "Why we chose this as your first focus", a: "Message sits earliest in the build sequence. Tightening it makes attract, convert and leadership noticeably easier, so it returns the most for the least effort right now." },
    { q: "What this may be costing you", a: R2().primaryBusinessFocus.likelyCost },
    { q: "How your two supporting areas fit", a: "Convert and Leadership are next in the sequence, not separate problems. Once your message carries more weight, a cleaner sales pathway and clearer boundaries fall into place faster." },
    { q: "How F.R.E.S.H supports implementation", a: R2().implementationSupportSignal.summary + " " + R2().implementationSupportSignal.detail },
  ];
  return (
    <section className="rs"><div className="v2-wrap">
      <div className="rs__label"><span className="n">07</span><span className="t">Go deeper, only if you want to</span></div>
      <div className="drawers">
        {items.map((it, i) => (
          <div className="drawer" key={i} data-open={open === i}>
            <button className="drawer__btn" onClick={() => setOpen(open === i ? null : i)}>{it.q}<Icon name={open === i ? "x" : "arrow"} size={18} /></button>
            <div className="drawer__panel"><p>{it.a}</p></div>
          </div>
        ))}
      </div>
    </div></section>
  );
}

/* ---- Soft floating bridge to Freedom Filled Business ---- */
function FFBFloatingBar() {
  const [closed, setClosed] = useState(false);
  if (closed) {
    return (
      <button className="ffb-reopen" onClick={() => setClosed(false)} aria-label="Show Freedom Filled Business pathway">
        <FFBMark size={20} color="var(--p-aztek)" />
        <span>Your full pathway</span>
      </button>
    );
  }
  return (
    <div className="ffb-bar" role="complementary">
      <div className="ffb-bar__mark"><FFBMark size={32} color="var(--p-aztek)" /></div>
      <div className="ffb-bar__copy">
        <p className="ffb-bar__label">Your full implementation pathway</p>
        <p className="ffb-bar__text">Freedom Filled<span className="reg">&reg;</span> Business is where this focus becomes a plan, with the support to carry it out.</p>
      </div>
      <a className="btn ffb-bar__cta" href="#" onClick={e => e.preventDefault()}>Explore the program<Icon name="arrow" size={15} /></a>
      <button className="ffb-bar__close" onClick={() => setClosed(true)} aria-label="Dismiss"><Icon name="x" size={16} /></button>
    </div>
  );
}

/* ============ Results2 shell ============ */
function Results2({ go, tweaks, setTweak, name }) {
  const [pathwayVar, setPathwayVar] = useState(tweaks.pathwayVisual || "layered");
  useEffect(() => { setPathwayVar(tweaks.pathwayVisual || "layered"); }, [tweaks.pathwayVisual]);
  return (
    <div className="v2">
      <TopBar onHome={() => go("landing")} right={<Btn variant="ghost" onClick={() => go("bridge")}>Next step</Btn>} />
      <ResultHero variant={tweaks.heroStyle} name={name} />
      <TopThree variant={tweaks.topThreeStyle} />
      <WhyHere />
      <FirstFix />
      <SupportSignal variant={tweaks.freshStyle} />
      <PathwaySection variant={pathwayVar} setVariant={(v) => { setPathwayVar(v); setTweak("pathwayVisual", v); }} />
      <FFBBridge variant={tweaks.bridgeStyle} />
      <Drawers />
      <Footer2 />
      <FFBFloatingBar />
    </div>
  );
}

Object.assign(window, { Results2, ResultHero, TopThree, PathwaySection, ScoreSnapshot, WhyHere, FirstFix, SupportSignal, FFBBridge, Drawers, FFBFloatingBar });
