/* Onboarding — TDEE mandatory first step, then goal/path selection */
const { useState, useMemo } = React;
const { Brand, Ring, Eyebrow, Icon, DataRow } = window;

function Onboarding({ user, onDone }) {
  const [step, setStep] = useState(0);
  const [unit, setUnit] = useState("metric"); // 'metric' | 'imperial'
  const [sex, setSex] = useState("male");
  const [age, setAge] = useState(32);
  const [kg, setKg] = useState(78.4);
  const [cm, setCm] = useState(172);
  const [activity, setActivity] = useState("moderate");
  const [goal, setGoal] = useState("lose");
  const [level, setLevel] = useState("moderate");

  const tdee = useMemo(() => {
    const k = unit === "metric" ? kg : window.TDEE.lbsToKg(kg);
    const c = unit === "metric" ? cm : cm;
    return Math.round(window.TDEE.calcTDEE({ sex, kg: k, cm: c, age, activity }));
  }, [sex, age, kg, cm, activity, unit]);

  const goalPreset = window.TDEE.GOAL_PRESETS[goal].find(g => g.id === level) || window.TDEE.GOAL_PRESETS[goal][0];
  const target = useMemo(() => Math.round(tdee * (1 + (goalPreset?.pct || 0))), [tdee, goalPreset]);
  const macros = useMemo(() => window.TDEE.macrosForTarget(target, unit === "metric" ? kg : window.TDEE.lbsToKg(kg), goal), [target, kg, goal, unit]);

  function finish() {
    onDone({
      sex, age, weightKg: unit === "metric" ? kg : window.TDEE.lbsToKg(kg),
      heightCm: cm, activity, tdee, goal, level, target, macros,
    });
  }

  const steps = ["Your body", "Activity", "Goal", "Confirm"];

  return (
    <div className="fade-in auth-split wide">
      {/* Left — coaching copy */}
      <div style={{
        background: "var(--bg-soft)", padding: "56px 56px",
        display: "flex", flexDirection: "column", gap: 32,
        borderRight: "1px solid var(--line)",
      }}>
        <Brand size="md" />

        <div className="stepper" style={{ marginTop: 16 }}>
          {steps.map((_, i) => (
            <div key={i} className={i < step ? "done" : i === step ? "on" : ""} />
          ))}
        </div>

        <div>
          <Eyebrow>Step {step + 1} of {steps.length} — {steps[step]}</Eyebrow>
          <h1 className="h-hero" style={{ marginTop: 16, fontSize: "clamp(36px, 4.5vw, 64px)" }}>
            {step === 0 && <>Tell us about<br/>your body.</>}
            {step === 1 && <>How active<br/>are you?</>}
            {step === 2 && <>What's the<br/>goal?</>}
            {step === 3 && <>Looks good?<br/>Let's lock it in.</>}
          </h1>
          <p className="muted" style={{ maxWidth: 460, marginTop: 20 }}>
            {step === 0 && "Honest numbers in, honest target out. We use the Mifflin-St Jeor equation — the same one tdeecalculator.net uses."}
            {step === 1 && "Pick the level that matches a typical week. If you're between two, round down — we'd rather under-promise."}
            {step === 2 && "You can change your path any time. Slow is sustainable; aggressive will be hard but faster."}
            {step === 3 && "This becomes your starting target. We'll re-check it weekly as your weight changes."}
          </p>
        </div>

        <div className="card" style={{ background: "var(--bg)" }}>
          <div className="row" style={{ gap: 20 }}>
            <Ring value={target} max={Math.max(tdee, target) * 1.1} size={100} stroke={10}
                  label={target.toLocaleString()} sub="kcal target" />
            <div className="col" style={{ gap: 10, flex: 1 }}>
              <DataRow k="BMR"  v={Math.round(window.TDEE.calcBMR({ sex, kg: unit === "metric" ? kg : window.TDEE.lbsToKg(kg), cm, age })).toLocaleString() + " kcal"} muted />
              <DataRow k="TDEE" v={tdee.toLocaleString() + " kcal"} />
              <DataRow k="Goal" v={goalPreset?.label || "—"} />
              <DataRow k="Path" v={goal === "lose" ? "Lose weight" : goal === "gain" ? "Gain weight" : "Maintain"} />
            </div>
          </div>
        </div>

        <div className="mono muted" style={{ fontSize: 11, marginTop: "auto" }}>
          Formula: Mifflin-St Jeor • Macros: 2.0–2.2g protein / kg, 25% fat, remainder carbs
        </div>
      </div>

      {/* Right — form */}
      <div style={{ padding: "56px 48px", display: "flex", flexDirection: "column" }}>
        <div className="between" style={{ marginBottom: 32 }}>
          <Eyebrow>Onboarding</Eyebrow>
          <div className="seg">
            <button className={unit === "metric"   ? "on" : ""} onClick={() => setUnit("metric")}>Metric</button>
            <button className={unit === "imperial" ? "on" : ""} onClick={() => setUnit("imperial")}>Imperial</button>
          </div>
        </div>

        {step === 0 && (
          <div className="col" style={{ gap: 18 }}>
            <div className="field">
              <label className="field-label">Sex (for BMR formula)</label>
              <div className="seg" style={{ alignSelf: "flex-start" }}>
                <button className={sex === "male"   ? "on" : ""} onClick={() => setSex("male")}>Male</button>
                <button className={sex === "female" ? "on" : ""} onClick={() => setSex("female")}>Female</button>
              </div>
            </div>
            <div className="grid-2">
              <NumberField label="Age" value={age} suffix="yrs" onChange={setAge} min={13} max={90} />
              <NumberField label={"Weight (" + (unit === "metric" ? "kg" : "lb") + ")"}
                value={kg} suffix={unit === "metric" ? "kg" : "lb"} onChange={setKg} step={0.1} />
            </div>
            <NumberField label={"Height (" + (unit === "metric" ? "cm" : "cm") + ")"}
              value={cm} suffix="cm" onChange={setCm} min={120} max={220} />
          </div>
        )}

        {step === 1 && (
          <div className="col" style={{ gap: 10 }}>
            {window.TDEE.ACTIVITY.map(a => (
              <OptionRow key={a.id}
                selected={activity === a.id}
                onClick={() => setActivity(a.id)}
                title={a.label}
                sub={a.desc}
                right={<span className="mono muted" style={{ fontSize: 12 }}>×{a.mult.toFixed(3)}</span>}
              />
            ))}
          </div>
        )}

        {step === 2 && (
          <div className="col" style={{ gap: 18 }}>
            <div className="field">
              <label className="field-label">Path</label>
              <div className="seg">
                <button className={goal === "lose"     ? "on" : ""} onClick={() => { setGoal("lose"); setLevel("moderate"); }}>Lose</button>
                <button className={goal === "maintain" ? "on" : ""} onClick={() => { setGoal("maintain"); setLevel("maintain"); }}>Maintain</button>
                <button className={goal === "gain"     ? "on" : ""} onClick={() => { setGoal("gain"); setLevel("moderate"); }}>Gain</button>
              </div>
            </div>
            <div className="field">
              <label className="field-label">Level</label>
              <div className="col" style={{ gap: 10 }}>
                {window.TDEE.GOAL_PRESETS[goal].map(g => (
                  <OptionRow key={g.id}
                    selected={level === g.id}
                    onClick={() => setLevel(g.id)}
                    title={g.label}
                    sub={g.desc}
                    right={<span className="mono" style={{ fontWeight: 600 }}>{Math.round(tdee * (1 + g.pct)).toLocaleString()} kcal</span>}
                  />
                ))}
              </div>
            </div>
          </div>
        )}

        {step === 3 && (
          <div className="col" style={{ gap: 18 }}>
            <div className="card">
              <Eyebrow>Daily calorie budget</Eyebrow>
              <div className="h-data" style={{ fontSize: 56, marginTop: 8 }}>
                {target.toLocaleString()} <span className="muted" style={{ fontSize: 18, fontWeight: 400 }}>kcal/day</span>
              </div>
              <div className="row" style={{ marginTop: 24, gap: 12, flexWrap: "wrap" }}>
                <span className="chip">{goalPreset?.label}</span>
                <span className="chip mono">TDEE {tdee.toLocaleString()}</span>
                <span className="chip mono">{goalPreset?.pct >= 0 ? "+" : ""}{Math.round((goalPreset?.pct || 0) * 100)}%</span>
              </div>
              <hr className="divider" style={{ margin: "20px 0" }} />
              <Eyebrow>Macros</Eyebrow>
              <div className="grid-3" style={{ marginTop: 12, gap: 16 }}>
                {[
                  ["Protein", macros.protein, "g", "var(--m-protein)"],
                  ["Carbs",   macros.carbs,   "g", "var(--m-carbs)"],
                  ["Fat",     macros.fat,     "g", "var(--m-fat)"],
                ].map(([k, v, u, c]) => (
                  <div key={k} className="card sunken" style={{ padding: 14 }}>
                    <div className="row" style={{ gap: 8, marginBottom: 8 }}>
                      <span className="tag-dot" style={{ background: c }} />
                      <span className="eyebrow">{k}</span>
                    </div>
                    <div className="mono" style={{ fontSize: 24, fontWeight: 700 }}>{v}<span className="muted" style={{ fontSize: 14, fontWeight: 400 }}>{u}</span></div>
                  </div>
                ))}
              </div>
            </div>
          </div>
        )}

        <div className="row" style={{ marginTop: "auto", paddingTop: 32, justifyContent: "space-between" }}>
          <button className="btn btn-ghost" disabled={step === 0} style={{ opacity: step === 0 ? 0.4 : 1 }}
                  onClick={() => setStep(s => Math.max(0, s - 1))}>
            Back
          </button>
          {step < 3 ? (
            <button className="btn btn-primary" onClick={() => setStep(s => s + 1)}>
              Continue <Icon name="arrow" size={14} />
            </button>
          ) : (
            <button className="btn btn-primary" onClick={finish}>
              Save & enter app <Icon name="arrow" size={14} />
            </button>
          )}
        </div>
      </div>
    </div>
  );
}

function NumberField({ label, value, onChange, suffix, min, max, step = 1 }) {
  return (
    <div className="field">
      <label className="field-label">{label}</label>
      <div style={{ position: "relative" }}>
        <input className="field-input mono" type="number" value={value}
               onChange={e => onChange(Number(e.target.value))}
               min={min} max={max} step={step}
               style={{ paddingRight: 60, fontSize: 18, fontWeight: 600 }} />
        {suffix && (
          <span className="mono muted" style={{
            position: "absolute", right: 16, top: "50%", transform: "translateY(-50%)",
            fontSize: 12,
          }}>{suffix}</span>
        )}
      </div>
    </div>
  );
}

function OptionRow({ selected, onClick, title, sub, right }) {
  return (
    <button onClick={onClick}
            style={{
              display: "flex", alignItems: "center", justifyContent: "space-between",
              padding: "14px 18px",
              border: "1px solid " + (selected ? "var(--fg)" : "var(--line)"),
              borderRadius: 14,
              background: selected ? "var(--bg-soft)" : "var(--bg)",
              textAlign: "left",
              transition: "border-color .15s, background .15s",
              width: "100%",
            }}>
      <div className="col" style={{ gap: 2 }}>
        <div style={{ fontWeight: 600, fontSize: 14, display: "flex", alignItems: "center", gap: 8 }}>
          {selected && <span className="tag-dot" style={{ background: "var(--accent)" }} />}
          {title}
        </div>
        <div className="muted" style={{ fontSize: 13 }}>{sub}</div>
      </div>
      {right}
    </button>
  );
}

Object.assign(window, { Onboarding, NumberField });
