// fc-lifecycle.jsx, Weigh-in day and its outcomes, plus the post-fight result.
// Uses the SHARED kit only (Card, SectionHeader, Stat, StepList, LargeTitle) so
// every screen matches the dashboards. Made and Missed are ONE template: identical
// hero + diff + divider + headline; only the module below swaps.

const lcLimit = FC.goalWeight;   // 74.4, the hard line
const lcWorking = 73.4;          // cycle-adjusted working target

// shared hero numeral block (same scale as Today / Fight Week)
function BigWeight({ value, sub = null, subColor = 'var(--ink-3)' }) {
  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 12, marginTop: 6 }}>
        <span style={{ fontFamily: 'var(--num)', fontWeight: 300, fontSize: 112, lineHeight: 0.8, letterSpacing: '-0.035em', color: 'var(--ink)' }}>{value}</span>
        <span style={{ fontFamily: 'var(--mono)', fontSize: 13, letterSpacing: '0.16em', color: 'var(--ink-3)', fontWeight: 600 }}>KG</span>
      </div>
      {sub && <div style={{ fontFamily: 'var(--mono)', fontSize: 11.5, letterSpacing: '0.14em', textTransform: 'uppercase', color: subColor, fontWeight: 700, marginTop: 14 }}>{sub}</div>}
    </div>
  );
}

// ════════════════════════════════════════════════════════════════════════════
// WEIGH-IN DAY, one job: get the official number on the record.
// ════════════════════════════════════════════════════════════════════════════
function WeighInDay({ styleKey = 'balanced' }) {
  // B4 — the official number is now actually enterable, reusing the same keypad
  // pattern as Log Weight. The typed value is published to window.__weighInWeight
  // so "RECORD WEIGH-IN" can route to the Made / Missed outcome from the number.
  const [val, setVal] = React.useState(() => window.__weighInWeight || '');
  const dirty = React.useRef(!!window.__weighInWeight);
  const onKey = (k) => setVal((v) => {
    if (k === 'del') { dirty.current = true; return v.length ? v.slice(0, -1) : ''; }
    if (!dirty.current) { dirty.current = true; v = ''; }
    if (k === '.') return v.includes('.') ? v : (v === '' ? '0.' : v + '.');
    if (/\.\d$/.test(v)) return v;                          // one decimal place
    if (v === '0') return k;
    if (v.replace('.', '').length >= 4) return v;
    return v + k;
  });
  React.useEffect(() => { window.__weighInWeight = val; }, [val]);
  const entered = dirty.current && val !== '';
  const numColor = !entered ? 'var(--rule-2)' : (parseFloat(val) <= lcLimit ? 'var(--ink)' : 'var(--t-red)');
  return (
    <Phone styleKey={styleKey} label="Weigh-in Day">
      <StatusBar />
      <LargeTitle eyebrow="Weigh-in day · 9:00 AM" title="The scale" trailing={<GearButton />} eyebrowColor="var(--accent)" />
      <div style={{ flex: 1, padding: '2px 20px 24px', display: 'flex', flexDirection: 'column' }}>

        <div style={{ fontFamily: 'var(--sans)', fontSize: 19, fontWeight: 600, lineHeight: 1.3, color: 'var(--ink)', margin: '2px 0 18px', textWrap: 'balance' }}>
          Weigh-in day. This is the one that counts.
        </div>

        <SectionHeader>Official weigh-in</SectionHeader>
        <Card pad="20px 20px 18px">
          <div style={{ fontFamily: 'var(--display)', fontSize: 10.5, letterSpacing: '0.15em', textTransform: 'uppercase', color: 'var(--ink-3)', fontWeight: 600, textAlign: 'center' }}>{entered ? 'Your official weight' : 'Enter your official weight'}</div>
          <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'center', gap: 8, margin: '12px 0 2px' }}>
            <span style={{ fontFamily: 'var(--num)', fontWeight: 300, fontSize: 72, letterSpacing: '-0.03em', color: numColor }}>{entered ? val : '00.0'}{entered && <span style={{ display: 'inline-block', width: 2, height: '0.72em', background: 'var(--accent)', marginLeft: 5, borderRadius: 1, transform: 'translateY(0.04em)' }} />}</span>
            <span style={{ fontFamily: 'var(--mono)', fontSize: 15, letterSpacing: '0.12em', color: entered ? 'var(--ink-3)' : 'var(--rule-2)', fontWeight: 600 }}>KG</span>
          </div>
        </Card>

        <div style={{ display: 'flex', justifyContent: 'center', gap: 18, margin: '14px 0 2px', fontFamily: 'var(--mono)', fontSize: 11, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--ink-3)', fontWeight: 600 }}>
          <span>Working {lcWorking.toFixed(1)}</span>
          <span style={{ color: 'var(--rule-2)' }}>·</span>
          <span style={{ color: 'var(--accent)' }}>Limit {lcLimit.toFixed(1)} kg</span>
        </div>

        <div style={{ flex: 1, minHeight: 10 }} />
        <window.IOSNumberPad onKey={onKey} />
        <button style={{ width: '100%', marginTop: 14, background: entered ? 'var(--ink)' : 'var(--rule)', color: entered ? 'var(--paper)' : 'var(--ink-3)', border: 'none', borderRadius: 'var(--radius-ctl)', minHeight: 56, fontFamily: 'var(--display)', fontSize: 14, letterSpacing: '0.14em', fontWeight: 600 }}>RECORD WEIGH-IN</button>

      </div>
      <TabBar active="home" /><HomeIndicator />
    </Phone>
  );
}

// ════════════════════════════════════════════════════════════════════════════
// OUTCOME, one template for both results. The number drives it. Made switches on
// the rebuild plan; Missed switches it off and holds space. Red shows once, on the
// fact. Missed is acknowledgement only: no actions, no next step.
// ════════════════════════════════════════════════════════════════════════════
function OutcomeScreen({ styleKey = 'balanced', made = true }) {
  const official = made ? 74.2 : 75.0;
  const diff = +Math.abs(official - lcLimit).toFixed(1);
  const diffLine = made ? `${diff.toFixed(1)} kg under the limit` : `${diff.toFixed(1)} kg over the limit`;
  const headline = made
    ? 'Cut’s done. Rebuild now so you walk in strong tomorrow.'
    : `${diff.toFixed(1)} over after a full camp. That’s brutal, and it happens to the best in the sport.`;
  const rebuild = [
    { label: 'NOW', title: 'Fluids + electrolytes', detail: '1.5 L with sodium over 2 hrs', state: 'now' },
    { label: '+2 HR', title: 'First real meal', detail: 'Easy carbs, lean protein, low fibre', state: 'todo' },
    { label: 'TONIGHT', title: 'Top up + sleep', detail: 'Keep sipping, full night', state: 'todo' },
    { label: 'SAT 8PM', title: 'Fight', detail: 'Walk in rebuilt', state: 'goal' },
  ];
  return (
    <Phone styleKey={styleKey} label={made ? 'Made Weight' : 'Missed Weight'}>
      <StatusBar />
      <LargeTitle eyebrow="Official weigh-in" title={made ? 'You made weight.' : 'You missed weight.'} trailing={<GearButton />} eyebrowColor={made ? 'var(--t-green)' : 'var(--ink-3)'} />
      <div style={{ flex: 1, padding: '6px 20px 28px', display: 'flex', flexDirection: 'column' }}>

        {made && window.OWMark && (
          <div style={{ display: 'flex', justifyContent: 'center', margin: '2px 0 8px' }}>
            <window.OWMark sport={(window.FC && window.FC.sport) || 'Boxing'} size={104} dark={false} accent="var(--red)" once />
          </div>
        )}

        {/* shared: hero numeral + diff fact */}
        <BigWeight value={official.toFixed(1)} sub={diffLine} subColor={made ? 'var(--t-green)' : 'var(--t-red)'} />

        <div style={{ height: 1, background: 'var(--rule)', margin: '24px 0 20px' }} />

        {/* shared: one-line headline */}
        <div style={{ fontFamily: 'var(--sans)', fontSize: 18, fontWeight: 600, lineHeight: 1.35, color: 'var(--ink)', textWrap: 'pretty' }}>{headline}</div>

        {/* swapped module */}
        {made ? (
          <div style={{ marginTop: 26 }}>
            <SectionHeader>Rebuild · next 36 hours</SectionHeader>
            <Card pad="6px 18px"><StepList steps={rebuild} /></Card>
          </div>
        ) : (
          <>
            <div style={{ fontFamily: 'var(--sans)', fontSize: 15, lineHeight: 1.6, color: 'var(--ink-2)', marginTop: 14, textWrap: 'pretty' }}>Rehydrate, eat, and rest tonight. Be kind to yourself.</div>
            <div style={{ flex: 1 }} />
            <div style={{ fontFamily: 'var(--display)', fontSize: 11, letterSpacing: '0.16em', textTransform: 'uppercase', color: 'var(--ink-3)', fontWeight: 600, textAlign: 'center', paddingTop: 24 }}>Your camp is still here when you&rsquo;re ready</div>
          </>
        )}

      </div>
      <TabBar active="home" /><HomeIndicator />
    </Phone>
  );
}

// backward-compatible thin wrappers
function WeighInMade({ styleKey = 'balanced' }) { return <OutcomeScreen styleKey={styleKey} made={true} />; }
function WeighInMissed({ styleKey = 'balanced' }) { return <OutcomeScreen styleKey={styleKey} made={false} />; }

// ════════════════════════════════════════════════════════════════════════════
// LOG WEIGHT, the entry behind "Log weight" / "Record weigh-in": big readout,
// editable date, number pad. Closes the daily loop (entry → result).
// ════════════════════════════════════════════════════════════════════════════
function LogWeight({ styleKey = 'balanced' }) {
  const [val, setVal] = React.useState(() => window.__loggedWeight || '75.2');
  const dirty = React.useRef(false);
  const onKey = (k) => setVal((v) => {
    if (k === 'del') { dirty.current = true; return v.length > 1 ? v.slice(0, -1) : '0'; }
    if (!dirty.current) { dirty.current = true; v = ''; }   // first keypress clears the seed value
    if (k === '.') return v.includes('.') ? v : (v === '' ? '0.' : v + '.');
    if (/\.\d$/.test(v)) return v;                          // cap at one decimal place
    if (v === '0') return k;
    if (v.replace('.', '').length >= 4) return v;           // keep it sane (e.g. 175.2)
    return v + k;
  });
  React.useEffect(() => { window.__loggedWeight = val; }, [val]);
  return (
    <Phone styleKey={styleKey} label="Log Weight">
      <StatusBar />
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '8px 18px 14px' }}>
        <button style={{ fontFamily: 'var(--sans)', fontSize: 16, color: 'var(--ink-3)', fontWeight: 500, minHeight: 44 }}>Cancel</button>
        <span style={{ fontFamily: 'var(--sans)', fontSize: 16, fontWeight: 600, color: 'var(--ink)' }}>Log weight</span>
        <button style={{ fontFamily: 'var(--sans)', fontSize: 16, color: 'var(--accent)', fontWeight: 600, minHeight: 44 }}>Save</button>
      </div>
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column' }}>
        <div style={{ textAlign: 'center', padding: '26px 20px 24px' }}>
          <div style={{ fontFamily: 'var(--display)', fontSize: 11, letterSpacing: '0.16em', textTransform: 'uppercase', color: 'var(--ink-3)', fontWeight: 600 }}>Today&rsquo;s weight</div>
          <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'center', gap: 10, marginTop: 14 }}>
            <span style={{ fontFamily: 'var(--num)', fontWeight: 300, fontSize: 76, letterSpacing: '-0.03em', color: 'var(--ink)' }}>{val}<span style={{ display: 'inline-block', width: 2, height: '0.78em', background: 'var(--accent)', marginLeft: 5, borderRadius: 1, transform: 'translateY(0.04em)' }} /></span>
            <span style={{ fontFamily: 'var(--mono)', fontSize: 15, letterSpacing: '0.12em', color: 'var(--ink-3)', fontWeight: 600 }}>KG</span>
          </div>
        </div>
        <div style={{ padding: '0 20px' }}>
          <GroupedList>
            <Row label="Date" value="Today, 31 Dec" last />
          </GroupedList>
        </div>
        <div style={{ flex: 1, minHeight: 16 }} />
        <window.IOSNumberPad onKey={onKey} />
      </div>
      <HomeIndicator />
    </Phone>
  );
}

// ════════════════════════════════════════════════════════════════════════════
// FIGHT RESULT, a separate, later beat. Logged after the bout; feeds the archive.
// ════════════════════════════════════════════════════════════════════════════
function FightResult({ styleKey = 'balanced' }) {
  const [sel, setSel] = React.useState('Won');
  const radio = (on) => (
    <span style={{ width: 22, height: 22, borderRadius: '50%', border: on ? 'none' : '1.6px solid var(--rule-2)', background: on ? 'var(--accent)' : 'transparent', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
      {on && <svg width="11" height="9" 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>
  );
  return (
    <Phone styleKey={styleKey} label="Fight Result">
      <StatusBar />
      <LargeTitle eyebrow="After the fight" title="How did it go?" trailing={<GearButton />} eyebrowColor="var(--accent)" />
      <div style={{ flex: 1, padding: '2px 20px 28px', display: 'flex', flexDirection: 'column' }}>
        <div style={{ fontFamily: 'var(--sans)', fontSize: 15, lineHeight: 1.55, color: 'var(--ink-2)', margin: '4px 4px 22px', textWrap: 'pretty' }}>
          Log the result to close out your camp. It makes the next one smarter.
        </div>
        <SectionHeader>Result</SectionHeader>
        <GroupedList>
          <Row label="Won" chevron={false} control={radio(sel === 'Won')} onClick={() => setSel('Won')} />
          <Row label="Lost" chevron={false} control={radio(sel === 'Lost')} onClick={() => setSel('Lost')} />
          <Row label="No contest" chevron={false} control={radio(sel === 'No contest')} onClick={() => setSel('No contest')} last />
        </GroupedList>
        <div style={{ flex: 1 }} />
        <button style={{ width: '100%', background: 'var(--ink)', color: 'var(--paper)', border: 'none', borderRadius: 'var(--radius-ctl)', minHeight: 56, fontFamily: 'var(--display)', fontSize: 14, letterSpacing: '0.14em', fontWeight: 600 }}>CLOSE CAMP</button>
      </div>
      <TabBar active="home" /><HomeIndicator />
    </Phone>
  );
}

Object.assign(window, { WeighInDay, OutcomeScreen, WeighInMade, WeighInMissed, FightResult, BigWeight, LogWeight });
