// fc-screens-a.jsx, Dashboard (Today), Add-Weight Result, Progress · v3
// Themed via window.Phone. Dashboard leads with today's weight + the log action
// as the dominant element; interpretation sits just below.

const { FC, TONE, SHADOW, computePace, Phone, Eyebrow, Num, Hairline, ToneBadge,
        HeroMotif, Card, SectionHeader, Stat, StatusBar, HomeIndicator, LargeTitle, CompactNav,
        NavAction, GearButton, TabBar, PrimaryButton, TextButton, GroupedList, Row,
        ProgressBar, FCChart, FCHealthCard, getStyle, _dayDate, _fmtDay } = window;

const Body = ({ children, gap = 16, pad = '4px 20px 26px' }) => (
  <div style={{ flex: 1, padding: pad, display: 'flex', flexDirection: 'column', gap }}>{children}</div>
);

// small kg-stat used in the verdict card
function MiniStat({ k, v, c = 'var(--ink)', i = 0 }) {
  return (
    <div style={{ flex: 1, paddingLeft: i ? 16 : 0, borderLeft: i ? '1px solid var(--rule)' : 'none' }}>
      <Eyebrow color="var(--ink-3)" style={{ fontSize: 10 }}>{k}</Eyebrow>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 3, marginTop: 7 }}>
        <Num size={22} color={c}>{v}</Num>
        <span style={{ fontFamily: 'var(--mono)', fontSize: 10, color: 'var(--ink-3)', fontWeight: 600 }}>kg</span>
      </div>
    </div>
  );
}

// ── DASHBOARD ────────────────────────────────────────────────────────────────
function Dashboard({ styleKey = 'hig', paceKey = 'onTrack' }) {
  const st = getStyle(styleKey);
  const p = computePace(paceKey);
  const tone = TONE[p.tone];
  const today = p.hist[p.hist.length - 1][1];
  const dPrev = today - p.hist[p.hist.length - 2][1];
  const down = dPrev <= 0;
  const dColor = down ? (st.heroInverted ? '#a9d18e' : 'var(--t-green)') : (st.heroInverted ? 'rgba(246,244,239,0.7)' : 'var(--ink-3)');
  const inv = st.heroInverted;
  const muted = inv ? 'rgba(246,244,239,0.6)' : 'var(--ink-3)';

  const weekTarget = 0.45, weekLoss = Math.abs(p.weeklyVel);

  return (
    <Phone styleKey={styleKey} label="Dashboard">
      <StatusBar />
      <LargeTitle eyebrow={`OnWeight · Round ${FC.todayDay}/${FC.campDays}`} title={`Hi, ${FC.firstName}`} trailing={<GearButton />} />
      <Body>
        {/* WEIGHT HERO, the dominant element: today's weight + log action */}
        <Card pad={22} inverted={inv}>
          <HeroMotif motif={st.motif} />
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <Eyebrow color={muted}>Fasted · 06:18</Eyebrow>
            <ToneBadge tone={p.tone} dark={inv}>{p.badge}</ToneBadge>
          </div>
          <div style={{ display: 'flex', alignItems: 'flex-end', gap: 14, marginTop: 14 }}>
            <Num size={96} color={inv ? 'var(--paper)' : 'var(--ink)'} style={{ lineHeight: 0.82 }}>{today.toFixed(1)}</Num>
            <div style={{ paddingBottom: 8 }}>
              <div style={{ fontFamily: 'var(--mono)', fontSize: 15, color: muted, fontWeight: 600, letterSpacing: '0.04em' }}>kg</div>
              <div style={{ display: 'inline-flex', alignItems: 'center', gap: 4, marginTop: 9, fontFamily: 'var(--sans)', fontSize: 13, color: dColor, fontWeight: 600, fontFeatureSettings: '"tnum"' }}>
                <span>{down ? '\u2193' : '\u2191'}</span>{Math.abs(dPrev).toFixed(1)} kg
                <span style={{ color: muted, fontWeight: 500 }}>today</span>
              </div>
            </div>
          </div>
          <div style={{ marginTop: 20 }}><PrimaryButton label="Log today's weight" plus big style={inv ? { background: 'var(--paper)', color: 'var(--ink)' } : {}} /></div>
        </Card>

        {/* VERDICT, interpretation, secondary to the weight */}
        <Card pad={18}>
          <div style={{ display: 'flex', gap: 12, alignItems: 'stretch' }}>
            <div style={{ width: 3, borderRadius: 2, background: tone.ink, flexShrink: 0 }} />
            <div style={{ flex: 1 }}>
              <div style={{ fontFamily: 'var(--sans)', fontSize: 17, fontWeight: 600, lineHeight: 1.25, color: 'var(--ink)', textWrap: 'balance' }}>{p.state.verdict}</div>
              <div style={{ fontFamily: 'var(--sans)', fontSize: 13.5, lineHeight: 1.5, color: 'var(--ink-2)', marginTop: 7, textWrap: 'pretty' }}>{p.state.line}</div>
            </div>
          </div>
          <div style={{ height: 1, background: 'var(--rule)', margin: '15px 0 14px' }} />
          <div style={{ display: 'flex' }}>
            <MiniStat k="Fight-day limit" v={FC.goalWeight.toFixed(1)} c="var(--accent)" />
            <MiniStat k="Projected" v={p.projected.toFixed(1)} c={p.gap <= 0.15 ? 'var(--ink)' : tone.ink} i={1} />
            <MiniStat k={p.daysOut + ' days'} v={Math.abs(p.toGo).toFixed(1)} i={1} />
          </div>
        </Card>

        {/* TREND */}
        <div>
          <SectionHeader trailing={<TextButton>Details</TextButton>}>Your trend</SectionHeader>
          <Card pad={'16px 10px 12px'} style={{ alignItems: 'center' }}>
            <div style={{ fontFamily: 'var(--sans)', fontSize: 14.5, color: 'var(--ink-2)', lineHeight: 1.5, alignSelf: 'stretch', padding: '0 8px 4px', textWrap: 'pretty' }}>{p.state.chartCaption}</div>
            <FCChart paceKey={paceKey} width={335} height={236} />
          </Card>
        </div>

        {/* THIS WEEK */}
        <div>
          <SectionHeader>This week</SectionHeader>
          <Card pad={18}>
            <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between' }}>
              <span style={{ fontFamily: 'var(--sans)', fontSize: 16, fontWeight: 600, color: 'var(--ink)' }}>{p.state.weekLine}</span>
              <span style={{ fontFamily: 'var(--sans)', fontSize: 13, color: 'var(--ink-3)', fontFeatureSettings: '"tnum"' }}><strong style={{ color: tone.ink, fontWeight: 600 }}>{weekLoss.toFixed(1)}</strong> / {weekTarget.toFixed(2)} kg</span>
            </div>
            <div style={{ marginTop: 13 }}><ProgressBar pct={weekLoss / weekTarget} tone={p.tone} /></div>
            <div style={{ fontFamily: 'var(--sans)', fontSize: 12.5, color: 'var(--ink-3)', lineHeight: 1.5, marginTop: 12, textWrap: 'pretty' }}>Target eased this week for your <strong style={{ color: 'var(--ink-2)', fontWeight: 600 }}>luteal phase</strong>. Expect a small water hold.</div>
          </Card>
        </div>

        {/* COACH */}
        <div>
          <SectionHeader>From the corner</SectionHeader>
          <Card pad={18} tint="var(--paper-2)" style={{ boxShadow: 'none', border: '1px solid var(--rule)' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              <window.CoachMark sport={(window.FC && window.FC.sport) || 'boxing'} size={30} />
              <div>
                <div style={{ fontFamily: 'var(--sans)', fontSize: 14, fontWeight: 600, color: 'var(--ink)' }}>Coach Donnelly</div>
                <div style={{ fontFamily: 'var(--mono)', fontSize: 10, color: 'var(--ink-3)', letterSpacing: '0.06em' }}>06:42 today</div>
              </div>
            </div>
            <div style={{ fontFamily: 'var(--serif)', fontSize: 15, lineHeight: 1.5, color: 'var(--ink)', marginTop: 14, fontStyle: 'italic', textWrap: 'pretty' }}>&ldquo;{p.state.coach}&rdquo;</div>
          </Card>
        </div>
      </Body>
      <TabBar active="home" />
      <HomeIndicator />
    </Phone>
  );
}

// ── ADD-WEIGHT RESULT ────────────────────────────────────────────────────────
function AddWeightResult({ styleKey = 'hig', paceKey = 'onTrack' }) {
  const st = getStyle(styleKey);
  const p = computePace(paceKey);
  const tone = TONE[p.tone];
  const isDanger = paceKey === 'danger';
  const typed = parseFloat(window.__loggedWeight);
  const logged = (!isNaN(typed) && typed > 30 && typed < 250) ? typed : p.hist[p.hist.length - 1][1];

  return (
    <Phone styleKey={styleKey} label="Add Weight Result">
      <StatusBar />
      <CompactNav title="Weight Logged" trailing={<NavAction>Done</NavAction>} />
      <Body pad="14px 20px 26px" gap={18}>
        <div style={{ paddingTop: 6 }}>
          {window.OWMark && (
            <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 6 }}>
              <window.OWMark sport={(window.FC && window.FC.sport) || 'Boxing'} size={88} dark={false} accent="var(--red)" clip="weighin" />
            </div>
          )}
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <span style={{ width: 30, height: 30, borderRadius: '50%', background: tone.soft, display: 'flex', alignItems: 'center', justifyContent: 'center' }}><svg width="14" height="11" viewBox="0 0 14 11" fill="none"><path d="M1 5.5 L5 9.5 L13 1.5" stroke={tone.ink} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/></svg></span>
            <span style={{ fontFamily: 'var(--sans)', fontSize: 14, color: 'var(--ink-3)' }}>Logged <strong style={{ color: 'var(--ink)', fontWeight: 600 }}>{logged.toFixed(1)} kg</strong> · 06:18</span>
          </div>
          {!isDanger && (
            <div style={{ display: 'flex', alignItems: 'center', gap: 9, marginTop: 12 }}>
              <div style={{ display: 'flex', gap: 4 }}>
                {[0, 1, 2, 3, 4, 5, 6].map((i) => (
                  <span key={i} style={{ width: 7, height: 7, borderRadius: '50%', background: i === 6 ? 'var(--accent)' : 'color-mix(in srgb, var(--ink) 24%, transparent)' }} />
                ))}
              </div>
              <span style={{ fontFamily: 'var(--mono)', fontSize: 10, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--ink-3)', fontWeight: 700 }}>Every morning this week</span>
            </div>
          )}
          <div style={{ fontFamily: 'var(--sans)', fontSize: 25, fontWeight: 700, letterSpacing: '-0.02em', lineHeight: 1.15, color: 'var(--ink)', marginTop: 18, textWrap: 'balance' }}>{p.state.resultHead}</div>
          <div style={{ fontFamily: 'var(--sans)', fontSize: 15.5, color: 'var(--ink-2)', marginTop: 8 }}>{p.state.resultSub}</div>
        </div>

        <Card pad={20}>
          <div style={{ display: 'flex' }}>
            <Stat label="Weekly" value={(p.weeklyVel >= 0 ? '+' : '−') + Math.abs(p.weeklyVel).toFixed(1)} unit="kg" sub={p.tone === 'green' ? 'On track' : p.tone === 'red' ? 'Not enough' : (paceKey === 'tooFast' ? 'Dropping fast' : 'A little slow')} subColor={tone.ink} i={0} />
            <div style={{ width: 1, background: 'var(--rule)', alignSelf: 'stretch', margin: '0 20px' }} />
            <Stat label="Projected" value={p.projected.toFixed(1)} unit="kg" sub={p.gap <= 0.15 ? 'On target' : p.gap > 1.2 ? 'Too far off' : 'Slightly off'} subColor={tone.ink} i={0} />
          </div>
        </Card>

        <Card pad={18} tint="var(--paper-2)" style={{ boxShadow: 'none', border: `1px solid ${tone.soft}` }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <Eyebrow>What this means</Eyebrow>
            <ToneBadge tone={p.tone}>{p.badge}</ToneBadge>
          </div>
          <div style={{ fontFamily: 'var(--sans)', fontSize: 17, fontWeight: 600, lineHeight: 1.4, color: 'var(--ink)', marginTop: 13, textWrap: 'pretty' }}>{p.state.verdict}</div>
          <div style={{ fontFamily: 'var(--sans)', fontSize: 14, color: 'var(--ink-2)', lineHeight: 1.55, marginTop: 11, textWrap: 'pretty' }}>{p.state.coach}</div>
        </Card>

        <div style={{ marginTop: 2 }}>
          {isDanger ? (<>
            <PrimaryButton label="Review my plan" />
            <div style={{ textAlign: 'center', marginTop: 14 }}><TextButton>Keep current goal</TextButton></div>
          </>) : <PrimaryButton label="Back to Today" />}
        </div>
      </Body>
      <HomeIndicator />
    </Phone>
  );
}

// ── PROGRESS ─────────────────────────────────────────────────────────────────
const _WD = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
const _MON = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];

// ── CELEBRATORY DAILY LOG ─────────────────────────────────────────────────────
// A brief dark "moment of joy" after a morning weigh-in — same dark, mark-centric
// treatment as Building Plan (OnbLoading). Rewards showing up (the streak), not
// pace, so it never shames a plateau/off day. Sits between logging and the verdict.
function DailyCelebrate({ paceKey = 'onTrack', day = 12, streak = 7 }) {
  const sport = (window.FC && window.FC.sport) || 'Boxing';
  const DARK = { '--paper': '#15140f', '--paper-2': '#211f18', '--ink': '#faf7f1', '--ink-2': 'rgba(250,247,241,0.80)', '--ink-3': 'rgba(250,247,241,0.52)', '--rule': 'rgba(250,247,241,0.14)' };
  const dots = 7;
  return (
    <Phone styleKey="balanced" label="Logged">
      <div style={{ ...DARK, flex: 1, display: 'flex', flexDirection: 'column', background: '#15140f', color: 'var(--ink)' }}>
        <StatusBar />
        <div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: '40px', textAlign: 'center' }}>
          {window.OWMark
            ? <window.OWMark sport={sport} size={140} dark={true} accent="#e0563d" clip="weighin" />
            : <svg width="46" height="46" viewBox="0 0 46 46" fill="none"><circle cx="23" cy="23" r="20" stroke="#e0563d" strokeWidth="3"/><path d="M14 23 l6 6 12-13" stroke="#e0563d" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"/></svg>}
          <div style={{ fontFamily: 'var(--mono)', fontSize: 10.5, letterSpacing: '0.2em', textTransform: 'uppercase', color: 'var(--ink-3)', fontWeight: 600, marginTop: 28 }}>Logged · 06:18</div>
          <div style={{ fontFamily: 'var(--sans)', fontSize: 27, fontWeight: 700, letterSpacing: '-0.02em', color: 'var(--ink)', marginTop: 12, textWrap: 'balance' }}>That’s {streak} mornings straight.</div>
          <div style={{ fontFamily: 'var(--sans)', fontSize: 14.5, color: 'var(--ink-2)', marginTop: 10, lineHeight: 1.5, maxWidth: '26ch' }}>Day {day} on the board. Consistency is what makes the trend true — not any one number.</div>
          <div style={{ display: 'flex', gap: 7, marginTop: 22 }}>
            {Array.from({ length: dots }).map((_, i) => (
              <span key={i} style={{ width: 8, height: 8, borderRadius: '50%', background: i < (streak % dots || dots) ? '#e0563d' : 'rgba(250,247,241,0.18)' }} />
            ))}
          </div>
        </div>
        <div style={{ padding: '0 20px 16px' }}>
          <button style={{ width: '100%', background: 'var(--ink)', color: '#15140f', border: 'none', borderRadius: 'var(--radius-ctl)', minHeight: 52, fontFamily: 'var(--display)', fontSize: 14, letterSpacing: '0.13em', fontWeight: 600 }}>SEE TODAY’S READ</button>
        </div>
        <HomeIndicator />
      </div>
    </Phone>
  );
}

function Progress({ styleKey = 'hig', paceKey = 'onTrack', chartPlace = 'left' }) {
  const p = computePace(paceKey);
  const start = p.hist[0][1], current = p.hist[p.hist.length - 1][1];
  const change = current - start;
  const rows = window.recentLog(paceKey, 8);

  return (
    <Phone styleKey={styleKey} label="Progress">
      <StatusBar />
      <LargeTitle title="Progress" trailing={<GearButton />} />
      <Body>
        <Card pad={20}>
          <Eyebrow color="var(--accent)">This camp</Eyebrow>
          <div style={{ fontFamily: 'var(--sans)', fontSize: 20, fontWeight: 600, lineHeight: 1.25, color: 'var(--ink)', marginTop: 11, textWrap: 'balance' }}>Down <span style={{ color: 'var(--accent)' }}>{Math.abs(change).toFixed(1)} kg</span> so far. Steady and safe.</div>
          <div style={{ display: 'flex', marginTop: 18, paddingTop: 18, borderTop: '1px solid var(--rule)' }}>
            <Stat label="Start" value={start.toFixed(1)} unit="kg" i={0} />
            <Stat label="Now" value={current.toFixed(1)} unit="kg" i={1} />
            <Stat label="To go" value={Math.abs(p.toGo).toFixed(1)} unit="kg" color="var(--accent)" i={1} />
          </div>
        </Card>

        <div style={{ background: 'var(--paper)', borderRadius: 'var(--radius)', boxShadow: 'var(--card-shadow)', border: 'var(--card-border)', padding: 20 }}>
          <FCHealthCard place={chartPlace} heading="Weight trajectory" paceKey={paceKey} width={331} />
        </div>

        <window.FCPaceGaugeCard paceKey={paceKey} width={331} />
        <window.FCConeCard paceKey={paceKey} width={331} />
        <window.FCBurndownCard paceKey={paceKey} width={331} />

        <div>
          <SectionHeader trailing={<TextButton>See all</TextButton>}>Recent log</SectionHeader>
          <GroupedList>
            {rows.map((r, i) => (
              <Row key={i} last={i === rows.length - 1 && !r.second} chevron={false}
                label={<span style={{ display: 'inline-flex', flexDirection: 'column', gap: 2 }}><span>{r.dayLabel}</span><span style={{ fontFamily: 'var(--mono)', fontSize: 10, letterSpacing: '0.04em', color: r.off ? 'var(--red)' : 'var(--ink-3)', fontWeight: 600 }}>{r.time}{r.off ? ' · OFF WINDOW' : ''}</span></span>}
                control={
                  <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
                    <span style={{ fontFamily: 'var(--sans)', fontSize: 12.5, color: r.d <= 0 ? 'var(--t-green)' : 'var(--ink-3)', fontWeight: 500, fontFeatureSettings: '"tnum"', minWidth: 42, textAlign: 'right' }}>{r.d <= 0 ? '\u2193' : '\u2191'} {Math.abs(r.d).toFixed(1)}</span>
                    <span style={{ display: 'flex', alignItems: 'baseline', gap: 2 }}><Num size={17} weight={600}>{r.w.toFixed(1)}</Num><span style={{ fontFamily: 'var(--mono)', fontSize: 9.5, color: 'var(--ink-3)', fontWeight: 600 }}>kg</span></span>
                    <svg width="7" height="12" viewBox="0 0 7 12" fill="none"><path d="M1 1 L6 6 L1 11" stroke="var(--rule-2)" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/></svg>
                  </div>
                } />
            ))}
            {rows.filter(r => r.second).map((r, i, a) => (
              <Row key={'2' + i} last={true} chevron={false}
                label={<span style={{ display: 'inline-flex', flexDirection: 'column', gap: 2 }}><span style={{ color: 'var(--ink-3)' }}>{r.dayLabel} · 2nd reading</span><span style={{ fontFamily: 'var(--mono)', fontSize: 10, letterSpacing: '0.04em', color: 'var(--ink-3)', fontWeight: 600 }}>{r.second.time} · NOT USED</span></span>}
                control={
                  <div style={{ display: 'flex', alignItems: 'center', gap: 14, opacity: 0.6 }}>
                    <span style={{ display: 'flex', alignItems: 'baseline', gap: 2 }}><Num size={17} weight={600}>{r.second.w.toFixed(1)}</Num><span style={{ fontFamily: 'var(--mono)', fontSize: 9.5, color: 'var(--ink-3)', fontWeight: 600 }}>kg</span></span>
                  </div>
                } />
            ))}
          </GroupedList>
          <div style={{ fontFamily: 'var(--sans)', fontSize: 12, color: 'var(--ink-3)', lineHeight: 1.5, padding: '9px 4px 0', textWrap: 'pretty' }}>Logged twice in a day? We use the earliest fasted reading for your trend.</div>
        </div>

        <window.FCTimeDriftCard width={331} />
      </Body>
      <TabBar active="progress" />
      <HomeIndicator />
    </Phone>
  );
}

Object.assign(window, { Dashboard, AddWeightResult, DailyCelebrate, Progress });
