// screen-profile.jsx — Profile + Onboarding + Re-goal

function ScreenProfile({ user, onChangePersona, onOpenOnboarding, onOpenRegoal }) {
  const profile = MOCK.PROFILES[user];
  const plan = MOCK.PLANS[user];

  const age = new Date(window.TODAY + 'T00:00:00').getFullYear() - new Date(profile.dob).getFullYear();

  return (
    <div className="scr">
      <div style={{ padding: '24px 22px 8px' }}>
        <Eyebrow>Profile</Eyebrow>
        <div className="h-display" style={{ marginTop: 4 }}>
          {profile.first_name} <em>{profile.last_name}</em>.
        </div>
        <div className="t-body" style={{ marginTop: 6 }}>
          {age}, {(profile.height_cm / 30.48).toFixed(1).split('.').map((p,i) => i===0 ? p + "'" : p + '"').join('')} · {(profile.weight_kg * 2.205).toFixed(0)}lb · {GOAL_LABELS[profile.goals.primary]}
        </div>
      </div>

      {/* 12-week target */}
      {profile.goals.twelve_week_target && (
        <div style={{ padding: '14px 16px 0' }}>
          <Card>
            <Eyebrow style={{ marginBottom: 10 }}>12-week target</Eyebrow>
            <div style={{
              fontFamily: 'var(--serif)', fontSize: 22, lineHeight: 1.2, color: 'var(--ink)',
              fontVariationSettings: "'opsz' 28", letterSpacing: '-0.02em',
            }}>
              {profile.goals.twelve_week_target}
            </div>
          </Card>
        </div>
      )}

      {/* Goals */}
      <div style={{ padding: '14px 16px 0' }}>
        <Eyebrow style={{ marginBottom: 8, paddingLeft: 4 }}>Goals</Eyebrow>
        <Card flush>
          <Row left="Primary" right={GOAL_LABELS[profile.goals.primary]} />
          {profile.goals.secondary && <Row left="Secondary" right={GOAL_LABELS[profile.goals.secondary]} />}
          <Row left="Coaching tone" right={profile.preferences.coaching_tone?.replace('_', ' ')} last />
        </Card>
      </div>

      {/* Training */}
      <div style={{ padding: '14px 16px 0' }}>
        <Eyebrow style={{ marginBottom: 8, paddingLeft: 4 }}>Training</Eyebrow>
        <Card flush>
          <Row left="Days per week" right={`${profile.schedule.days_per_week} sessions`} />
          <Row left="Session length" right={`${profile.schedule.session_minutes} min`} />
          <Row left="Environment" right={profile.environment.primary.replace('_', ' ')} />
          <Row left="Experience" right={`${profile.training_history.years}y · ${profile.training_history.level}`} last />
        </Card>
      </div>

      {/* Health blocks */}
      {profile.female_health && (
        <div style={{ padding: '14px 16px 0' }}>
          <Eyebrow style={{ marginBottom: 8, paddingLeft: 4 }}>Cycle</Eyebrow>
          <Card flush>
            <Row left="Status" right={profile.female_health.cycle_status} />
            <Row left="Avg length" right={`${profile.female_health.average_cycle_length} days`} />
            <Row left="Last period" right={new Date(profile.female_health.last_period_start).toLocaleDateString('en-US', { month: 'short', day: 'numeric' })} last />
          </Card>
        </div>
      )}
      {profile.male_health && (
        <div style={{ padding: '14px 16px 0' }}>
          <Eyebrow style={{ marginBottom: 8, paddingLeft: 4 }}>Vitality</Eyebrow>
          <Card flush>
            <Row left="Morning erections" right={profile.male_health.morning_erections_frequency?.replace('_',' ')} />
            <Row left="Libido" right={`${profile.male_health.libido_1_10}/10`} last />
          </Card>
        </div>
      )}

      {/* Devices */}
      <div style={{ padding: '14px 16px 0' }}>
        <Eyebrow style={{ marginBottom: 8, paddingLeft: 4 }}>Connected</Eyebrow>
        <Card flush>
          <Row left="Wearable" right={profile.lifestyle.wearable} />
          <Row left="Reminders" right={profile.preferences.reminder_frequency} />
          <Row left="Privacy" right={profile.preferences.privacy_mode?.replace('_',' ')} last />
        </Card>
      </div>

      {/* Actions */}
      <div style={{ padding: '20px 16px 120px' }}>
        <div className="col gap-8">
          <button onClick={onOpenRegoal} className="btn btn-ghost">
            <Icon name="target" size={16} stroke={2} /> Re-goal next mesocycle
          </button>
          <button onClick={onChangePersona} className="btn btn-ghost">
            <Icon name="user" size={16} stroke={2} /> Switch profile
          </button>
          <button onClick={onOpenOnboarding} className="btn btn-soft">
            <Icon name="plus" size={16} stroke={2} /> New profile
          </button>
        </div>
      </div>
    </div>
  );
}

// ── Onboarding modal flow ────────────────────────────────────────────────

const ONBOARDING_STEPS = [
  { id: 'name',        title: 'What should we call you?',          eyebrow: 'Step 1 of 6' },
  { id: 'body',        title: 'Tell us about your body.',           eyebrow: 'Step 2 of 6' },
  { id: 'goal',        title: 'What are we training for?',          eyebrow: 'Step 3 of 6' },
  { id: 'schedule',    title: 'How many days, how long?',           eyebrow: 'Step 4 of 6' },
  { id: 'environment', title: 'Where does the work happen?',        eyebrow: 'Step 5 of 6' },
  { id: 'voice',       title: 'How should we talk to you?',         eyebrow: 'Step 6 of 6' },
];

function OnboardingFlow({ onClose, onComplete }) {
  const [step, setStep] = React.useState(0);
  const [submitting, setSubmitting] = React.useState(false);
  const [error, setError] = React.useState(null);
  const [a, setA] = React.useState({
    first_name: '', last_name: '',
    gender: 'female',
    height_ft: 5, height_in: 6, weight: 145, weight_unit: 'lb', bodyfat_pct: '',
    goals: { primary: '', secondary: '', twelve_week_target: '' },
    environment: { primary: '', equipment: [] },
    schedule: { days_per_week: 4, session_minutes: 45 },
    preferences: { coaching_tone: '' },
    dob: '',
    female_health: { cycle_status: 'regular', track_cycle_in_app: true, last_period_start: '', average_cycle_length: 28 },
  });

  const stepCfg = ONBOARDING_STEPS[step];
  const isLast = step === ONBOARDING_STEPS.length - 1;

  // Mock "what's left" — based on the local state
  const missing = computeMissing(a);
  const ready = missing.length === 0;

  const finalize = async () => {
    setSubmitting(true); setError(null);
    try {
      const res = await window.api.onboardingFinalize(a);
      if (window.bootstrapLive) await window.bootstrapLive(window.TODAY);
      if (onComplete && res && res.profile) onComplete(res.profile.user_id);
      onClose();
    } catch (e) { setError((e && e.message) || 'Could not build your plan'); setSubmitting(false); }
  };

  return (
    <div style={{ position: 'absolute', inset: 0, background: 'var(--bg)', zIndex: 100, display: 'flex', flexDirection: 'column' }}>
      {/* status bar takes top space (rendered by frame); padding to clear it */}
      <div style={{ padding: '64px 16px 14px', borderBottom: '0.5px solid var(--line)' }}>
        <div className="row between" style={{ alignItems: 'center' }}>
          <button onClick={step === 0 ? onClose : () => setStep(step - 1)}
            style={{
              appearance: 'none', background: 'transparent', border: 0, cursor: 'pointer',
              padding: 0, fontFamily: 'var(--sans)', fontSize: 14, color: 'var(--ink-2)',
            }}>
            {step === 0 ? '✕' : '←'} {step === 0 ? 'Close' : 'Back'}
          </button>
          <div className="t-mono" style={{ fontSize: 11, color: 'var(--ink-3)' }}>
            {step + 1} / {ONBOARDING_STEPS.length}
          </div>
        </div>
        {/* progress */}
        <div style={{ marginTop: 14, height: 2, background: 'rgba(28,26,20,0.08)', borderRadius: 999 }}>
          <div style={{ height: '100%', width: `${((step + 1) / ONBOARDING_STEPS.length) * 100}%`, background: 'var(--ink)', borderRadius: 999, transition: 'width .25s' }} />
        </div>
      </div>

      <div style={{ flex: 1, overflowY: 'auto', padding: '24px 22px 16px' }}>
        <Eyebrow>{stepCfg.eyebrow}</Eyebrow>
        <div className="h-display" style={{ marginTop: 8, marginBottom: 18, fontSize: 30 }}>
          {stepCfg.title}
        </div>

        <OnboardingStep stepId={stepCfg.id} a={a} setA={setA} />
      </div>

      {/* What's-left + CTA */}
      <div style={{ padding: '14px 16px 36px', borderTop: '0.5px solid var(--line)', background: 'var(--card)' }}>
        {(missing.length > 0 || isLast) && (
          <div className="mb-12">
            <Eyebrow style={{ marginBottom: 8 }}>What's left{missing.length ? ' · ' + missing.length : ''}</Eyebrow>
            {ready
              ? <div className="t-body" style={{ color: 'var(--green)' }}>Nothing — you're ready to build your first plan.</div>
              : <div className="col gap-6" style={{ maxHeight: 140, overflowY: 'auto' }}>
                  {missing.map(m => (
                    <button key={m.label} onClick={() => setStep(m.step)} className="row between"
                      style={{ appearance: 'none', cursor: 'pointer', background: 'transparent', border: 0, padding: '2px 0', width: '100%', alignItems: 'center', textAlign: 'left' }}>
                      <span className="t-small row gap-6" style={{ alignItems: 'center', color: 'var(--ink-2)' }}>
                        <span style={{ width: 4, height: 4, background: 'var(--amber)', borderRadius: 999 }} />
                        {m.label}
                      </span>
                      <Icon name="chevron" size={14} stroke={2} color="var(--ink-3)" />
                    </button>
                  ))}
                </div>}
          </div>
        )}
        {error && <div className="t-small" style={{ color: 'var(--red)', marginBottom: 10 }}>{error}</div>}
        <button className="btn"
          onClick={() => isLast ? finalize() : setStep(step + 1)}
          disabled={(isLast && !ready) || submitting}
          style={{ opacity: ((isLast && !ready) || submitting) ? 0.5 : 1 }}>
          {submitting ? 'Building your plan…' : (isLast ? (ready ? 'Build my plan →' : 'Fill the gaps first') : 'Continue')}
        </button>
      </div>
    </div>
  );
}

function computeMissing(a) {
  const m = [];
  if (!a.first_name) m.push({ label: 'First name', step: 0 });
  if (!a.last_name) m.push({ label: 'Last name', step: 0 });
  if (!a.dob) m.push({ label: 'Date of birth', step: 1 });
  if (a.gender === 'female') {
    if (!a.female_health.cycle_status) m.push({ label: 'Cycle status', step: 1 });
    if (a.female_health.track_cycle_in_app && a.female_health.cycle_status === 'regular' && !a.female_health.last_period_start) m.push({ label: 'Last period start', step: 1 });
  }
  if (!a.goals.primary) m.push({ label: 'Primary goal', step: 2 });
  if (!a.schedule.days_per_week) m.push({ label: 'Days per week', step: 3 });
  if (!a.environment.primary) m.push({ label: 'Training environment', step: 4 });
  return m;
}

function OnboardingStep({ stepId, a, setA }) {
  const set = (path, val) => {
    const next = JSON.parse(JSON.stringify(a));
    const keys = path.split('.');
    let o = next;
    for (let i = 0; i < keys.length - 1; i++) o = o[keys[i]];
    o[keys[keys.length - 1]] = val;
    setA(next);
  };

  if (stepId === 'name') return (
    <div className="col gap-12">
      <Field label="First name">
        <TextInput value={a.first_name} onChange={(v) => set('first_name', v)} placeholder="Alex" />
      </Field>
      <Field label="Last name">
        <TextInput value={a.last_name} onChange={(v) => set('last_name', v)} placeholder="Rivera" />
      </Field>
      <Field label="Gender">
        <PillGroup value={a.gender} options={[['female','Female'],['male','Male']]} onChange={(v) => set('gender', v)} />
      </Field>
    </div>
  );

  if (stepId === 'body') return (
    <div className="col gap-14">
      <Field label="Height">
        <div className="row gap-8">
          <div className="row gap-4 grow" style={{
            background: 'var(--card)', border: '0.5px solid var(--line)', borderRadius: 12,
            padding: '12px 14px', alignItems: 'baseline',
          }}>
            <input type="number" value={a.height_ft} onChange={(e) => set('height_ft', Number(e.target.value))}
              className="t-num"
              style={{ width: 44, fontSize: 20, border: 0, outline: 'none', background: 'transparent', textAlign: 'right' }} />
            <span className="t-small">ft</span>
            <input type="number" value={a.height_in} onChange={(e) => set('height_in', Number(e.target.value))}
              className="t-num"
              style={{ width: 44, fontSize: 20, border: 0, outline: 'none', background: 'transparent', textAlign: 'right', marginLeft: 12 }} />
            <span className="t-small">in</span>
          </div>
        </div>
      </Field>
      <Field label="Weight">
        <div className="row gap-8" style={{
          background: 'var(--card)', border: '0.5px solid var(--line)', borderRadius: 12,
          padding: '12px 14px', alignItems: 'baseline',
        }}>
          <input type="number" value={a.weight} onChange={(e) => set('weight', Number(e.target.value))}
            className="t-num"
            style={{ width: 80, fontSize: 20, border: 0, outline: 'none', background: 'transparent', textAlign: 'right' }} />
          <PillGroup value={a.weight_unit} options={[['lb','lb'],['kg','kg']]} onChange={(v) => set('weight_unit', v)} compact />
        </div>
      </Field>
      <Field label="Bodyfat %" optional>
        <TextInput type="number" value={a.bodyfat_pct} onChange={(v) => set('bodyfat_pct', v)} placeholder="optional" />
      </Field>
      <Field label="Date of birth">
        <TextInput type="date" value={a.dob} onChange={(v) => set('dob', v)} placeholder="YYYY-MM-DD" />
      </Field>
      {a.gender === 'female' && (
        <Field label="Cycle status">
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
            {[['regular','Regular'],['irregular','Irregular'],['hormonal_bc','On birth control'],['perimenopausal','Perimenopausal'],['postmenopausal','Postmenopausal']].map(([k, l]) => (
              <button key={k} onClick={() => set('female_health.cycle_status', k)}
                className={a.female_health.cycle_status === k ? 'chip chip-on' : 'chip'}
                style={{ border: 0, cursor: 'pointer' }}>{l}</button>
            ))}
          </div>
        </Field>
      )}
      {a.gender === 'female' && a.female_health.cycle_status === 'regular' && (
        <Field label="Last period start">
          <TextInput type="date" value={a.female_health.last_period_start} onChange={(v) => set('female_health.last_period_start', v)} placeholder="YYYY-MM-DD" />
        </Field>
      )}
      {a.gender === 'female' && a.female_health.cycle_status === 'regular' && (
        <Field label="Average cycle length">
          <Stepper value={a.female_health.average_cycle_length} min={21} max={40} onChange={(v) => set('female_health.average_cycle_length', v)} unit="days" />
        </Field>
      )}
    </div>
  );

  if (stepId === 'goal') {
    const goals = ['hypertrophy','strength','fat_loss','recomp','performance','longevity','sexual_health','energy'];
    return (
      <div className="col gap-12">
        <Field label="Primary goal">
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
            {goals.map(g => (
              <button key={g} onClick={() => set('goals.primary', g)}
                className={a.goals.primary === g ? 'chip chip-on' : 'chip'}
                style={{ border: 0, cursor: 'pointer' }}>
                {GOAL_LABELS[g]}
              </button>
            ))}
          </div>
        </Field>
        <Field label="12-week target" optional>
          <textarea value={a.goals.twelve_week_target}
            onChange={(e) => set('goals.twelve_week_target', e.target.value)}
            placeholder="e.g. add 4kg lean mass, hit bench BW × 1.25"
            rows={3}
            style={{
              width: '100%', resize: 'none',
              border: '0.5px solid var(--line)', borderRadius: 12,
              padding: '12px 14px',
              fontFamily: 'var(--serif)', fontSize: 16, lineHeight: 1.35,
              background: 'var(--card)', outline: 'none',
            }}/>
        </Field>
      </div>
    );
  }

  if (stepId === 'schedule') return (
    <div className="col gap-14">
      <Field label="Days per week">
        <Stepper value={a.schedule.days_per_week} min={2} max={6} onChange={(v) => set('schedule.days_per_week', v)} unit="days" />
      </Field>
      <Field label="Session length">
        <PillGroup value={a.schedule.session_minutes}
          options={[[30,'30'],[45,'45'],[60,'60'],[75,'75'],[90,'90']]}
          onChange={(v) => set('schedule.session_minutes', v)} />
      </Field>
    </div>
  );

  if (stepId === 'environment') {
    const envs = [
      ['commercial_gym','Commercial gym'],
      ['home_gym','Home gym'],
      ['hybrid','Hybrid'],
      ['travel','Travel'],
      ['outdoor','Outdoor'],
    ];
    return (
      <div className="col gap-12">
        <Field label="Where do you train?">
          <div className="col gap-6">
            {envs.map(([k, l]) => (
              <button key={k} onClick={() => set('environment.primary', k)}
                style={{
                  appearance: 'none', cursor: 'pointer',
                  background: a.environment.primary === k ? 'var(--ink)' : 'var(--card)',
                  color: a.environment.primary === k ? 'var(--bg)' : 'var(--ink)',
                  border: '0.5px solid var(--line)', borderRadius: 14,
                  padding: '14px 16px',
                  fontFamily: 'var(--serif)', fontSize: 17, textAlign: 'left',
                }}>{l}</button>
            ))}
          </div>
        </Field>
      </div>
    );
  }

  if (stepId === 'voice') {
    const tones = [
      ['drill_sergeant', 'Drill sergeant', 'Direct, sharp, no shoulder pats.'],
      ['firm_warm',      'Firm and warm',  'Honest but kind. Most people land here.'],
      ['chill_mentor',   'Chill mentor',   'Patient. Curious. Long view.'],
    ];
    return (
      <div className="col gap-10">
        <Eyebrow>Coaching tone</Eyebrow>
        {tones.map(([k, l, sub]) => (
          <button key={k} onClick={() => set('preferences.coaching_tone', k)}
            style={{
              appearance: 'none', cursor: 'pointer',
              background: a.preferences.coaching_tone === k ? 'var(--ink)' : 'var(--card)',
              color: a.preferences.coaching_tone === k ? 'var(--bg)' : 'var(--ink)',
              border: '0.5px solid var(--line)', borderRadius: 16,
              padding: '14px 16px', textAlign: 'left',
            }}>
            <div style={{ fontFamily: 'var(--serif)', fontSize: 18, marginBottom: 4 }}>{l}</div>
            <div style={{ fontSize: 13, opacity: 0.7 }}>{sub}</div>
          </button>
        ))}
      </div>
    );
  }
}

function Field({ label, optional, children }) {
  return (
    <div className="col gap-6">
      <div className="row between baseline">
        <Eyebrow>{label}</Eyebrow>
        {optional && <span className="t-small">optional</span>}
      </div>
      {children}
    </div>
  );
}

function TextInput({ value, onChange, placeholder, type = 'text' }) {
  return (
    <input type={type} value={value || ''} onChange={(e) => onChange(e.target.value)}
      placeholder={placeholder}
      style={{
        width: '100%', border: '0.5px solid var(--line)',
        background: 'var(--card)', borderRadius: 12,
        padding: '12px 14px',
        fontFamily: 'var(--serif)', fontSize: 18,
        outline: 'none', color: 'var(--ink)',
      }}/>
  );
}

function PillGroup({ value, options, onChange, compact }) {
  return (
    <div style={{
      display: 'inline-flex', padding: 3, gap: 0,
      background: 'rgba(28,26,20,0.06)', borderRadius: 999,
    }}>
      {options.map(([k, l]) => (
        <button key={k} onClick={() => onChange(k)}
          style={{
            appearance: 'none', cursor: 'pointer',
            background: value === k ? 'var(--card)' : 'transparent',
            color: value === k ? 'var(--ink)' : 'var(--ink-3)',
            border: 0, borderRadius: 999,
            padding: compact ? '6px 12px' : '8px 16px',
            fontFamily: 'var(--sans)', fontSize: compact ? 12 : 13.5, fontWeight: 500,
            boxShadow: value === k ? '0 1px 3px rgba(0,0,0,0.08)' : 'none',
          }}>{l}</button>
      ))}
    </div>
  );
}

function Stepper({ value, min, max, onChange, unit }) {
  return (
    <div className="row gap-12" style={{
      background: 'var(--card)', border: '0.5px solid var(--line)', borderRadius: 14,
      padding: '8px 12px', alignItems: 'center', width: 'fit-content',
    }}>
      <button onClick={() => onChange(Math.max(min, value - 1))}
        style={{ appearance: 'none', cursor: 'pointer', width: 32, height: 32, borderRadius: 999, background: 'rgba(28,26,20,0.06)', border: 0, fontSize: 18, color: 'var(--ink)' }}>−</button>
      <div className="t-num" style={{ fontSize: 26, minWidth: 32, textAlign: 'center' }}>{value}</div>
      <button onClick={() => onChange(Math.min(max, value + 1))}
        style={{ appearance: 'none', cursor: 'pointer', width: 32, height: 32, borderRadius: 999, background: 'var(--ink)', color: 'var(--bg)', border: 0, fontSize: 18 }}>+</button>
      {unit && <span className="t-small" style={{ marginLeft: 6 }}>{unit}</span>}
    </div>
  );
}

// ── Re-goal sheet ────────────────────────────────────────────────────────

function RegoalSheet({ user, onClose }) {
  const profile = MOCK.PROFILES[user];
  const [pivot, setPivot] = React.useState(profile.goals.primary);
  const [stage, setStage] = React.useState('pick'); // pick | preview

  const goals = ['hypertrophy','strength','fat_loss','recomp','performance','longevity'];

  if (stage === 'preview') {
    return (
      <RegoalPreview user={user} pivot={pivot} onClose={onClose} onBack={() => setStage('pick')} />
    );
  }

  return (
    <div style={{ position: 'absolute', inset: 0, background: 'rgba(0,0,0,0.4)', zIndex: 99, display: 'flex', flexDirection: 'column', justifyContent: 'flex-end' }} onClick={onClose}>
      <div onClick={(e) => e.stopPropagation()}
        style={{
          background: 'var(--bg)', borderTopLeftRadius: 28, borderTopRightRadius: 28,
          padding: '14px 22px 36px', maxHeight: '85%', overflowY: 'auto',
        }}>
        <div style={{ width: 36, height: 4, background: 'rgba(28,26,20,0.18)', borderRadius: 999, margin: '0 auto 16px' }} />
        <Eyebrow>Re-goal</Eyebrow>
        <div className="h-title" style={{ marginTop: 4, marginBottom: 8 }}>
          Pick the next <em>4 weeks</em>.
        </div>
        <div className="t-body mb-16">
          Tell us where to point. We'll rebuild the mesocycle around it and recommend a retest.
        </div>
        <div className="col gap-6 mb-16">
          {goals.map(g => (
            <button key={g} onClick={() => setPivot(g)}
              style={{
                appearance: 'none', cursor: 'pointer',
                background: pivot === g ? 'var(--ink)' : 'var(--card)',
                color: pivot === g ? 'var(--bg)' : 'var(--ink)',
                border: '0.5px solid var(--line)', borderRadius: 14,
                padding: '14px 16px',
                fontFamily: 'var(--serif)', fontSize: 17, textAlign: 'left',
                display: 'flex', justifyContent: 'space-between', alignItems: 'center',
              }}>
              <span>{GOAL_LABELS[g]}</span>
              {g === profile.goals.primary && <span className="t-mono" style={{ fontSize: 10, opacity: 0.6, letterSpacing: '0.06em', textTransform: 'uppercase' }}>current</span>}
            </button>
          ))}
        </div>
        <button className="btn" onClick={() => setStage('preview')}>
          Preview new plan <Icon name="arrow" size={16} stroke={2} />
        </button>
      </div>
    </div>
  );
}

function RegoalPreview({ user, pivot, onClose, onBack }) {
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState(null);
  const commit = async () => {
    setBusy(true); setErr(null);
    try {
      const cur = ((window.MOCK.PROFILES[user] || {}).goals || {}).primary;
      const np = await window.api.regoal(user, null, pivot !== cur ? pivot : null);
      if (window.MOCK && window.MOCK.PLANS) window.MOCK.PLANS[user] = window.__adaptPlan ? window.__adaptPlan(np) : np;
      onClose();
    } catch (e) { setErr((e && e.message) || 'Could not re-goal'); setBusy(false); }
  };
  // Build a mock new mesocycle
  const newPlan = {
    primary_goal: pivot,
    mesocycle_index: MOCK.PLANS[user].mesocycle_index + 1,
    start_date: '2026-06-15',
    next_re_goal_date: '2026-07-13',
    retest: pivot === 'strength' ? 'Test 5RM on bench, squat, deadlift in week 4.'
           : pivot === 'fat_loss' ? 'Re-measure waist + photos in week 4.'
           : pivot === 'hypertrophy' ? 'Re-measure arm + chest in week 4. Photos.'
           : 'Re-test target movement in week 4 and re-evaluate.',
  };

  return (
    <div style={{ position: 'absolute', inset: 0, background: 'var(--bg)', zIndex: 100, display: 'flex', flexDirection: 'column' }}>
      <div style={{ padding: '64px 16px 14px', borderBottom: '0.5px solid var(--line)' }}>
        <div className="row between">
          <button onClick={onBack} style={{ appearance: 'none', background: 'transparent', border: 0, cursor: 'pointer', padding: 0, color: 'var(--ink-2)', fontSize: 14 }}>← Back</button>
          <button onClick={onClose} style={{ appearance: 'none', background: 'transparent', border: 0, cursor: 'pointer', padding: 0, color: 'var(--ink-3)', fontSize: 14 }}>Cancel</button>
        </div>
      </div>
      <div style={{ flex: 1, overflowY: 'auto', padding: '24px 22px' }}>
        <Eyebrow>New mesocycle preview</Eyebrow>
        <div className="h-display" style={{ marginTop: 8, marginBottom: 12, fontSize: 32 }}>
          The <em>{GOAL_LABELS[pivot]}</em> block.
        </div>
        <div className="t-body mb-20">
          Starts <strong style={{ color: 'var(--ink)' }}>{new Date(newPlan.start_date).toLocaleDateString('en-US', { weekday: 'long', month: 'long', day: 'numeric' })}</strong>. Four weeks: intro → build → peak → deload. Next re-goal: {new Date(newPlan.next_re_goal_date).toLocaleDateString('en-US', { month: 'short', day: 'numeric' })}.
        </div>

        <Card style={{ background: 'var(--bg-2)', border: 0 }} className="mb-16">
          <div className="row gap-10 mb-8" style={{ alignItems: 'center' }}>
            <Icon name="target" size={16} stroke={2} color="var(--ink-2)" />
            <Eyebrow>Recommended retest</Eyebrow>
          </div>
          <div style={{ fontFamily: 'var(--serif)', fontSize: 17, lineHeight: 1.3, color: 'var(--ink)' }}>
            "{newPlan.retest}"
          </div>
        </Card>

        <Eyebrow style={{ marginBottom: 10 }}>Week structure</Eyebrow>
        <Card flush>
          {[
            { w: 1, label: 'Intro',  copy: 'Movement quality, get the patterns clean.' },
            { w: 2, label: 'Build',  copy: 'Volume climbs. Anchors get heavier.' },
            { w: 3, label: 'Peak',   copy: 'Highest intensity. Top sets on the line.' },
            { w: 4, label: 'Deload', copy: 'Half-volume, low intensity. Retest end of week.' },
          ].map((w, i, arr) => (
            <div key={i} style={{
              padding: '14px 18px',
              borderBottom: i === arr.length - 1 ? '0' : '0.5px solid var(--line-2)',
              display: 'flex', alignItems: 'flex-start', gap: 14,
            }}>
              <div className="t-num" style={{ fontSize: 22, color: 'var(--ink-3)', minWidth: 28 }}>0{w.w}</div>
              <div className="col gap-2">
                <div style={{ fontFamily: 'var(--serif)', fontSize: 17, color: 'var(--ink)' }}>{w.label}</div>
                <div className="t-small">{w.copy}</div>
              </div>
            </div>
          ))}
        </Card>
      </div>
      <div style={{ padding: '14px 16px 36px', borderTop: '0.5px solid var(--line)', background: 'var(--card)' }}>
        {err && <div className="t-small" style={{ color: 'var(--red)', marginBottom: 10 }}>{err}</div>}
        <button className="btn" onClick={commit} disabled={busy} style={{ opacity: busy ? 0.6 : 1 }}>
          <Icon name="check" size={16} stroke={2.2} /> {busy ? 'Locking in\u2026' : 'Lock in this block'}
        </button>
      </div>
    </div>
  );
}

Object.assign(window, { ScreenProfile, OnboardingFlow, RegoalSheet });
