/* =====================================================================
   flow2.jsx — v2 landing, profile, question flow + transitions,
   mapping state, bridge/confirmation. Self-contained (no v1 deps).
   ===================================================================== */

function Footer2() {
  return (
    <footer className="foot">
      <div className="foot__inner">
        <div className="foot__top">
          <div>
            <div className="foot__brand">The Freedom Filled<span className="reg">&reg;</span> Pathway Audit</div>
            <p className="foot__tag">A diagnostic from Tracy Harris Co. Peace, profit and presence, by design.</p>
          </div>
          <nav className="foot__links"><a href="#" onClick={e=>e.preventDefault()}>Privacy</a><a href="#" onClick={e=>e.preventDefault()}>Terms</a><a href="#" onClick={e=>e.preventDefault()}>Contact</a></nav>
        </div>
        <div className="foot__bottom"><span>&copy; 2026 Tracy Harris Co. All rights reserved.</span><span>Your answers are private and used only to map your pathway.</span></div>
      </div>
    </footer>
  );
}

/* ============ LANDING v2 ============ */
function Landing2({ go, landingStyle }) {
  const framework = landingStyle !== "minimal";
  const copy = (
    <div>
      <span className="l2-pill"><span className="dot"></span>Premium business diagnostic &middot; 6 minutes</span>
      <h1 className="l2-title">Where should you <em>focus next</em> in your business?</h1>
      <p className="l2-sub">{window.FFP2.AUDIT2.subhook} The audit maps you to your one most important focus, the two that support it, and the rhythm that helps you implement it.</p>
      <div className="l2-actions">
        <Btn variant="" onClick={() => go("profile")} icon="arrow">Start the audit</Btn>
        <Btn as="a" href="#how" variant="ghost">How it works</Btn>
      </div>
      <dl className="l2-meta">
        <div><dt>Questions</dt><dd>12</dd></div>
        <div><dt>The pathway</dt><dd>Build &middot; Sell &middot; Lead</dd></div>
        <div><dt>Your result</dt><dd>One next move</dd></div>
      </dl>
    </div>
  );
  return (
    <div className="screen v2">
      <TopBar right={<Btn onClick={() => go("profile")} icon="arrow">Start the audit</Btn>} onHome={() => go("landing")} />
      <section className="l2-hero"><div className="v2-wrap">
        {framework ? (
          <div className="l2-grid">
            {copy}
            <div className="l2-preview">
              <CircularPathway result={window.FFP2.RESULT2} size={360} />
              <p className="l2-preview__cap">The Freedom Filled<span className="reg">&reg;</span> Business pathway</p>
            </div>
          </div>
        ) : (
          <div style={{ maxWidth: 720, margin: "0 auto", textAlign: "center" }}>
            <div style={{ display: "inline-block" }}>{copy}</div>
          </div>
        )}
      </div></section>

      <section className="rs section--elevated" id="how" style={{ background: "var(--surface-elevated)" }}><div className="v2-wrap">
        <div className="rs__label"><span className="n">01</span><span className="t">What you get</span></div>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 16 }} className="l2-how">
          {[
            { t: "One clear focus", d: "Not a list of everything wrong. The single most important place to tighten next." },
            { t: "Two supporting areas", d: "What to keep in view, so the next moves get easier, not heavier." },
            { t: "A pathway, not a verdict", d: "See where your focus sits inside the Build, Sell, Lead pathway, with F.R.E.S.H beneath it." },
          ].map((c, i) => (
            <div key={i} style={{ background: "var(--surface-canvas)", border: "1px solid var(--border-hairline)", borderRadius: 10, padding: "26px 24px" }}>
              <div style={{ fontFamily: "var(--f-serif-display)", fontSize: 15, color: "var(--p-sage)", marginBottom: 10 }}>0{i + 1}</div>
              <h3 style={{ fontFamily: "var(--f-serif-display)", fontWeight: 400, fontSize: 22, color: "var(--ink-heading)", margin: "0 0 8px", lineHeight: 1.15 }}>{c.t}</h3>
              <p style={{ fontFamily: "var(--f-sans)", fontSize: 13.5, lineHeight: 1.6, color: "var(--ink-body)", margin: 0 }}>{c.d}</p>
            </div>
          ))}
        </div>
        <div style={{ marginTop: 36, textAlign: "center" }}><Btn variant="" onClick={() => go("profile")} icon="arrow">Find your next focus</Btn></div>
      </div></section>
      <Footer2 />
    </div>
  );
}

/* ============ PROFILE v2 (lean) ============ */
function Profile2({ go, profile, setProfile }) {
  const [err, setErr] = useState({});
  const set = (k, v) => setProfile(p => ({ ...p, [k]: v }));
  const stages = [["idea","Idea or early"],["inconsistent","Growing"],["established","Established"],["scaling","Scaling"]];
  const submit = (e) => {
    e.preventDefault();
    const x = {};
    if (!profile.firstName.trim()) x.firstName = "Please add your first name.";
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(profile.email)) x.email = "We need a valid email for your result.";
    if (!profile.consent) x.consent = "Please tick to receive your result.";
    setErr(x); if (!Object.keys(x).length) go("question");
  };
  return (
    <div className="v2">
      <TopBar step="Step 1 of 2 &middot; Your details" onHome={() => go("landing")} />
      <div className="split">
        <aside className="split__aside">
          <div className="split__aside-photo"><img src="assets/images/tracy-lifestyle-desk.jpg" alt="" /></div>
          <div className="split__aside-inner">
            <p className="eyebrow">Before we begin</p>
            <h2>This makes your pathway <em>yours</em>.</h2>
            <p>A few details so your result speaks to your real stage and situation, not a generic average.</p>
            <div className="split__aside-marks">
              <div className="split__aside-mark"><Icon name="lock" size={17} /><span>Private. Used only to map and send your result.</span></div>
              <div className="split__aside-mark"><Icon name="clock" size={17} /><span>The audit takes about six minutes.</span></div>
            </div>
          </div>
        </aside>
        <main className="split__form">
          <form className="form-shell" onSubmit={submit} noValidate>
            <p className="eyebrow" style={{ marginBottom: 10 }}>Your details</p>
            <h2 className="serif" style={{ fontSize: 30, color: "var(--ink-heading)", margin: "0 0 26px", lineHeight: 1.1 }}>Where should we send your result?</h2>
            <div className="field-row">
              <div className="field"><label className="field__label">First name <span className="field__req">*</span></label>
                <input className={"input" + (err.firstName ? " input--error" : "")} value={profile.firstName} onChange={e => set("firstName", e.target.value)} placeholder="Leah" />
                {err.firstName && <div className="field__error"><Icon name="alert" size={13} />{err.firstName}</div>}</div>
              <div className="field"><label className="field__label">Last name <span className="opt">optional</span></label>
                <input className="input" value={profile.lastName} onChange={e => set("lastName", e.target.value)} placeholder="Marsh" /></div>
            </div>
            <div className="field"><label className="field__label">Email <span className="field__req">*</span></label>
              <input className={"input" + (err.email ? " input--error" : "")} type="email" value={profile.email} onChange={e => set("email", e.target.value)} placeholder="you@yourbusiness.com" />
              {err.email && <div className="field__error"><Icon name="alert" size={13} />{err.email}</div>}</div>
            <div className="field"><label className="field__label">Business stage <span className="opt">optional</span></label>
              <div className="chip-set">{stages.map(([v, l]) => <button type="button" key={v} className="chip" aria-pressed={profile.businessStage === v} onClick={() => set("businessStage", profile.businessStage === v ? "" : v)}>{l}</button>)}</div></div>
            <label className="consent"><input type="checkbox" checked={profile.consent} onChange={e => set("consent", e.target.checked)} /><span>Yes, send my result and the occasional note from Tracy. Unsubscribe anytime.</span></label>
            {err.consent && <div className="field__error" style={{ marginTop: -16, marginBottom: 16 }}><Icon name="alert" size={13} />{err.consent}</div>}
            <div className="form-actions">
              <button type="button" className="q-back" onClick={() => go("landing")}><Icon name="arrowLeft" size={15} />Back</button>
              <Btn as="button" type="submit" variant="" icon="arrow">Begin the audit</Btn>
            </div>
          </form>
        </main>
      </div>
    </div>
  );
}

/* ============ TRANSITION PAGE (personalised + image treatments) ============ */
function TransitionPage({ section, idx, total, onContinue, onBack, treatment, name }) {
  const lead = name && idx === 0 ? `Thanks, ${name}.` : null;
  let title = section.title;
  if (name && section.key === "lead") title = `${name}, ${title.charAt(0).toLowerCase()}${title.slice(1)}`;
  const progress = (
    <div className="trans__rel">
      <span className="lbl">{section.relation}</span>
      <span className="seg">{window.FFP2.SECTIONS.map((s, i) => <span key={s.key} className={i === idx ? "on" : ""}></span>)}</span>
    </div>
  );
  const inner = (
    <React.Fragment>
      <p className="trans__eyebrow">{section.eyebrow}</p>
      {lead && <p className="trans__lead">{lead}</p>}
      <h2 className="trans__title">{title}</h2>
      <p>{section.body}</p>
      {progress}
      <div><Btn variant="" onClick={onContinue} icon="arrow">{idx === 0 ? "Let's begin" : "Continue"}</Btn></div>
    </React.Fragment>
  );

  if (treatment === "editorial") {
    return (
      <div className="trans v2">
        <TopBar step={`Section ${idx + 1} of ${total}`} onHome={onBack} />
        <div className="trans-img">
          <div className="trans-img__media"><img src={section.image} alt="" /><span className="trans-img__cap script">{section.caption}</span></div>
          <div className="trans-img__copy"><div className="trans-img__inner fadein" key={section.key}>{inner}</div></div>
        </div>
      </div>
    );
  }
  if (treatment === "texture") {
    return (
      <div className="trans v2 trans--texture">
        <TopBar step={`Section ${idx + 1} of ${total}`} onHome={onBack} />
        <div className="trans__body">
          <div className="trans-tex" aria-hidden="true">
            <svg viewBox="0 0 600 600" className="trans-tex__arcs">
              {[260, 210, 160, 110].map((r, i) => <circle key={i} cx="300" cy="300" r={r} fill="none" stroke="var(--p-sage)" strokeOpacity={0.16 - i * 0.02} strokeWidth="1" />)}
            </svg>
            <div className="trans-tex__chip"><img src={section.image} alt="" /></div>
          </div>
          <div className="trans__inner fadein" key={section.key} style={{ position: "relative", zIndex: 2 }}>{inner}</div>
        </div>
      </div>
    );
  }
  return (
    <div className="trans v2">
      <TopBar step={`Section ${idx + 1} of ${total}`} onHome={onBack} />
      <div className="trans__body"><div className="trans__inner fadein" key={section.key}>{inner}</div></div>
    </div>
  );
}

/* ============ QUESTION FLOW (sectioned, with transitions) ============ */
function QuestionFlow2({ go, answers, setAnswers, transitionTreatment, name }) {
  const SECTIONS = window.FFP2.SECTIONS, QS = window.FFP2.QUESTIONS2;
  const bySection = SECTIONS.map(s => QS.filter(q => q.section === s.key));
  const [si, setSi] = useState(0);
  const [qi, setQi] = useState(-1); // -1 = show transition
  const total = QS.length;
  const answeredCount = Object.keys(answers).length;

  const sectionQs = bySection[si];
  const q = qi >= 0 ? sectionQs[qi] : null;
  const keys = ["A", "B", "C", "D"];

  const next = () => {
    if (qi < sectionQs.length - 1) { setQi(qi + 1); window.scrollTo(0, 0); }
    else if (si < SECTIONS.length - 1) { setSi(si + 1); setQi(-1); window.scrollTo(0, 0); }
    else go("mapping");
  };
  const back = () => {
    if (qi > 0) setQi(qi - 1);
    else if (qi === 0) setQi(-1);
    else if (si > 0) { setSi(si - 1); setQi(bySection[si - 1].length - 1); }
    else go("profile");
    window.scrollTo(0, 0);
  };

  if (qi === -1) {
    return <TransitionPage section={SECTIONS[si]} idx={si} total={SECTIONS.length} treatment={transitionTreatment} name={name}
      onContinue={() => { setQi(0); window.scrollTo(0, 0); }} onBack={back} />;
  }

  const selected = answers[q.id];
  const pct = (answeredCount / total) * 100;
  return (
    <div className="q-screen v2">
      <TopBar step={`${SECTIONS[si].relation}`} onHome={() => go("landing")} right={<button className="q-save" onClick={() => go("landing")}>Save &amp; exit</button>} />
      <div className="q-progress"><div className="q-progress__bar" style={{ width: pct + "%" }} /></div>
      <div className="q-body"><div className="q-inner fadein" key={q.id}>
        <div className="q-meta">
          <span className="q-count">Question <b>{String(QS.indexOf(q) + 1).padStart(2, "0")}</b> of {total}</span>
          <span className="q-dim"><span className="rule"></span>{SECTIONS[si].eyebrow}</span>
        </div>
        <h2 className="q-text">{q.text}</h2>
        <div className="q-options">
          {q.options.map((o, oi) => (
            <button key={o.id} className="q-option" aria-pressed={selected === o.id} onClick={() => setAnswers(a => ({ ...a, [q.id]: o.id }))}>
              <span className="q-option__key">{selected === o.id ? <Icon name="check" size={13} /> : keys[oi]}</span>
              <span className="q-option__text">{o.text}</span>
            </button>
          ))}
        </div>
        {q.note && <p style={{ marginTop: 20, fontFamily: "var(--f-sans)", fontSize: 13, fontStyle: "italic", color: "var(--ink-mute)", display: "flex", gap: 9, alignItems: "flex-start" }}><span style={{ color: "var(--p-sage)", flex: "0 0 auto", marginTop: 1 }}><Icon name="spark" size={15} /></span>{q.note}</p>}
      </div></div>
      <div className="q-foot">
        <button className="q-back" onClick={back}><Icon name="arrowLeft" size={15} />Back</button>
        <Btn variant="" onClick={next} icon="arrow" aria-disabled={!selected} disabled={!selected}>{(si === SECTIONS.length - 1 && qi === sectionQs.length - 1) ? "Map my pathway" : "Continue"}</Btn>
      </div>
    </div>
  );
}

/* ============ MAPPING STATE ============ */
function Mapping2({ go, name }) {
  useEffect(() => { const t = setTimeout(() => go("results"), 2900); return () => clearTimeout(t); }, []);
  const acc = (window.__ffp2Theme && window.__ffp2Theme.accent) || "#6e8e77";
  return (
    <div className="mapping">
      <div className="mapping__photo" aria-hidden="true"><img src="assets/images/tracy-lifestyle-1.jpg" alt="" /></div>
      <div className="mapping__inner">
        <svg width="60" height="60" viewBox="0 0 60 60" style={{ animation: "spin 1.1s linear infinite", margin: "0 auto" }}>
          <circle cx="30" cy="30" r="25" fill="none" stroke="rgba(246,244,241,0.18)" strokeWidth="4" />
          <path d="M30 5 a25 25 0 0 1 25 25" fill="none" stroke={acc} strokeWidth="4" strokeLinecap="round" />
        </svg>
        <h1 className="mapping__title">Mapping your <em>pathway</em>{name ? ", " + name : ""}</h1>
        <p className="mapping__sub">We are looking at your business focus, your supporting areas, and the rhythm that will help you implement the next move.</p>
      </div>
    </div>
  );
}

/* ============ BRIDGE / CONFIRMATION PAGE ============ */
function BridgePage({ go, name }) {
  const r = window.FFP2.RESULT2;
  const who = name || r.firstName;
  return (
    <div className="screen v2">
      <TopBar onHome={() => go("landing")} />
      <section className="rs" style={{ flex: 1, display: "grid", placeItems: "center", background: "var(--surface-elevated)" }}>
        <div className="v2-wrap v2-wrap--narrow" style={{ textAlign: "center" }}>
          <div style={{ width: 60, height: 60, borderRadius: "50%", background: "var(--p-sage)", display: "grid", placeItems: "center", margin: "0 auto 26px", color: "#fff" }}><Icon name="check" size={28} /></div>
          <p className="eyebrow" style={{ textAlign: "center", marginBottom: 14 }}>{who ? "Your pathway is saved, " + who : "Your pathway is saved"}</p>
          <h1 className="trans__title">Freedom Filled<span className="reg">&reg;</span> Business is where the <em>full pathway</em> comes together.</h1>
          <p style={{ fontFamily: "var(--f-sans)", fontSize: 16, lineHeight: 1.7, color: "var(--ink-body)", maxWidth: "48ch", margin: "0 auto 30px" }}>{r.ffbBridge.copy}</p>
          <div style={{ display: "flex", gap: 18, justifyContent: "center", flexWrap: "wrap" }}>
            <Btn variant="" icon="arrow" as="a" href="#" onClick={e => e.preventDefault()}>{r.ffbBridge.cta.label}</Btn>
            <Btn variant="ghost" onClick={() => go("results")}>Back to my result</Btn>
          </div>
        </div>
      </section>
      <Footer2 />
    </div>
  );
}

Object.assign(window, { Footer2, Landing2, Profile2, QuestionFlow2, TransitionPage, Mapping2, BridgePage });
