// fc-detail.jsx — Wave 5: the detail / editor screens the rows always implied
// but never had. Shared "balanced" kit only. IIFE-scoped so helpers don't collide.
//   EditField       · edit a single settings value (name / email / password)
//   TimePicker      · iOS-style time sheet (reminder + quiet hours)
//   DatePicker      · month-grid date sheet (set / move a fight date)
//   HelpFeedback    · support index (the dead "Help & feedback" row)
//   LogEntryDetail  · view one past weigh-in + edit / delete
//   WeekDetail      · one week's daily weigh-ins + verdict
//   PastCampDetail  · an archived camp's summary
//   ArticleReader   · a Learn article, opened from the library
(function () {
  const { Phone, StatusBar, HomeIndicator, GroupedList, Row, SectionHeader, Card, Stat,
          Eyebrow, HeroButton, Toggle } = window;
  const A = 'var(--accent)';

  // bare-chevron back bar (the canonical S4 treatment) + optional trailing action
  function NavBar({ title, trailing = null }) {
    return (
      <div style={{ height: 50, padding: '0 12px', display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexShrink: 0 }}>
        <button aria-label="Back" style={{ width: 44, height: 44, marginLeft: -8, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'none', border: 'none', cursor: 'pointer' }}>
          <svg width="11" height="18" viewBox="0 0 11 18" fill="none"><path d="M9 1 L2 9 L9 17" stroke="var(--ink)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" /></svg>
        </button>
        <span style={{ fontFamily: 'var(--display)', fontSize: 13, letterSpacing: '0.14em', textTransform: 'uppercase', fontWeight: 600, color: 'var(--ink-2)', whiteSpace: 'nowrap' }}>{title}</span>
        <div style={{ minWidth: 44, display: 'flex', justifyContent: 'flex-end' }}>{trailing}</div>
      </div>
    );
  }
  const SaveAction = () => <button style={{ fontFamily: 'var(--sans)', fontSize: 16, color: A, fontWeight: 600, minHeight: 44, background: 'none', border: 'none', cursor: 'pointer' }}>Save</button>;

  // dimmed bottom-sheet shell with the iOS grabber (S6)
  function Sheet({ title, children, cta = 'Done' }) {
    return (
      <Phone styleKey="balanced" label={title}>
        <div style={{ position: 'absolute', inset: 0, background: 'rgba(15,14,11,0.55)', backdropFilter: 'blur(2px)' }} />
        <div style={{ position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column', justifyContent: 'flex-end', padding: 10 }}>
          <div style={{ background: 'var(--paper)', borderRadius: 24, overflow: 'hidden', boxShadow: '0 20px 60px rgba(0,0,0,0.4)' }}>
            <div style={{ display: 'flex', justifyContent: 'center', paddingTop: 10 }}><div style={{ width: 36, height: 5, borderRadius: 3, background: 'var(--rule-2)', opacity: 0.5 }} /></div>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '12px 20px 6px' }}>
              <span style={{ fontFamily: 'var(--display)', fontSize: 12, letterSpacing: '0.14em', textTransform: 'uppercase', fontWeight: 600, color: 'var(--ink-3)' }}>{title}</span>
              <button style={{ fontFamily: 'var(--sans)', fontSize: 16, fontWeight: 600, color: A, background: 'none', border: 'none', cursor: 'pointer', minHeight: 40 }}>{cta}</button>
            </div>
            <div style={{ padding: '4px 16px 20px' }}>{children}</div>
          </div>
        </div>
        <HomeIndicator />
      </Phone>
    );
  }

  // ── EDIT FIELD (name / email / password) ─────────────────────────────────────
  const FIELD = {
    name:     { title: 'Name', label: 'Full name', val: 'Alex Mercer', kbd: 'words', note: 'The name shown on your profile and exports.' },
    email:    { title: 'Email', label: 'Email address', val: 'alex.mercer@gmail.com', kbd: 'email', note: 'Used for sign-in, your weigh-in receipts and data exports.' },
    password: { title: 'Password', label: 'New password', val: '', ph: 'At least 8 characters', mask: true, note: 'Use 8+ characters with a mix of letters and numbers.' },
  };
  function EditField({ field = 'name' }) {
    const f = FIELD[field] || FIELD.name;
    const shown = f.mask ? '' : f.val;
    return (
      <Phone styleKey="balanced" label={`Edit · ${f.title}`}>
        <StatusBar />
        <NavBar title={f.title} trailing={<SaveAction />} />
        <div style={{ flex: 1, padding: '14px 20px', display: 'flex', flexDirection: 'column' }}>
          <Eyebrow color={A} style={{ marginBottom: 9 }}>{f.label}</Eyebrow>
          <div style={{ background: 'var(--paper)', border: '1px solid var(--rule)', borderRadius: 'var(--radius-ctl)', minHeight: 54, display: 'flex', alignItems: 'center', padding: '0 16px', fontFamily: 'var(--sans)', fontSize: 17, color: 'var(--ink)' }}>
            <span>{shown || <span style={{ color: 'var(--rule-2)' }}>{f.ph || ''}</span>}</span>
            <span style={{ display: 'inline-block', width: 2, height: 22, background: A, marginLeft: shown ? 3 : 0, borderRadius: 1 }} />
          </div>
          {field === 'password' && (
            <div style={{ marginTop: 12 }}>
              <div style={{ background: 'var(--paper)', border: '1px solid var(--rule)', borderRadius: 'var(--radius-ctl)', minHeight: 54, display: 'flex', alignItems: 'center', padding: '0 16px', fontFamily: 'var(--sans)', fontSize: 17, color: 'var(--rule-2)' }}>Confirm new password</div>
            </div>
          )}
          <div style={{ fontFamily: 'var(--sans)', fontSize: 12.5, color: 'var(--ink-3)', lineHeight: 1.5, marginTop: 11, padding: '0 2px', textWrap: 'pretty' }}>{f.note}</div>
        </div>
        <window.IOSKeyboard />
        <HomeIndicator />
      </Phone>
    );
  }

  // ── TIME PICKER ──────────────────────────────────────────────────────────────
  function Wheel({ values, sel, onSel }) {
    const win = [-2, -1, 0, 1, 2].map(o => sel + o);
    const at = (idx) => ((idx % values.length) + values.length) % values.length;
    return (
      <div style={{ position: 'relative', flex: 1, height: 180 }}>
        <div style={{ position: 'absolute', top: 72, left: 0, right: 0, height: 36, background: 'var(--paper-2)', borderRadius: 8 }} />
        <div style={{ position: 'relative', display: 'flex', flexDirection: 'column' }}>
          {win.map((idx, i) => {
            const dist = Math.abs(i - 2);
            return (
              <button key={i} onClick={() => onSel(at(idx))} style={{ height: 36, lineHeight: '36px', width: '100%', textAlign: 'center', background: 'none', border: 'none', cursor: 'pointer', fontFamily: 'var(--num)', fontSize: dist === 0 ? 22 : 19, fontWeight: dist === 0 ? 600 : 400, color: dist === 0 ? 'var(--ink)' : dist === 1 ? 'var(--ink-3)' : 'var(--rule-2)' }}>{values[at(idx)]}</button>
            );
          })}
        </div>
      </div>
    );
  }
  function TimePicker({ title = 'Morning reminder', h = 6, m = 50, ap = 0 }) {
    const [hi, setHi] = React.useState(h - 1);
    const [mi, setMi] = React.useState(m);
    const [ai, setAi] = React.useState(ap);
    const hours = Array.from({ length: 12 }, (_, i) => String(i + 1));
    const mins = Array.from({ length: 60 }, (_, i) => String(i).padStart(2, '0'));
    const aps = ['AM', 'PM'];
    return (
      <Sheet title={title}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 4, padding: '0 18px' }}>
          <Wheel values={hours} sel={hi} onSel={setHi} />
          <span style={{ fontFamily: 'var(--num)', fontSize: 22, fontWeight: 600, color: 'var(--ink)' }}>:</span>
          <Wheel values={mins} sel={mi} onSel={setMi} />
          <div style={{ flex: '0 0 auto', display: 'flex', flexDirection: 'column', gap: 8, paddingLeft: 8 }}>
            {aps.map((v, i) => <button key={v} onClick={() => setAi(i)} style={{ padding: '8px 14px', borderRadius: 8, border: 'none', cursor: 'pointer', background: ai === i ? 'var(--paper-2)' : 'transparent', fontFamily: 'var(--num)', fontSize: 18, fontWeight: ai === i ? 600 : 400, color: ai === i ? 'var(--ink)' : 'var(--rule-2)' }}>{v}</button>)}
          </div>
        </div>
        <div style={{ fontFamily: 'var(--sans)', fontSize: 12.5, color: 'var(--ink-3)', textAlign: 'center', marginTop: 8, textWrap: 'pretty' }}>One consistent fasted time gives the most accurate trend.</div>
      </Sheet>
    );
  }

  // ── DATE PICKER ──────────────────────────────────────────────────────────────
  function DatePicker({ title = 'Fight date', month = 'January 2026', startDow = 4, days = 31, sel = 11 }) {
    const [pick, setPick] = React.useState(sel);
    const cells = [...Array(startDow).fill(null), ...Array.from({ length: days }, (_, i) => i + 1)];
    return (
      <Sheet title={title}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '4px 8px 12px' }}>
          <span style={{ fontFamily: 'var(--sans)', fontSize: 16, fontWeight: 600, color: 'var(--ink)' }}>{month}</span>
          <div style={{ display: 'flex', gap: 24 }}>
            <svg width="9" height="15" viewBox="0 0 9 15" fill="none"><path d="M7 1 L1.5 7.5 L7 14" stroke="var(--ink-3)" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" /></svg>
            <svg width="9" height="15" viewBox="0 0 9 15" fill="none"><path d="M2 1 L7.5 7.5 L2 14" stroke={A} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" /></svg>
          </div>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gap: '4px 0' }}>
          {['S', 'M', 'T', 'W', 'T', 'F', 'S'].map((d, i) => <div key={i} style={{ textAlign: 'center', fontFamily: 'var(--mono)', fontSize: 10, color: 'var(--ink-3)', fontWeight: 600, paddingBottom: 4 }}>{d}</div>)}
          {cells.map((d, i) => (
            <div key={i} style={{ aspectRatio: '1', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              {d && <button onClick={() => setPick(d)} style={{ width: 34, height: 34, borderRadius: '50%', border: 'none', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'var(--sans)', fontSize: 15, fontWeight: d === pick ? 600 : 400, background: d === pick ? A : 'transparent', color: d === pick ? '#fff' : 'var(--ink)' }}>{d}</button>}
            </div>
          ))}
        </div>
        <div style={{ fontFamily: 'var(--sans)', fontSize: 12.5, color: 'var(--ink-3)', textAlign: 'center', marginTop: 12, textWrap: 'pretty' }}>We rebuild every daily target around the date you pick.</div>
      </Sheet>
    );
  }

  // ── HELP & FEEDBACK ──────────────────────────────────────────────────────────
  function HelpFeedback() {
    const faqs = ['Why does the scale read high some mornings?', 'How is my cut rate calculated?', 'Can I change my fight date mid-camp?', 'What happens if I miss weight?'];
    const contact = [['Contact support', 'Replies within a day'], ['Send feedback', 'Tell us what to build next'], ['Report a problem', 'Something broken or wrong?']];
    return (
      <Phone styleKey="balanced" label="Help & feedback">
        <StatusBar />
        <NavBar title="Help" />
        <div className="scroll" style={{ flex: 1, padding: '6px 20px 28px', display: 'flex', flexDirection: 'column', gap: 22, overflowY: 'auto' }}>
          <div>
            <div style={{ fontFamily: 'var(--sans)', fontSize: 25, fontWeight: 700, letterSpacing: '-0.02em', color: 'var(--ink)', textWrap: 'balance' }}>How can we help?</div>
            <div style={{ fontFamily: 'var(--sans)', fontSize: 14.5, lineHeight: 1.5, color: 'var(--ink-2)', marginTop: 8, textWrap: 'pretty' }}>Answers to the common questions, or reach a human.</div>
          </div>
          <div>
            <SectionHeader>Common questions</SectionHeader>
            <GroupedList>{faqs.map((q, i) => <Row key={q} label={q} onClick={() => {}} last={i === faqs.length - 1} />)}</GroupedList>
          </div>
          <div>
            <SectionHeader>Get in touch</SectionHeader>
            <GroupedList>{contact.map((c, i) => <Row key={c[0]} label={c[0]} note={c[1]} onClick={() => {}} last={i === contact.length - 1} />)}</GroupedList>
          </div>
          <div style={{ fontFamily: 'var(--mono)', fontSize: 11, letterSpacing: '0.06em', color: 'var(--ink-3)', textAlign: 'center' }}>OnWeight · v1.0.0 (build 142)</div>
        </div>
        <HomeIndicator />
      </Phone>
    );
  }

  // ── LOG-ENTRY DETAIL ─────────────────────────────────────────────────────────
  function LogEntryDetail({ weight = '76.3', day = 'Tue 24 Dec', time = '6:52 AM' }) {
    return (
      <Phone styleKey="balanced" label="Weigh-in detail">
        <StatusBar />
        <NavBar title="Weigh-in" trailing={<button style={{ fontFamily: 'var(--sans)', fontSize: 16, color: A, fontWeight: 600, minHeight: 44, background: 'none', border: 'none', cursor: 'pointer' }}>Edit</button>} />
        <div style={{ flex: 1, padding: '8px 20px 24px', display: 'flex', flexDirection: 'column' }}>
          <Eyebrow color={A}>{day} · {time}</Eyebrow>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 12, marginTop: 10 }}>
            <span style={{ fontFamily: 'var(--num)', fontWeight: 300, fontSize: 96, lineHeight: 0.85, letterSpacing: '-0.035em', color: 'var(--ink)' }}>{weight}</span>
            <span style={{ fontFamily: 'var(--mono)', fontSize: 13, letterSpacing: '0.16em', color: 'var(--ink-3)', fontWeight: 600 }}>KG</span>
          </div>
          <div style={{ marginTop: 26 }}>
            <Card pad={18} style={{ flexDirection: 'row' }}>
              <Stat label="Vs plan" value="+0.2" unit="kg" color="var(--t-amber)" i={0} />
              <Stat label="Vs day before" value="−0.3" unit="kg" color="var(--t-green)" i={1} />
              <Stat label="Phase" value="Luteal" i={1} />
            </Card>
          </div>
          <div style={{ marginTop: 18 }}>
            <SectionHeader>Note</SectionHeader>
            <GroupedList><Row label="Felt heavy, slept badly" chevron={false} onClick={() => {}} last /></GroupedList>
          </div>
          <div style={{ flex: 1 }} />
          <button style={{ width: '100%', minHeight: 52, borderRadius: 'var(--radius-ctl)', background: 'transparent', border: '1px solid color-mix(in srgb, var(--t-red) 40%, transparent)', color: 'var(--t-red)', fontFamily: 'var(--display)', fontSize: 13, letterSpacing: '0.12em', fontWeight: 600, cursor: 'pointer' }}>DELETE THIS ENTRY</button>
        </div>
        <HomeIndicator />
      </Phone>
    );
  }

  // ── WEEK DETAIL ──────────────────────────────────────────────────────────────
  function WeekDetail({ label = 'Week 4', range = '22–28 Dec' }) {
    const days = [['Mon', '77.1'], ['Tue', '76.9'], ['Wed', '77.0'], ['Thu', '76.6'], ['Fri', '76.4'], ['Sat', '76.5'], ['Sun', '76.2']];
    return (
      <Phone styleKey="balanced" label={`${label} detail`}>
        <StatusBar />
        <NavBar title={label} />
        <div className="scroll" style={{ flex: 1, padding: '6px 20px 28px', display: 'flex', flexDirection: 'column', gap: 20, overflowY: 'auto' }}>
          <div>
            <Eyebrow color={A}>{range}</Eyebrow>
            <div style={{ display: 'flex', alignItems: 'baseline', gap: 10, marginTop: 8 }}>
              <span style={{ fontFamily: 'var(--num)', fontWeight: 300, fontSize: 52, letterSpacing: '-0.03em', color: 'var(--t-green)' }}>−0.9</span>
              <span style={{ fontFamily: 'var(--mono)', fontSize: 12, letterSpacing: '0.14em', color: 'var(--ink-3)', fontWeight: 600 }}>KG THIS WEEK</span>
            </div>
            <div style={{ fontFamily: 'var(--sans)', fontSize: 14.5, color: 'var(--ink-2)', marginTop: 8, textWrap: 'pretty' }}>On pace — right around your 0.5%/wk target. 7 of 7 days logged.</div>
          </div>
          <Card pad={18} style={{ flexDirection: 'row' }}>
            <Stat label="Avg" value="76.7" unit="kg" i={0} />
            <Stat label="Logged" value="7/7" i={1} />
            <Stat label="Verdict" value="On pace" color="var(--t-green)" i={1} />
          </Card>
          <div>
            <SectionHeader>Daily</SectionHeader>
            <GroupedList>{days.map((d, i) => <Row key={d[0]} label={d[0]} value={`${d[1]} kg`} onClick={() => {}} last={i === days.length - 1} />)}</GroupedList>
          </div>
        </div>
        <HomeIndicator />
      </Phone>
    );
  }

  // ── PAST-CAMP DETAIL ─────────────────────────────────────────────────────────
  function PastCampDetail({ division = 'Lightweight', sport = 'MMA', date = '14 Sep 2025', result = 'Won' }) {
    return (
      <Phone styleKey="balanced" label="Camp detail">
        <StatusBar />
        <NavBar title="Camp" />
        <div className="scroll" style={{ flex: 1, padding: '6px 20px 28px', display: 'flex', flexDirection: 'column', gap: 20, overflowY: 'auto' }}>
          <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 12 }}>
            <div>
              <div style={{ fontFamily: 'var(--sans)', fontSize: 23, fontWeight: 700, letterSpacing: '-0.02em', color: 'var(--ink)' }}>{division}</div>
              <div style={{ fontFamily: 'var(--sans)', fontSize: 14, color: 'var(--ink-3)', marginTop: 3 }}>{sport} · {date}</div>
            </div>
            <span style={{ flexShrink: 0, fontFamily: 'var(--display)', fontSize: 11, letterSpacing: '0.12em', textTransform: 'uppercase', fontWeight: 700, color: 'var(--t-green)', border: '1px solid var(--t-green)', borderRadius: 100, padding: '4px 11px' }}>{result} · made weight</span>
          </div>
          <Card pad={18} style={{ flexDirection: 'row' }}>
            <Stat label="Start" value="80.2" unit="kg" i={0} />
            <Stat label="Weigh-in" value="74.2" unit="kg" color={A} i={1} />
            <Stat label="Cut" value="6.0" unit="kg" i={1} />
          </Card>
          <div style={{ background: 'var(--paper-2)', borderRadius: 'var(--radius)', height: 150, display: 'flex', alignItems: 'center', justifyContent: 'center', backgroundImage: 'repeating-linear-gradient(45deg, var(--rule) 0, var(--rule) 1px, transparent 1px, transparent 9px)' }}>
            <span style={{ fontFamily: 'var(--mono)', fontSize: 11, letterSpacing: '0.08em', color: 'var(--ink-3)' }}>CAMP TREND CHART</span>
          </div>
          <div>
            <SectionHeader>Summary</SectionHeader>
            <GroupedList>
              <Row label="Camp length" value="50 days" chevron={false} />
              <Row label="Avg loss / week" value="0.84 kg" chevron={false} />
              <Row label="Cut rate" value="0.52% / wk" chevron={false} />
              <Row label="Days logged" value="48/50" chevron={false} last />
            </GroupedList>
          </div>
        </div>
        <HomeIndicator />
      </Phone>
    );
  }

  // ── ARTICLE READER ───────────────────────────────────────────────────────────
  function ArticleReader({ kicker = 'Cycle & health', title = 'Why the scale lies in your luteal phase', read = '4 min read' }) {
    const paras = [
      'In the week before your period, your body holds extra water — often around half a kilo, sometimes more. It is fluid, not fat, and it clears on its own.',
      'That means a normal hormonal swing can look exactly like falling behind your cut. The scale ticks up, the trend flattens, and it is tempting to panic and slash food or water.',
      'Don\u2019t. OnWeight bakes the expected swing into your weekly targets, so a luteal-phase hold reads as "expected," not "behind." Read the trend across the cycle, never a single morning.',
      'The fix is patience: hold your plan, keep logging, and watch the water clear in the follicular phase that follows.',
    ];
    return (
      <Phone styleKey="balanced" label="Article">
        <StatusBar />
        <NavBar title="Learn" />
        <div className="scroll" style={{ flex: 1, padding: '8px 22px 30px', display: 'flex', flexDirection: 'column', overflowY: 'auto' }}>
          <Eyebrow color={A}>{kicker} · {read}</Eyebrow>
          <div style={{ fontFamily: 'var(--sans)', fontSize: 27, fontWeight: 700, letterSpacing: '-0.02em', lineHeight: 1.15, color: 'var(--ink)', marginTop: 12, textWrap: 'balance' }}>{title}</div>
          <div style={{ height: 160, marginTop: 18, borderRadius: 'var(--radius)', background: 'var(--paper-2)', backgroundImage: 'repeating-linear-gradient(45deg, var(--rule) 0, var(--rule) 1px, transparent 1px, transparent 9px)' }} />
          {paras.map((p, i) => <p key={i} style={{ fontFamily: 'var(--sans)', fontSize: 16, lineHeight: 1.6, color: 'var(--ink-2)', margin: '16px 0 0', textWrap: 'pretty' }}>{p}</p>)}
          <div style={{ marginTop: 24, paddingTop: 16, borderTop: '1px solid var(--rule)', fontFamily: 'var(--sans)', fontSize: 14, color: 'var(--ink-3)' }}>Coach Donnelly · OnWeight</div>
        </div>
        <HomeIndicator />
      </Phone>
    );
  }

  // ── PLAN EDIT FIELD ──────────────────────────────────────────────────────────
  // Everything on Edit Plan is editable, and every field spells out HOW the change
  // rebuilds the plan (before → after) before you apply it. One pattern, five fields.
  const START = 78.4, WEEKS = 8, LIMIT = 74.4, BASE_WK = (START - LIMIT) / WEEKS;
  const f1 = (n) => Number(n).toFixed(1), f2 = (n) => Number(n).toFixed(2);
  const PLAN_FIELDS = {
    division: {
      title: 'Division', intro: 'Your division sets the limit you must hit on the scale.', cur: 74.4,
      opts: [['Flyweight', '61.2 kg', 61.2], ['Lightweight', '74.4 kg · current', 74.4], ['Welterweight', '77.1 kg', 77.1]],
      impact: (v) => ({
        note: v < LIMIT ? 'A lower limit is a bigger cut — every daily target drops and your weekly pace steepens.' : v > LIMIT ? 'A higher limit eases the cut — daily targets relax and you carry more into fight week.' : 'No change to your limit.',
        rows: [['Scale limit', f1(LIMIT) + ' kg', f1(v) + ' kg'], ['Total cut', f1(START - LIMIT) + ' kg', f1(START - v) + ' kg'], ['Weekly pace', f2(BASE_WK) + ' kg', f2((START - v) / WEEKS) + ' kg']],
      }),
    },
    date: {
      title: 'Weigh-in date', intro: 'Moving the date changes your runway, so the pace recalculates.', cur: 8,
      opts: [['Sat 28 Dec', '6 weeks out', 6], ['Sat 11 Jan', '8 weeks · current', 8], ['Sat 25 Jan', '10 weeks out', 10]],
      impact: (w) => { const wk = (START - LIMIT) / w, pct = wk / START * 100; return {
        note: w < WEEKS ? 'A nearer date compresses the cut — faster weekly loss, less margin for a bad week.' : w > WEEKS ? 'A later date adds runway — gentler weekly loss and more buffer.' : 'No change to your runway.',
        rows: [['Runway', WEEKS + ' wk', w + ' wk'], ['Weekly pace', f2(BASE_WK) + ' kg', f2(wk) + ' kg'], ['Safety', '0.64% / wk', f2(pct) + '% / wk' + (pct > 1 ? '  ⚠' : '')]],
      }; },
    },
    rate: {
      title: 'Cut rate', intro: 'How fast you lose each week — the dial between speed and power.', cur: 0.5,
      opts: [['Conservative', '0.25% / wk', 0.25], ['Optimal', '0.5% / wk · current', 0.5], ['Aggressive', '0.75% / wk', 0.75], ['Maximum', '1.0% / wk', 1.0]],
      impact: (r) => { const wk = START * r / 100, wks = (START - LIMIT) / wk; return {
        note: r >= 1 ? 'At the ceiling — power and recovery start to suffer. A last resort.' : r >= 0.75 ? 'Faster than ideal; fuel hard and watch the trend closely.' : r <= 0.25 ? 'Very gentle — needs a long runway to make weight.' : 'The sweet spot: makes weight while protecting power.',
        rows: [['Weekly loss', f2(START * 0.5 / 100) + ' kg', f2(wk) + ' kg'], ['Weeks to limit', String(WEEKS), wks.toFixed(1)], ['Power risk', 'Low', r >= 1 ? 'High' : r >= 0.75 ? 'Moderate' : 'Low']],
      }; },
    },
    gear: {
      title: 'Gear allowance', intro: 'What you wear on the scale counts toward the limit.', cur: 0.5,
      opts: [['No gear', '+0.0 kg', 0], ['Shorts + gloves', '+0.5 kg · current', 0.5], ['Full gi', '+1.0 kg', 1.0]],
      impact: (g) => ({
        note: 'More gear on the scale means a little less true bodyweight to cut in camp.',
        rows: [['Scale limit', f1(LIMIT) + ' kg', f1(LIMIT) + ' kg'], ['True target', f1(LIMIT - 0.5) + ' kg', f1(LIMIT - g) + ' kg'], ['True cut', f1(START - (LIMIT - 0.5)) + ' kg', f1(START - (LIMIT - g)) + ' kg']],
      }),
    },
    rehyd: {
      title: 'Rehydration cap', intro: 'A re-weigh limit caps how much water you can cut fight week.', cur: 1,
      opts: [['No re-weigh', '0% cap', 0], ['1% cap', 'Common · current', 1], ['2% cap', 'Lenient', 2]],
      impact: (c) => ({
        note: c === 0 ? 'No cap means more fight-week water room, so the camp cut can be gentler.' : 'A tighter cap means more of the cut must be real weight, made in camp.',
        rows: [['Fight-week water', f1(START * 1 / 100) + ' kg', f1(START * c / 100) + ' kg'], ['Camp (true) cut', f1((START - LIMIT) - START * 1 / 100) + ' kg', f1((START - LIMIT) - START * c / 100) + ' kg']],
      }),
    },
  };
  function ImpactRow({ k, a, b, i }) {
    return (
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, minHeight: 46, borderTop: i ? '1px solid var(--rule)' : 'none' }}>
        <span style={{ flex: 1, fontFamily: 'var(--sans)', fontSize: 14, fontWeight: 500, color: 'var(--ink)' }}>{k}</span>
        <span style={{ fontFamily: 'var(--sans)', fontSize: 13.5, color: 'var(--ink-3)' }}>{a}</span>
        {b !== undefined && <><svg width="16" height="11" viewBox="0 0 18 12" fill="none" style={{ flexShrink: 0 }}><path d="M1 6 H16 M12 2 L16 6 L12 10" stroke="var(--rule-2)" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/></svg>
        <span style={{ fontFamily: 'var(--sans)', fontSize: 13.5, fontWeight: 600, color: A }}>{b}</span></>}
      </div>
    );
  }
  function PlanEditField({ field = 'division' }) {
    const F = PLAN_FIELDS[field] || PLAN_FIELDS.division;
    const [sel, setSel] = React.useState(F.cur);
    const changed = sel !== F.cur;
    const imp = F.impact(sel);
    return (
      <Phone styleKey="balanced" label={`Edit · ${F.title}`}>
        <StatusBar />
        <NavBar title={F.title} />
        <div className="scroll" style={{ flex: 1, padding: '8px 20px 18px', display: 'flex', flexDirection: 'column', overflowY: 'auto' }}>
          <div style={{ fontFamily: 'var(--sans)', fontSize: 14.5, lineHeight: 1.5, color: 'var(--ink-2)', textWrap: 'pretty' }}>{F.intro}</div>
          <div style={{ marginTop: 16 }}>
            <GroupedList>
              {F.opts.map((o, i) => <Row key={o[0]} label={o[0]} chevron={false} last={i === F.opts.length - 1} onClick={() => setSel(o[2])}
                control={<span style={{ display: 'flex', alignItems: 'center', gap: 10 }}><span style={{ fontFamily: 'var(--sans)', fontSize: 13.5, color: 'var(--ink-3)', whiteSpace: 'nowrap' }}>{o[1]}</span><span style={{ width: 21, height: 21, borderRadius: '50%', flexShrink: 0, border: sel === o[2] ? 'none' : '1.6px solid var(--rule-2)', background: sel === o[2] ? A : 'transparent', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>{sel === o[2] && <svg width="10" height="8" viewBox="0 0 11 9" fill="none"><path d="M1 4.5 L4 7.5 L10 1" stroke="#fff" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/></svg>}</span></span>} />)}
            </GroupedList>
          </div>
          <div style={{ marginTop: 20, background: changed ? 'var(--accent-soft)' : 'var(--paper-2)', borderRadius: 'var(--radius)', border: changed ? '1px solid color-mix(in srgb, var(--accent) 26%, transparent)' : '1px solid var(--rule)', padding: '15px 17px' }}>
            <div style={{ fontFamily: 'var(--display)', fontSize: 10.5, letterSpacing: '0.14em', textTransform: 'uppercase', color: A, fontWeight: 700 }}>How this changes your plan</div>
            <div style={{ fontFamily: 'var(--sans)', fontSize: 13.5, lineHeight: 1.5, color: 'var(--ink-2)', marginTop: 8, textWrap: 'pretty' }}>{imp.note}</div>
            <div style={{ marginTop: 10 }}>{imp.rows.map((r, i) => <ImpactRow key={r[0]} k={r[0]} a={r[1]} b={changed ? r[2] : undefined} i={i} />)}</div>
          </div>
        </div>
        <div style={{ padding: '0 20px 8px' }}>
          <button style={{ width: '100%', minHeight: 54, borderRadius: 'var(--radius-ctl)', border: 'none', cursor: 'pointer', background: changed ? 'var(--ink)' : 'var(--rule)', color: changed ? 'var(--paper)' : 'var(--ink-3)', fontFamily: 'var(--display)', fontSize: 14, letterSpacing: '0.13em', fontWeight: 600 }}>{changed ? 'APPLY & REBUILD PLAN' : 'NO CHANGES YET'}</button>
        </div>
        <HomeIndicator />
      </Phone>
    );
  }

  // ── CYCLE PHASE HELP (D4 target for "This doesn't match how I feel") ─────────
  const _PHASES = [
    ['Menstrual', 'Days 1–5', 'Cramps, low energy, bleeding. Water clings the first day or two, then drops.', 'var(--accent)'],
    ['Follicular', 'Days 6–13', 'Feeling light, energy back. Water sits lowest — the scale reads closest to true.', 'var(--t-green)'],
    ['Ovulation', 'Days 14–16', 'Mid-cycle. Water low to neutral, scale still honest.', 'var(--t-green)'],
    ['Luteal', 'Days 17–28', 'Bloating, breast tenderness, cravings. You hold ~+0.5 kg of water — already in your plan.', 'var(--accent)'],
  ];
  function CyclePhaseHelp() {
    return (
      <Phone styleKey="balanced" label="Phase signs">
        <StatusBar />
        <NavBar title="Phase signs" />
        <div className="scroll" style={{ flex: 1, padding: '8px 20px 24px', display: 'flex', flexDirection: 'column', overflowY: 'auto' }}>
          <div style={{ fontFamily: 'var(--sans)', fontSize: 22, fontWeight: 700, letterSpacing: '-0.02em', color: 'var(--ink)', textWrap: 'balance' }}>Where are you, really?</div>
          <div style={{ fontFamily: 'var(--sans)', fontSize: 14.5, lineHeight: 1.5, color: 'var(--ink-2)', marginTop: 8, textWrap: 'pretty' }}>Cycles drift, so the calendar can be off. Match what your body’s doing — or log your period to re-anchor the dates exactly.</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginTop: 18 }}>
            {_PHASES.map((p) => (
              <div key={p[0]} style={{ background: 'var(--paper)', borderRadius: 'var(--radius)', boxShadow: 'var(--card-shadow)', border: 'var(--card-border)', padding: '14px 16px' }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 9 }}>
                  <span style={{ width: 9, height: 9, borderRadius: '50%', background: p[3], flexShrink: 0 }} />
                  <span style={{ fontFamily: 'var(--sans)', fontSize: 16, fontWeight: 700, color: 'var(--ink)' }}>{p[0]}</span>
                  <span style={{ marginLeft: 'auto', fontFamily: 'var(--mono)', fontSize: 10, letterSpacing: '0.06em', color: 'var(--ink-3)', fontWeight: 600 }}>{p[1]}</span>
                </div>
                <div style={{ fontFamily: 'var(--sans)', fontSize: 13.5, lineHeight: 1.5, color: 'var(--ink-2)', marginTop: 7, textWrap: 'pretty' }}>{p[2]}</div>
              </div>
            ))}
          </div>
          <div style={{ marginTop: 18, background: 'var(--accent-soft)', borderRadius: 'var(--radius)', border: '1px solid color-mix(in srgb, var(--accent) 26%, transparent)', padding: '16px 17px' }}>
            <div style={{ fontFamily: 'var(--sans)', fontSize: 15.5, fontWeight: 600, color: 'var(--ink)' }}>Re-anchor from your period</div>
            <div style={{ fontFamily: 'var(--sans)', fontSize: 13, color: 'var(--ink-2)', lineHeight: 1.5, marginTop: 5, textWrap: 'pretty' }}>A logged bleed is the one sure signal — it re-fixes the calendar more accurately than any guess.</div>
            <button style={{ width: '100%', marginTop: 13, minHeight: 50, borderRadius: 'var(--radius-ctl)', border: 'none', cursor: 'pointer', background: 'var(--ink)', color: 'var(--paper)', fontFamily: 'var(--display)', fontSize: 13, letterSpacing: '0.12em', fontWeight: 600 }}>LOG PERIOD START</button>
          </div>
        </div>
        <HomeIndicator />
      </Phone>
    );
  }

  // ── CYCLE LENGTH PICKER (D5) ─────────────────────────────────────────────────
  function CycleLengthPicker() {
    const days = Array.from({ length: 20 }, (_, i) => String(i + 21)); // 21–40
    const [i, setI] = React.useState(7); // 28 days
    return (
      <Sheet title="Cycle length">
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8, padding: '0 18px' }}>
          <Wheel values={days} sel={i} onSel={setI} />
          <span style={{ fontFamily: 'var(--mono)', fontSize: 13, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--ink-3)', fontWeight: 600 }}>days</span>
        </div>
        <div style={{ fontFamily: 'var(--sans)', fontSize: 12.5, color: 'var(--ink-3)', textAlign: 'center', marginTop: 8, textWrap: 'pretty' }}>Most cycles run 24–32 days. We refine this from your logged periods over time.</div>
      </Sheet>
    );
  }

  // ── PAYMENT METHOD (D3) ──────────────────────────────────────────────────────
  function PaymentMethod() {
    return (
      <Phone styleKey="balanced" label="Payment method">
        <StatusBar />
        <NavBar title="Payment" trailing={<SaveAction />} />
        <div className="scroll" style={{ flex: 1, padding: '8px 20px 24px', display: 'flex', flexDirection: 'column', overflowY: 'auto' }}>
          {/* card hero */}
          <div style={{ background: 'var(--ink)', color: 'var(--paper)', borderRadius: 'var(--radius)', padding: '20px', position: 'relative', overflow: 'hidden' }}>
            <div style={{ fontFamily: 'var(--display)', fontSize: 10.5, letterSpacing: '0.16em', textTransform: 'uppercase', color: 'rgba(246,244,239,0.6)', fontWeight: 600 }}>Card on file</div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 18 }}>
              <span style={{ fontFamily: 'var(--num)', fontSize: 22, letterSpacing: '0.1em' }}>•••• •••• •••• 4242</span>
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginTop: 16, fontFamily: 'var(--mono)', fontSize: 11, letterSpacing: '0.08em', color: 'rgba(246,244,239,0.7)' }}>
              <span>ALEX MERCER</span><span>EXP 08 / 27</span>
            </div>
          </div>
          <div style={{ marginTop: 20 }}>
            <SectionHeader>Pay with</SectionHeader>
            <GroupedList>
              <Row label="Visa ending 4242" value="Default" chevron={false} control={<span style={{ width: 21, height: 21, borderRadius: '50%', background: A, display: 'flex', alignItems: 'center', justifyContent: 'center' }}><svg width="10" height="8" viewBox="0 0 11 9" fill="none"><path d="M1 4.5 L4 7.5 L10 1" stroke="#fff" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/></svg></span>} />
              <Row label="Apple Pay" onClick={() => {}} />
              <Row label="Add a card" valueColor="var(--accent)" onClick={() => {}} last />
            </GroupedList>
          </div>
          <div style={{ fontFamily: 'var(--sans)', fontSize: 12.5, color: 'var(--ink-3)', lineHeight: 1.5, marginTop: 12, padding: '0 2px', textWrap: 'pretty' }}>Used for your OnWeight subscription. Changing it here updates the card on your next renewal and on receipts.</div>
        </div>
        <HomeIndicator />
      </Phone>
    );
  }

  // ── BILLING HISTORY (D3) ─────────────────────────────────────────────────────
  function BillingHistory() {
    const rows = [
      ['14 Sep 2025', '$59.00', 'Annual · paid'], ['14 Sep 2024', '$59.00', 'Annual · paid'],
      ['11 Aug 2024', '$8.00', 'Monthly · paid'], ['11 Jul 2024', '$8.00', 'Monthly · paid'],
      ['04 Jul 2024', '$0.00', '7-day trial'],
    ];
    return (
      <Phone styleKey="balanced" label="Billing history">
        <StatusBar />
        <NavBar title="Billing" />
        <div className="scroll" style={{ flex: 1, padding: '6px 20px 24px', display: 'flex', flexDirection: 'column', gap: 18, overflowY: 'auto' }}>
          <div>
            <div style={{ fontFamily: 'var(--sans)', fontSize: 23, fontWeight: 700, letterSpacing: '-0.02em', color: 'var(--ink)' }}>Billing history</div>
            <div style={{ fontFamily: 'var(--sans)', fontSize: 14, color: 'var(--ink-3)', marginTop: 4 }}>Every charge since you joined. Tap one for its receipt.</div>
          </div>
          <GroupedList>
            {rows.map((r, i) => (
              <Row key={i} last={i === rows.length - 1} onClick={() => {}} label={r[0]} value={r[1]}
                note={r[2]} />
            ))}
          </GroupedList>
          <div style={{ fontFamily: 'var(--mono)', fontSize: 11, letterSpacing: '0.06em', color: 'var(--ink-3)', textAlign: 'center' }}>Total paid · $134.00</div>
        </div>
        <HomeIndicator />
      </Phone>
    );
  }

  // ── SHARPEN ACCURACY INPUTS (D1 leftover) ────────────────────────────────────
  // Data-collection screens behind Sharpen's "Add detail" rows. Each tightens the
  // projection rather than re-speccing the plan, so it shows the accuracy gain.
  const SHARPEN_FIELDS = {
    training: { title: 'Training load', q: 'How hard is your training block right now?', acc: '+8%',
      opts: [['Light', '1–3 sessions / wk'], ['Moderate', '4–6 sessions / wk'], ['Heavy', '2-a-days · pro camp']],
      note: 'Sets how much your daily burn supports the cut, so targets aren’t over-aggressive.' },
    refeed: { title: 'Refeed days', q: 'Do you run planned refeed / higher-carb days?', acc: '+7%',
      opts: [['None', ''], ['Weekly', 'One day / wk'], ['Twice weekly', 'Two days / wk']],
      note: 'Refeeds show up as planned scale bumps, so a normal jump never reads as falling behind.' },
    watercut: { title: 'Water-cut capacity', q: 'How much have you cut by water manipulation before?', acc: '+12%',
      opts: [['Never / unsure', ''], ['~2% of bodyweight', 'Mild'], ['~4%', 'Moderate'], ['5%+', 'Aggressive · risky']],
      note: 'Calibrates the fight-week water buffer so the camp cut isn’t over- or under-built.' },
    history: { title: 'Past cut history', q: 'How did your last weight cut go?', acc: '+10%',
      opts: [['Made it comfortably', ''], ['Made it, but tough', ''], ['Missed weight', '']],
      note: 'Tells the model how your body responds, so the pace is tuned to you, not the average.' },
    sleep: { title: 'Sleep & stress', q: 'How are your sleep and stress through camp?', acc: '+5%',
      opts: [['Good', '7–9 h · low stress'], ['Average', ''], ['Poor', 'Short sleep · high stress']],
      note: 'Poor recovery raises injury and stall risk; we ease the plan and flag it if it slips.' },
  };
  function SharpenInput({ field = 'watercut' }) {
    const F = SHARPEN_FIELDS[field] || SHARPEN_FIELDS.watercut;
    const [sel, setSel] = React.useState(0);
    return (
      <Phone styleKey="balanced" label={`Sharpen · ${F.title}`}>
        <StatusBar />
        <NavBar title={F.title} trailing={<SaveAction />} />
        <div className="scroll" style={{ flex: 1, padding: '8px 20px 18px', display: 'flex', flexDirection: 'column', overflowY: 'auto' }}>
          <div style={{ fontFamily: 'var(--sans)', fontSize: 20, fontWeight: 700, letterSpacing: '-0.01em', lineHeight: 1.25, color: 'var(--ink)', textWrap: 'balance' }}>{F.q}</div>
          <div style={{ marginTop: 16 }}>
            <GroupedList>
              {F.opts.map((o, i) => <Row key={o[0]} label={o[0]} chevron={false} last={i === F.opts.length - 1} onClick={() => setSel(i)}
                control={<span style={{ display: 'flex', alignItems: 'center', gap: 10 }}>{o[1] && <span style={{ fontFamily: 'var(--sans)', fontSize: 13.5, color: 'var(--ink-3)', whiteSpace: 'nowrap' }}>{o[1]}</span>}<span style={{ width: 21, height: 21, borderRadius: '50%', flexShrink: 0, border: sel === i ? 'none' : '1.6px solid var(--rule-2)', background: sel === i ? A : 'transparent', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>{sel === i && <svg width="10" height="8" viewBox="0 0 11 9" fill="none"><path d="M1 4.5 L4 7.5 L10 1" stroke="#fff" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/></svg>}</span></span>} />)}
            </GroupedList>
          </div>
          <div style={{ marginTop: 20, background: 'var(--paper-2)', borderRadius: 'var(--radius)', border: '1px solid var(--rule)', padding: '15px 17px' }}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <span style={{ fontFamily: 'var(--display)', fontSize: 10.5, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--ink-3)', fontWeight: 700 }}>Why this helps</span>
              <span style={{ fontFamily: 'var(--mono)', fontSize: 11, letterSpacing: '0.06em', color: 'var(--t-green)', fontWeight: 700 }}>PLAN ACCURACY {F.acc}</span>
            </div>
            <div style={{ fontFamily: 'var(--sans)', fontSize: 13.5, lineHeight: 1.5, color: 'var(--ink-2)', marginTop: 8, textWrap: 'pretty' }}>{F.note}</div>
          </div>
        </div>
        <div style={{ padding: '0 20px 8px' }}>
          <button style={{ width: '100%', minHeight: 54, borderRadius: 'var(--radius-ctl)', border: 'none', cursor: 'pointer', background: 'var(--ink)', color: 'var(--paper)', fontFamily: 'var(--display)', fontSize: 14, letterSpacing: '0.13em', fontWeight: 600 }}>SAVE & TIGHTEN PLAN</button>
        </div>
        <HomeIndicator />
      </Phone>
    );
  }

  Object.assign(window, { EditField, TimePicker, DatePicker, HelpFeedback, LogEntryDetail, WeekDetail, PastCampDetail, ArticleReader, PlanEditField, CyclePhaseHelp, CycleLengthPicker, PaymentMethod, BillingHistory, SharpenInput });
})();
