/* ============================================================
   BridgeOS — Level Test (onboarding calibration)
   Multi-step honest self-assessment across all 6 stats.
   Seeds starting scores so experienced people don't start at zero.
   ============================================================ */
function LevelTest({ name, onDone, onSkip }) {
  const PP = window.PP;
  const [step, setStep] = useState(0);
  const [v, setV] = useState({
    pushups: 15, pullups: 3, liftYrs: 0,
    runKm: 2, cardioDay: 2,
    streakDays: 0, routineDays: 2,
    readHrs: 1, focusHrs: 1,
    skillHrs: 3, skillYrs: 1,
    income: 0,
  });
  const set = function(k) { return function(e) { setV(function(prev) { var n = {}; Object.assign(n, prev); n[k] = Number(e.target.value); return n; }); }; };

  // Seed values: calibrated so strong/skilled people land at Lv 3-5
  // The 0.5 factor in decayedScores halves these before applying
  const seed = {
    STR: Math.round(v.pushups * 14 + v.pullups * 45 + v.liftYrs * 120),
    END: Math.round(v.runKm * 120 + v.cardioDay * 60),
    DIS: Math.round(v.streakDays * 18 + v.routineDays * 22),
    MND: Math.round(v.readHrs * 55 + v.focusHrs * 40),
    SKL: Math.round(v.skillHrs * 60 + v.skillYrs * 90),
    WLT: Math.round(v.income),
  };

  function LvBar(props) {
    var cat = props.cat;
    var s = seed[cat] || 0;
    var info = PP.catLevel(s * 0.5);
    var pct = ((info.level - 1) + info.pct) / 10 * 100;
    var col = "oklch(0.82 0.15 " + PP.CATS[cat].hue + ")";
    return (
      <div className="lt-lv-bar">
        <span className="lt-lv-cat mono" style={{ color: col }}>{cat}</span>
        <div className="lt-lv-track"><div className="lt-lv-fill" style={{ width: pct + "%", background: col }} /></div>
        <span className="lt-lv-num mono" style={{ color: col }}>Lv {info.level}</span>
      </div>
    );
  }

  function Marks(props) {
    return <div className="lt-range-labels mono">{props.items.map(function(m, i) { return <span key={i}>{m}</span>; })}</div>;
  }

  var STEPS = ["STR","END","DIS","MND","SKL","WLT","review"];
  var CAT_NAMES = { STR:"Strength", END:"Endurance", DIS:"Discipline", MND:"Mind", SKL:"Skill", WLT:"Wealth" };

  var pages = [
    <div className="stack" key="str">
      <div className="lt-cat-label" style={{ color: "oklch(0.82 0.15 " + PP.CATS.STR.hue + ")" }}>Strength</div>
      <p className="lt-desc dim">Rate your current ability honestly. This calibrates your starting level — not your potential.</p>
      <Field label={"Max push-ups in one set — " + v.pushups}>
        <input className="range" type="range" min="0" max="100" value={v.pushups} onChange={set("pushups")} />
        <Marks items={["0","25","50","75","100"]} />
      </Field>
      <Field label={"Max pull-ups in one set — " + v.pullups}>
        <input className="range" type="range" min="0" max="30" value={v.pullups} onChange={set("pullups")} />
        <Marks items={["0","8","15","22","30+"]} />
      </Field>
      <Field label={"Years of consistent weight training — " + v.liftYrs}>
        <input className="range" type="range" min="0" max="15" value={v.liftYrs} onChange={set("liftYrs")} />
        <Marks items={["Never","3 yrs","7 yrs","12 yrs","15+ yrs"]} />
      </Field>
      <LvBar cat="STR" />
    </div>,

    <div className="stack" key="end">
      <div className="lt-cat-label" style={{ color: "oklch(0.82 0.15 " + PP.CATS.END.hue + ")" }}>Endurance</div>
      <p className="lt-desc dim">Your cardio capacity right now — not your personal best from years ago.</p>
      <Field label={"Longest distance you can run today without stopping — " + v.runKm + " km"}>
        <input className="range" type="range" min="0" max="42" step="0.5" value={v.runKm} onChange={set("runKm")} />
        <Marks items={["0 km","5 km","10 km","21 km","Marathon"]} />
      </Field>
      <Field label={"Cardio sessions per week (run, bike, swim) — " + v.cardioDay + "x"}>
        <input className="range" type="range" min="0" max="7" value={v.cardioDay} onChange={set("cardioDay")} />
        <Marks items={["Never","2x","4x","6x","Daily"]} />
      </Field>
      <LvBar cat="END" />
    </div>,

    <div className="stack" key="dis">
      <div className="lt-cat-label" style={{ color: "oklch(0.82 0.15 " + PP.CATS.DIS.hue + ")" }}>Discipline</div>
      <p className="lt-desc dim">Discipline is built by showing up every day. How consistent have you been?</p>
      <Field label={"Current unbroken daily habit streak — " + v.streakDays + " days"}>
        <input className="range" type="range" min="0" max="365" value={v.streakDays} onChange={set("streakDays")} />
        <Marks items={["0","30d","90d","180d","365d"]} />
      </Field>
      <Field label={"Days per week you follow a structured routine — " + v.routineDays}>
        <input className="range" type="range" min="0" max="7" value={v.routineDays} onChange={set("routineDays")} />
        <Marks items={["Never","2","4","6","Every day"]} />
      </Field>
      <LvBar cat="DIS" />
    </div>,

    <div className="stack" key="mnd">
      <div className="lt-cat-label" style={{ color: "oklch(0.82 0.15 " + PP.CATS.MND.hue + ")" }}>Mind</div>
      <p className="lt-desc dim">Mental sharpness through deliberate reading and deep focus work.</p>
      <Field label={"Hours per week reading books — " + v.readHrs + " hrs"}>
        <input className="range" type="range" min="0" max="20" step="0.5" value={v.readHrs} onChange={set("readHrs")} />
        <Marks items={["Never","3h","8h","14h","20h+"]} />
      </Field>
      <Field label={"Hours per week of deep focus work, no phone — " + v.focusHrs + " hrs"}>
        <input className="range" type="range" min="0" max="30" step="0.5" value={v.focusHrs} onChange={set("focusHrs")} />
        <Marks items={["Rarely","5h","15h","25h","30h+"]} />
      </Field>
      <LvBar cat="MND" />
    </div>,

    <div className="stack" key="skl">
      <div className="lt-cat-label" style={{ color: "oklch(0.82 0.15 " + PP.CATS.SKL.hue + ")" }}>Skill</div>
      <p className="lt-desc dim">Craft, music, coding, art, business — whatever you are building mastery in.</p>
      <Field label={"Hours per week actively practising your main skill — " + v.skillHrs + " hrs"}>
        <input className="range" type="range" min="0" max="40" value={v.skillHrs} onChange={set("skillHrs")} />
        <Marks items={["0","10h","20h","30h","40h+"]} />
      </Field>
      <Field label={"Years seriously developing this skill — " + v.skillYrs}>
        <input className="range" type="range" min="0" max="20" value={v.skillYrs} onChange={set("skillYrs")} />
        <Marks items={["Starting","3 yrs","8 yrs","14 yrs","20+ yrs"]} />
      </Field>
      <LvBar cat="SKL" />
    </div>,

    <div className="stack" key="wlt">
      <div className="lt-cat-label" style={{ color: "oklch(0.82 0.15 " + PP.CATS.WLT.hue + ")" }}>Wealth</div>
      <p className="lt-desc dim">Money earned from your effort — employment, freelance, or business.</p>
      <Field label={"Monthly income / earnings — $" + v.income.toLocaleString()}>
        <input className="range" type="range" min="0" max="30000" step="250" value={v.income} onChange={set("income")} />
        <Marks items={["$0","$5k","$12k","$22k","$30k+"]} />
      </Field>
      <p className="dim mono" style={{ fontSize:12 }}>Wealth decays very slowly — consistent income compounds over time.</p>
      <LvBar cat="WLT" />
    </div>,

    <div className="stack" key="review">
      <p className="lt-desc">Your starting stats. Levels get significantly harder to earn the higher you climb — this is your foundation to build on.</p>
      <div className="lt-review-bars">
        {PP.CAT_ORDER.map(function(c) {
          var s = seed[c] || 0;
          var info = PP.catLevel(s * 0.5);
          var col = "oklch(0.82 0.15 " + PP.CATS[c].hue + ")";
          var barPct = ((info.level - 1) + info.pct) / 10 * 100;
          var ptsLeft = Math.round(info.span - info.into);
          return (
            <div key={c} className="lt-review-row">
              <span className="lt-review-cat" style={{ color: col }}>{c}</span>
              <div className="lt-lv-track"><div className="lt-lv-fill" style={{ width: barPct + "%", background: col }} /></div>
              <span className="lt-review-lv mono" style={{ color: col }}>Lv {info.level}</span>
              <span className="dim mono" style={{ fontSize:11 }}>{ptsLeft} pts to Lv {info.level + 1}</span>
            </div>
          );
        })}
      </div>
      <p className="dim mono" style={{ fontSize:12, marginTop:8 }}>Discipline and Mind can only be built by logging every day — they start low for everyone and grow from real data.</p>
    </div>,
  ];

  var isReview = step === STEPS.length - 1;
  var totalLvl = PP.CAT_ORDER.reduce(function(a, c) { return a + PP.catLevel((seed[c]||0)*0.5).level; }, 0);
  var catLabel = step < 6 ? (CAT_NAMES[STEPS[step]] || "") : "Review";

  return (
    <Modal open dismissable={false} onClose={function(){}} title={"Calibrate — " + catLabel}
      footer={
        <div style={{ display:"flex", gap:8, width:"100%", justifyContent:"space-between", alignItems:"center" }}>
          <div>
            {step > 0
              ? <button className="btn" onClick={function(){ setStep(step - 1); }}>Back</button>
              : <button className="btn" onClick={onSkip}>Skip (Lv 1)</button>
            }
          </div>
          <div style={{ display:"flex", gap:8, alignItems:"center" }}>
            <span className="dim mono" style={{ fontSize:12 }}>{step + 1} / {STEPS.length}</span>
            {!isReview
              ? <button className="btn btn-accent" onClick={function(){ setStep(step + 1); }}>Next</button>
              : <button className="btn btn-accent" onClick={function(){ onDone(seed); }}>Start at Level {totalLvl}</button>
            }
          </div>
        </div>
      }>
      {pages[step]}
    </Modal>
  );
}

Object.assign(window, { LevelTest });
