// fc-onboarding-coachlab.jsx — Onboarding message-delivery lab.
// Compares two ways to infuse social proof, the scientific-tracking UVP and
// fight-framing through the funnel: (A) INLINE coach beats that ride on the
// question screen the message belongs to, vs (B) standalone INTERSTITIAL
// educational screens between questions. Same copy, two mechanisms — so the
// length cost of interstitials is visible side by side.
//
// Copy is engine-accurate: cycle = a water offset on the EXPECTED scale weight
// (never the target); rules = division limit + gear + re-weigh + water cap;
// social proof = FC_SOCIAL_PROOF; fight-framing = FC_SPORT_PROTECT.

const CL_FB = '#a32a18';

// the OnWeight mark, used as the "corner coach" glyph
function OWMark({ size = 26, color = 'var(--accent)' }) {
  return (
    <svg width={size} height={size * 1.08} viewBox="0 0 100 108" fill="none" aria-hidden="true" style={{ flexShrink: 0 }}>
      <path d="M14 46 L34 88 L50 56 L66 88 L86 46" stroke={color} strokeWidth="10" strokeLinecap="round" strokeLinejoin="round" />
      <circle cx="50" cy="34" r="15" stroke={color} strokeWidth="10" />
    </svg>
  );
}

// INLINE beat — sits on the question screen, costs no extra step
function CoachBeat({ eyebrow, line, stat, statOf, src }) {
  return (
    <div style={{ display: 'flex', gap: 12, alignItems: 'flex-start', background: 'var(--paper)', border: '1px solid var(--rule)', borderLeft: '3px solid var(--accent)', borderRadius: 14, padding: '13px 15px', marginTop: 16, boxShadow: 'var(--card-shadow)' }}>
      <OWMark size={24} />
      <div style={{ flex: 1, minWidth: 0 }}>
        <div className="mono" style={{ fontSize: 9.5, letterSpacing: '0.14em', color: 'var(--accent)', fontWeight: 700, textTransform: 'uppercase' }}>{eyebrow}</div>
        {stat && (
          <div style={{ marginTop: 6 }}>
            <span style={{ fontFamily: 'var(--display)', fontWeight: 700, fontSize: 20, color: 'var(--ink)', letterSpacing: '0.01em' }}>{stat}</span>
            <span style={{ fontSize: 12.5, color: 'var(--ink-3)', marginLeft: 6 }}>{statOf}</span>
          </div>
        )}
        <div style={{ fontFamily: 'var(--sans)', fontSize: 13.5, lineHeight: 1.5, color: 'var(--ink-2)', marginTop: 5 }}>{line}</div>
        {src && <div className="mono" style={{ fontSize: 8.5, letterSpacing: '0.04em', color: 'var(--ink-3)', marginTop: 7, textTransform: 'uppercase' }}>Source · {src}</div>}
      </div>
    </div>
  );
}

// INTERSTITIAL — a full screen of its own, between two questions (the heavier option)
function EduScreen({ eyebrow, headline, body, chart, footnote }) {
  return (
    <Phone styleKey="balanced" label={'Edu · ' + eyebrow}>
      <StatusBar />
      <div style={{ background: '#e9ddcd', padding: '16px 20px 18px', display: 'flex', flexDirection: 'column', gap: 9 }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <OWMark size={30} color="var(--ink)" />
          <span className="mono" style={{ fontSize: 8.5, letterSpacing: '0.14em', color: 'var(--ink-3)', textTransform: 'uppercase', border: '1px solid var(--rule-2)', borderRadius: 100, padding: '3px 9px' }}>Between questions</span>
        </div>
        <div className="mono" style={{ fontSize: 10, letterSpacing: '0.16em', color: 'var(--accent)', fontWeight: 700, textTransform: 'uppercase' }}>{eyebrow}</div>
        <div style={{ fontFamily: 'var(--display)', fontWeight: 700, fontSize: 25, lineHeight: 1.06, letterSpacing: '0.005em', textTransform: 'uppercase', color: 'var(--ink)', textWrap: 'balance' }}>{headline}</div>
      </div>
      <div style={{ flex: 1, padding: '16px 20px 18px', display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
        <div style={{ fontFamily: 'var(--sans)', fontSize: 14.5, lineHeight: 1.55, color: 'var(--ink-2)' }}>{body}</div>
        {chart && <div style={{ marginTop: 14 }}>{chart}</div>}
        <div style={{ flex: 1, minHeight: 8 }} />
        {footnote && <div className="mono" style={{ fontSize: 9.5, letterSpacing: '0.04em', color: 'var(--ink-3)', marginTop: 14, lineHeight: 1.5, textTransform: 'uppercase' }}>{footnote}</div>}
        <button style={{ width: '100%', background: 'var(--ink)', color: 'var(--paper)', border: 'none', borderRadius: 'var(--radius-ctl)', minHeight: 54, fontFamily: 'var(--display)', fontSize: 14, letterSpacing: '0.14em', fontWeight: 600, marginTop: 14 }}>GOT IT</button>
      </div>
      <HomeIndicator />
    </Phone>
  );
}

// a question screen (real OnbStep chrome) + an optional inline beat
function LabQ({ moment, step, total, withBeat }) {
  return (
    <OnbStep flow="setup" label={moment.label} step={step} total={total} title={moment.title} subtitle={moment.subtitle} cta={moment.cta || 'Continue'}>
      {moment.q}
      {withBeat && <CoachBeat {...moment.beat} />}
    </OnbStep>
  );
}

// ── content, engine-accurate, per sport ──────────────────────────────────────
const CL_WEIGH = {
  'same-day': 'the morning you compete',
  'day-before': 'the day before',
  'same-or-day-before': 'the same day (amateur)',
  'within-2h': 'in the gi, minutes before you roll',
};

function labMoments(sport) {
  const SP = (window.FC_SPORTS || {});
  const S = SP[sport] || SP.MMA || {};
  const sp = window.socialProofFor ? window.socialProofFor(sport) : {};
  const pr = (window.FC_SPORT_PROTECT || {})[sport] || (window.FC_SPORT_PROTECT || {}).Other || { protect: 'your strength and stamina.' };
  const FC = window.FC || {};
  const weigh = CL_WEIGH[S.weighIn] || 'on a set day';
  const gear = S.equipmentReq ? (S.equipmentKg + ' kg of gear') : null;
  const reweigh = S.reweigh ? ('a +' + (S.reweighPct || 5) + '% re-weigh control') : null;
  const wc = window.maxWaterCutPct ? window.maxWaterCutPct(sport) : 0.05;
  const waterLabel = wc > 0 ? (Math.round(wc * 100) + '% of bodyweight') : 'no water cut';
  const protectFull = pr.protect;
  const protectShort = (() => { const s = protectFull.split('. ')[0]; const t = s.endsWith('.') ? s : s + '.'; return t.charAt(0).toLowerCase() + t.slice(1); })();
  const start = (FC.planStart != null ? FC.planStart : 78.4);

  const quote = (window.FC_FIGHTER_QUOTES || [])[0];
  const proofQuote = quote ? (
    <div style={{ borderLeft: '3px solid var(--accent)', paddingLeft: 14, marginTop: 4 }}>
      <div className="serif" style={{ fontStyle: 'italic', fontSize: 15.5, lineHeight: 1.45, color: 'var(--ink)' }}>“{quote.quote}”</div>
      <div className="mono" style={{ fontSize: 9.5, letterSpacing: '0.06em', color: 'var(--ink-3)', textTransform: 'uppercase', marginTop: 8 }}>{quote.who} · {quote.cred}</div>
    </div>
  ) : null;

  const rulesList = (
    <GroupedList>
      <Row label="Weigh-in" value={CL_WEIGH[S.weighIn] ? CL_WEIGH[S.weighIn].replace(/^the /, '') : 'set day'} chevron={false} />
      <Row label="Gear allowance" value={gear ? ('+' + gear) : 'None (fight kit)'} chevron={false} />
      <Row label="Re-weigh control" value={reweigh ? ('+' + (S.reweighPct || 5) + '%') : 'Single weigh-in'} chevron={false} last={true} />
    </GroupedList>
  );

  return [
    {
      key: 'sport', label: 'Sport', step: 1, title: 'What do you fight?',
      subtitle: 'This sets your rules, your gear and your coach.',
      q: (
        <GroupedList>
          <SelRow label={sport} sub={pr.tag} on={true} />
          <SelRow label="Boxing" on={false} />
          <SelRow label="Judo" on={false} last={true} />
        </GroupedList>
      ),
      beat: { eyebrow: "You're in good company", stat: sp.stat, statOf: sp.statOf, line: sp.coachLine, src: sp.src },
      edu: {
        eyebrow: 'The landscape',
        headline: "Cutting is the norm. Doing it well isn't.",
        body: sp.stat + ' ' + sp.statOf + '. ' + sp.line + ' ' + (window.FC_SOCIAL_PROOF_AUTHORITY || ''),
        chart: proofQuote,
        footnote: 'Source · ' + sp.src,
      },
    },
    {
      key: 'weight', label: 'Current Weight', step: 2, title: 'What do you weigh now?',
      subtitle: "Your fasted morning weight — that's your start line.",
      q: (
        <div style={{ textAlign: 'center', padding: '14px 0 8px' }}>
          <div style={{ fontFamily: 'var(--num)', fontSize: 62, fontWeight: 600, color: 'var(--ink)', lineHeight: 1 }}>
            {start.toFixed(1)}<span style={{ fontSize: 22, color: 'var(--ink-3)', marginLeft: 6 }}>kg</span>
          </div>
          <div className="mono" style={{ fontSize: 10, letterSpacing: '0.1em', color: 'var(--ink-3)', textTransform: 'uppercase', marginTop: 12 }}>Fasted · this morning</div>
        </div>
      ),
      beat: { eyebrow: 'How we read it', line: "We track your 7-day trend, not the number that flashes up this morning. Water and food alone swing the scale a kilo overnight — your plan won't flinch at the noise." },
      edu: {
        eyebrow: 'The method',
        headline: 'We trust the trend, not the daily number.',
        body: 'A single morning reading is mostly water, food and timing. OnWeight smooths every weigh-in into a trend line and judges your pace off that — so one heavy day is never mistaken for falling behind.',
        chart: <window.FCChart paceKey="onTrack" width={331} height={196} showPlan={true} />,
        footnote: 'Exponentially-weighted trend · evidence-based tracking cascade',
      },
    },
    {
      key: 'cycle', label: 'Cycle', step: 3, title: 'Track your cycle?',
      subtitle: 'We plan around the water shifts near weigh-in, and learn your pattern over time.',
      q: (
        <GroupedList>
          <SelRow label="Yes, track my cycle" sub="Recommended for the most accurate read" on={true} />
          <SelRow label="Not right now" on={false} last={true} />
        </GroupedList>
      ),
      beat: { eyebrow: 'For athletes who cycle', line: "Near your period you naturally hold water — up to about half a kilo. We fold that into the weight we expect on the scale, so a normal swing never reads as off-pace. Your target and your training never change." },
      edu: {
        eyebrow: 'Cycle-aware, not cycle-driven',
        headline: 'We adjust the expectation — never your target.',
        body: 'Your body holds a little water in the days before your period. OnWeight bends your expected weight to match, so the app reads that swing as water, not lost progress. The division limit and your plan stay exactly where they were — and on contraception or an irregular cycle, we watch your symptoms instead of guessing from a calendar.',
        chart: <window.PhaseIndicator />,
        footnote: 'Phase model · natural cycle only · RED-S safeguard if a period goes missing',
      },
    },
    {
      key: 'rules', label: 'Your rules', step: 4, title: 'Confirm your weigh-in rules',
      subtitle: 'We tune the target to your federation, not a generic number.',
      q: rulesList,
      beat: { eyebrow: 'Tuned to your rulebook', line: 'Your scale target already knows ' + sport + ' weighs in ' + weigh + (gear ? ', counts your ' + gear : ', no gear') + (reweigh ? ', and leaves room for ' + reweigh : '') + '. You chase the real number, not a guess.' },
      edu: {
        eyebrow: 'Down to the clause',
        headline: 'Your target is built from your rules.',
        body: 'We start at your division limit' + (gear ? ', add back your ' + gear : '') + (reweigh ? ', leave room for ' + reweigh : '') + ', and cap fight-week water at what your weigh-in timing safely allows (' + waterLabel + '). Every clause that moves the number is already in it.',
        chart: rulesList,
        footnote: S.note || '',
      },
    },
    {
      key: 'rate', label: 'Cut rate', step: 5, title: 'How fast?',
      subtitle: '0.5%/wk keeps you strong. Faster is possible, with trade-offs.',
      q: (
        <GroupedList>
          <SelRow label="0.25%/wk" sub="Conservative · needs a long runway" on={false} />
          <SelRow label="0.5%/wk" sub="Recommended · protects performance" on={true} />
          <SelRow label="0.75%/wk" sub="Faster · manageable" on={false} />
          <SelRow label="1.0%/wk" sub="Aggressive · the safe ceiling" on={false} last={true} />
        </GroupedList>
      ),
      beat: { eyebrow: 'Why steady wins', line: 'A steady cut protects ' + protectShort + " Make weight light and strong — that's how you win the fight, not just the weigh-in." },
      edu: {
        eyebrow: 'Winning starts on the scale',
        headline: 'Make weight without leaving the fight in the sauna.',
        body: 'Crash the last kilos and you make the number but show up flat — slower, weaker, gassed. Hold the cut to a steady rate and you keep ' + protectFull + ' Light and dangerous beats light and empty.',
        footnote: window.FC_SOCIAL_PROOF_AUTHORITY || '',
      },
    },
  ];
}

Object.assign(window, { OWMark, CoachBeat, EduScreen, LabQ, labMoments });
