/* HTD Program 4 — Mission loop */
(function () {
  const { useState, useEffect, useRef } = React;
  const Icon = window.HTDIcon;
  const { useNav, PushView, SectionLabel, Panel, GPSMap, ConfPill, MetricRow } = window.HTDUI;
  const F = window.HTD_FIX;

  const KV = ({k,v,c}) => (<div><div className="label-mono">{k}</div>
    <div style={{ fontFamily:'var(--display)', fontWeight:600, fontSize:17, color:c||'var(--bone)', marginTop:2 }}>{v}</div></div>);

  // ---------- MISSION DETAIL ----------
  function MissionDetail() {
    const nav = useNav(); const t = F.today;
    const toast = window.HTDUI.toast;
    const [saved, setSaved] = useState(false);
    const [scaled, setScaled] = useState(false);
    const foot = <button className="btn-primary" onClick={()=>nav.push('ActiveMission')}>START MISSION<span className="sub">LOCK IN. NO EXCUSES.</span></button>;
    return (
      <PushView title="MISSION DETAIL" footer={foot}>
        <div className="label-mono" style={{ marginTop:8 }}>{t.category} · {scaled?'35 MIN':t.duration}{scaled?' · SCALED':''}</div>
        <div className="display-xl" style={{ fontSize:34, margin:'8px 0 6px' }}>{scaled?'RUN 6K FASTED':t.title}</div>
        <div className="muted" style={{ fontSize:13.5, marginBottom:12 }}>{t.subtitle}</div>
        <div className="row" style={{ gap:8 }}>{t.tags.map(x=><span key={x} className="chip">{x}</span>)}</div>

        <div style={{ marginTop:16, padding:'13px 15px', borderLeft:'2px solid var(--acid)', background:'rgba(152,255,16,0.03)' }}>
          <div className="label-mono acid" style={{ marginBottom:6 }}>WHY THIS BUILDS YOU</div>
          <div style={{ fontFamily:'var(--ui)', fontSize:13.5, fontStyle:'italic', lineHeight:1.55, color:'var(--bone-muted)' }}>{t.lore}</div>
        </div>

        <SectionLabel>WHY THIS MISSION</SectionLabel>
        <Panel glow><div style={{ fontSize:13.5, lineHeight:1.55, color:'var(--bone-muted)' }}>{t.why}</div></Panel>

        <SectionLabel>PROOF STANDARD</SectionLabel>
        <Panel><div className="row" style={{ gap:18 }}>
          {[['gps','GPS + HR'],['camera','PHOTO FINISH']].map(([ic,l])=>(
            <div key={l} className="row" style={{ gap:9 }}><Icon name={ic} size={18} color="var(--acid)" />
              <span style={{ fontFamily:'var(--ui)', fontWeight:600, fontSize:14 }}>{l}</span></div>))}
        </div></Panel>

        <SectionLabel>PROTOCOL</SectionLabel>
        <Panel pad={false}>{t.protocol.map(([ph,desc],i)=>(
          <div key={i} className="row" style={{ gap:13, padding:'13px 14px', borderBottom: i<t.protocol.length-1?'1px solid var(--hairline)':'none' }}>
            <span className="num-mono" style={{ fontFamily:'var(--display)', fontWeight:700, fontSize:15, color:'var(--steel)', width:18 }}>{i+1}</span>
            <div><div style={{ fontFamily:'var(--display)', fontWeight:600, fontSize:14, letterSpacing:.5 }}>{ph}</div>
              <div className="muted" style={{ fontSize:12.5, marginTop:2 }}>{desc}</div></div>
          </div>))}</Panel>

        <div className="row" style={{ gap:10, marginTop:14 }}>
          <Panel style={{ flex:1 }}><div className="label-mono">PROGRESSION</div><div className="muted" style={{ fontSize:12.5, marginTop:6, lineHeight:1.45 }}>{t.progression}</div></Panel>
          <Panel style={{ flex:1 }}><div className="label-mono">REGRESSION</div><div className="muted" style={{ fontSize:12.5, marginTop:6, lineHeight:1.45 }}>{t.regression}</div></Panel>
        </div>

        <SectionLabel>SAFETY STOP CONDITIONS</SectionLabel>
        <Panel>{t.contra.map((c,i)=>(<div key={i} className="row" style={{ gap:9, padding:'6px 0' }}>
          <Icon name="alert" size={15} color="var(--amber)" /><span className="muted" style={{ fontSize:13 }}>{c}</span></div>))}</Panel>

        <div className="row" style={{ gap:10, marginTop:14 }}>
          <button className="btn-ghost" onClick={()=>nav.push('AIArchitect')}>REQUEST AI ALTERNATIVE</button>
          <button className="btn-ghost" style={scaled?{ borderColor:'var(--border-active)', color:'var(--acid)' }:{}}
            onClick={()=>{ setScaled(s=>!s); toast(scaled?'RESTORED · 10K · DIFFICULTY 8.0':'SCALED · 6K · DIFFICULTY 6.0'); }}>{scaled?'✓ SCALED · 6K':'SCALE MISSION'}</button>
        </div>
        <button className="btn-ghost" style={{ marginTop:10, ...(saved?{ borderColor:'var(--border-active)', color:'var(--acid)' }:{}) }}
          onClick={()=>{ setSaved(s=>!s); toast(saved?'REMOVED FROM SAVED':'SAVED FOR LATER · EXPIRES MIDNIGHT'); }}>{saved?'✓ SAVED FOR LATER':'SAVE FOR LATER'}</button>
        <div className="row between" style={{ marginTop:14, padding:'0 2px' }}>
          <span className="label-mono">EXPECTED RECOVERY COST</span><span className="label-mono amber-c">{t.recoveryCost}</span>
        </div>
      </PushView>
    );
  }

  // ---------- ACTIVE MISSION ----------
  function ActiveMission() {
    const nav = useNav(); const t = F.today;
    const [sec, setSec] = useState(1132);
    const [paused, setPaused] = useState(false);
    const [noteOpen, setNoteOpen] = useState(false);
    const [exMode, setExMode] = useState('TIMER');
    const [checks, setChecks] = useState({});
    useEffect(()=>{ if (paused) return; const id=setInterval(()=>setSec(s=>s+1),1000); return ()=>clearInterval(id); },[paused]);
    const mm = String(Math.floor(sec/60)).padStart(2,'0'), ss = String(sec%60).padStart(2,'0');
    const dist = (sec/300).toFixed(2);
    const foot = (
      <div style={{ display:'flex', flexDirection:'column', gap:10 }}>
        <div className="row" style={{ gap:10 }}>
          <button className="btn-ghost" onClick={()=>setPaused(p=>!p)} style={paused?{ borderColor:'var(--border-active)', color:'var(--acid)' }:{}}>
            {paused?'▶ RESUME':'❙❙ PAUSE'}</button>
          <button className="btn-ghost" style={{ width:'auto', padding:'0 18px' }} onClick={()=>setNoteOpen(o=>!o)}>NOTE</button>
          <button className="btn-ghost" style={{ width:'auto', padding:'0 16px', borderColor:'rgba(255,59,48,0.45)', color:'var(--danger)' }}
            onClick={()=>nav.pop()} aria-label="Safety stop">⏻ STOP</button>
        </div>
        <button className="btn-primary" onClick={()=>nav.push('ProofCapture')}>SUBMIT PROOF<span className="sub">{paused?'MISSION PAUSED · TIMER HELD':'MISSION IN PROGRESS · GPS LOCKED'}</span></button>
      </div>);
    return (
      <PushView title="ACTIVE MISSION" footer={foot}>
        <div className="row between" style={{ marginTop:6 }}>
          <div><div className="label-mono" style={{ color: paused?'var(--amber)':'var(--acid)' }}>● {paused?'PAUSED':'LIVE'} · PHASE 2 / MAIN SET</div>
            <div className="display-lg" style={{ fontSize:22, marginTop:6 }}>{t.title}</div></div>
        </div>
        <div className="row" style={{ gap:8, marginTop:14, flexWrap:'wrap' }}>
          {['TIMER','INTERVALS','CHECKLIST','FOCUS'].map(m=>(
            <button key={m} onClick={()=>setExMode(m)} className="label-mono" style={{ padding:'8px 11px', borderRadius:6, cursor:'pointer',
              background: exMode===m?'rgba(152,255,16,0.08)':'var(--panel)', border:'1px solid '+(exMode===m?'var(--acid)':'var(--hairline-2)'),
              color: exMode===m?'var(--acid)':'var(--bone-muted)' }}>{m}</button>))}
        </div>
        {exMode==='TIMER' && <div className="panel panel-glow" style={{ marginTop:14, padding:'24px 16px', textAlign:'center', borderColor: paused?'rgba(255,195,7,0.5)':undefined }}>
          <div className="label-mono">{paused?'PAUSED':'ELAPSED'}</div>
          <div className="num-mono" style={{ fontFamily:'var(--display)', fontWeight:700, fontSize:64, lineHeight:1, color: paused?'var(--amber)':'var(--acid)', marginTop:4 }}>{mm}:{ss}</div>
          <div className="row" style={{ justifyContent:'space-around', marginTop:18, borderTop:'1px solid var(--hairline)', paddingTop:14 }}>
            <KV k="DISTANCE" v={dist+' KM'} /><KV k="AVG PACE" v="4:58 /KM" /><KV k="AVG HR" v="142 BPM" c="var(--acid)" />
          </div>
        </div>}
        {exMode==='INTERVALS' && <div className="panel panel-glow" style={{ marginTop:14, padding:'22px 16px', textAlign:'center' }}>
          <div className="label-mono">ROUND {Math.min(8,(Math.floor(sec/90)%8)+1)} / 8 · {(sec%90)<60?'WORK':'REST'}</div>
          <div className="num-mono" style={{ fontFamily:'var(--display)', fontWeight:700, fontSize:64, lineHeight:1, marginTop:4,
            color: (sec%90)<60?'var(--acid)':'var(--amber)' }}>
            {String(Math.floor(((sec%90)<60?60-(sec%90):90-(sec%90))/60)).padStart(1,'0')}:{String(((sec%90)<60?60-(sec%90):90-(sec%90))%60).padStart(2,'0')}</div>
          <div className="row" style={{ gap:4, marginTop:18 }}>
            {Array.from({length:8}).map((_,i)=>(
              <div key={i} style={{ flex:1, height:5, borderRadius:2,
                background: i<(Math.floor(sec/90)%8)?'var(--acid)':i===(Math.floor(sec/90)%8)?'var(--acid-deep)':'var(--raised-2)' }} />))}
          </div>
          <div className="label-mono" style={{ marginTop:12 }}>60S WORK · 30S REST · TARGET Z4</div>
        </div>}
        {exMode==='CHECKLIST' && <div className="panel panel-glow" style={{ marginTop:14, padding:'6px 0' }}>
          {t.protocol.map(([ph,desc],i)=>{
            const on = !!checks[i];
            return (
              <button key={i} onClick={()=>setChecks(c=>({...c,[i]:!c[i]}))} className="row" style={{ width:'100%', gap:12, padding:'13px 16px', cursor:'pointer',
                background:'none', border:'none', borderBottom:i<t.protocol.length-1?'1px solid var(--hairline)':'none', textAlign:'left' }}>
                <div style={{ width:22, height:22, borderRadius:6, flex:'0 0 auto', border:'1px solid '+(on?'var(--acid)':'var(--hairline-2)'),
                  background: on?'var(--acid)':'transparent', display:'grid', placeItems:'center' }}>
                  {on && <Icon name="check" size={14} color="#0a1400" />}</div>
                <div><div style={{ fontFamily:'var(--display)', fontWeight:600, fontSize:14, letterSpacing:.5, color: on?'var(--acid)':'var(--bone)' }}>{ph}</div>
                  <div className="muted" style={{ fontSize:12, marginTop:1 }}>{desc}</div></div>
              </button>);
          })}
          <div className="label-mono" style={{ padding:'12px 16px 8px', color:'var(--acid)' }}>
            {Object.values(checks).filter(Boolean).length} / {t.protocol.length} STEPS COMPLETE</div>
        </div>}
        {exMode==='FOCUS' && <div className="panel panel-glow" style={{ marginTop:14, padding:'26px 16px', textAlign:'center' }}>
          <div className="label-mono">DEEP FOCUS BLOCK · REMAINING</div>
          <div className="num-mono" style={{ fontFamily:'var(--display)', fontWeight:700, fontSize:64, lineHeight:1, color:'var(--cyan)', marginTop:4 }}>
            {String(Math.floor(Math.max(0,2700-sec)/60)).padStart(2,'0')}:{String(Math.max(0,2700-sec)%60).padStart(2,'0')}</div>
          <div className="label-mono" style={{ marginTop:14 }}>PHONE FACE DOWN · SINGLE TASK · NO INPUTS</div>
        </div>}
        <SectionLabel>LIVE ROUTE</SectionLabel>
        <Panel pad={false} style={{ overflow:'hidden' }}><GPSMap height={130} /></Panel>
        {noteOpen && <>
          <SectionLabel>MISSION NOTE</SectionLabel>
          <textarea autoFocus placeholder="Mid-mission note…" rows={2}
            style={{ width:'100%', background:'var(--panel)', border:'1px solid var(--border-active)', borderRadius:'var(--r)',
              color:'var(--bone)', fontFamily:'var(--ui)', fontSize:14, padding:12, outline:'none', resize:'none' }} />
        </>}
        <SectionLabel>PROOF REQUIREMENTS</SectionLabel>
        <Panel pad={false}>{[['GPS track recording','on'],['Heart rate stream','on'],['Photo finish at end','pending']].map(([l,st],i)=>(
          <div key={i} className="row between" style={{ padding:'12px 14px', borderBottom:i<2?'1px solid var(--hairline)':'none' }}>
            <span style={{ fontSize:13.5, color:'var(--bone-muted)' }}>{l}</span>
            <span className="label-mono" style={{ color: st==='on'?'var(--acid)':'var(--steel)' }}>{st==='on'?'● CAPTURING':'○ PENDING'}</span>
          </div>))}</Panel>
      </PushView>
    );
  }

  // ---------- PROOF CAPTURE ----------
  function ProofCapture() {
    const nav = useNav();
    const [mode, setMode] = useState('GPS MAP');
    const [vis, setVis] = useState('PUBLIC');
    const [anomaly, setAnomaly] = useState(false);
    const [camGranted, setCamGranted] = useState(false);
    const needsCam = mode==='PHOTO'||mode==='VIDEO';
    const camBlocked = needsCam && !camGranted;
    const modes = [['GPS MAP','gps'],['WEARABLE','watch'],['PHOTO','camera'],['VIDEO','camera'],['TIMER','timer']];
    const foot = <button className="btn-primary" disabled={camBlocked} style={camBlocked?{opacity:.35,cursor:'not-allowed'}:{}}
      onClick={()=>!camBlocked && nav.push('ProofIntegrity',{anomaly})}>SUBMIT PROOF<span className="sub">{camBlocked?'CAMERA PERMISSION REQUIRED':'RUN INTEGRITY CHECK'}</span></button>;
    return (
      <PushView title="PROOF CAPTURE" footer={foot}>
        <SectionLabel style={{ marginTop:10 }}>PROOF TYPE</SectionLabel>
        <div className="row" style={{ flexWrap:'wrap', gap:8 }}>
          {modes.map(([m,ic])=>(
            <button key={m} onClick={()=>setMode(m)} className="row" style={{ gap:7, height:34, padding:'0 12px', cursor:'pointer',
              background: mode===m?'rgba(152,255,16,0.08)':'var(--panel)', border:'1px solid '+(mode===m?'var(--acid)':'var(--hairline-2)'),
              borderRadius:'var(--r-sm)', color: mode===m?'var(--acid)':'var(--bone-muted)', fontFamily:'var(--mono)', fontSize:10, letterSpacing:1 }}>
              <Icon name={ic} size={14} color={mode===m?'var(--acid)':'var(--steel)'} />{m}</button>))}
        </div>

        <SectionLabel>CAPTURE</SectionLabel>
        {mode==='GPS MAP'
          ? <Panel pad={false} style={{ overflow:'hidden' }}><GPSMap height={150} />
              <div className="row between" style={{ padding:'10px 14px' }}><span className="label-mono">GARMIN FENIX 7</span><span className="label-mono acid">● SYNCED</span></div></Panel>
          : camBlocked
          ? <Panel style={{ borderColor:'rgba(255,195,7,0.5)' }}>
              <div style={{ textAlign:'center', padding:'14px 0 4px' }}>
                <Icon name="camera" size={28} color="var(--amber)" />
                <div className="display-lg" style={{ fontSize:17, marginTop:10, color:'var(--amber)' }}>CAMERA PERMISSION NEEDED</div>
                <div className="muted" style={{ fontSize:12.5, marginTop:6, lineHeight:1.5 }}>HTD needs camera access to capture {mode.toLowerCase()} proof. Your media stays private until you share it.</div>
              </div>
              <div className="row" style={{ gap:10, marginTop:14 }}>
                <button className="btn-ghost" style={{ borderColor:'var(--border-active)', color:'var(--acid)' }} onClick={()=>setCamGranted(true)}>ALLOW CAMERA</button>
                <button className="btn-ghost" onClick={()=>setCamGranted(true)}>FROM LIBRARY</button>
              </div>
            </Panel>
          : <div style={{ height:150, borderRadius:'var(--r)', border:'1px dashed var(--hairline-2)', display:'grid', placeItems:'center',
              background:'repeating-linear-gradient(135deg,#0c0f0b 0 8px,#0a0d0a 8px 16px)' }}>
              <div style={{ textAlign:'center' }}><Icon name="upload" size={26} color="var(--steel)" />
                <div className="label-mono" style={{ marginTop:8 }}>DROP {mode} PROOF</div></div></div>}

        <SectionLabel>REQUIRED PROOF</SectionLabel>
        <Panel pad={false}>{[['GPS distance ≥ 10 KM',true],['Heart rate stream',true],['Photo finish',!anomaly]].map(([l,ok],i)=>(
          <div key={i} className="row between" style={{ padding:'11px 14px', borderBottom:i<2?'1px solid var(--hairline)':'none' }}>
            <span style={{ fontSize:13.5, color:'var(--bone-muted)' }}>{l}</span>
            <Icon name={ok?'check':'alert'} size={15} color={ok?'var(--acid)':'var(--amber)'} /></div>))}</Panel>

        <SectionLabel>VISIBILITY</SectionLabel>
        <div className="row" style={{ gap:8 }}>{['PRIVATE','CREW','PUBLIC'].map(v=>(
          <button key={v} onClick={()=>setVis(v)} style={{ flex:1, height:38, cursor:'pointer', borderRadius:'var(--r-sm)',
            background: vis===v?'rgba(152,255,16,0.08)':'var(--panel)', border:'1px solid '+(vis===v?'var(--acid)':'var(--hairline-2)'),
            color: vis===v?'var(--acid)':'var(--bone-muted)', fontFamily:'var(--mono)', fontSize:10, letterSpacing:1 }}>{v}</button>))}</div>

        <label className="row between" style={{ marginTop:18, padding:'12px 0', cursor:'pointer' }}>
          <span className="label-mono" style={{ textTransform:'none', letterSpacing:.5 }}>DEMO · inject proof anomaly</span>
          <span onClick={()=>setAnomaly(a=>!a)} style={{ width:42, height:24, borderRadius:12, background: anomaly?'var(--acid)':'var(--raised-2)',
            border:'1px solid var(--hairline-2)', position:'relative', transition:'background .15s' }}>
            <span style={{ position:'absolute', top:2, left: anomaly?20:2, width:18, height:18, borderRadius:'50%', background: anomaly?'#0a1400':'var(--steel)', transition:'left .15s' }} /></span>
        </label>
      </PushView>
    );
  }

  // ---------- PROOF INTEGRITY ----------
  function ProofIntegrity({ params }) {
    const nav = useNav();
    const anomaly = params && params.anomaly;
    const checks = [
      ['Checksum / duplicate', true],['GPS ↔ time consistency', true],
      ['Pace plausibility', !anomaly],['Required proof present', true],['Media type / size', true],
    ];
    const conf = anomaly ? 'MED' : 'HIGH';
    const foot = anomaly
      ? <div style={{ display:'flex', flexDirection:'column', gap:10 }}>
          <button className="btn-primary" onClick={()=>nav.push('RatingDebrief')}>SUBMIT WITH WARNING</button>
          <button className="btn-ghost" onClick={()=>nav.pop()}>RE-CAPTURE PROOF</button></div>
      : <button className="btn-primary" onClick={()=>nav.push('RatingDebrief')}>PROOF ACCEPTED · CONTINUE</button>;
    return (
      <PushView title="PROOF INTEGRITY" footer={foot}>
        <div className="panel panel-pad" style={{ marginTop:14, textAlign:'center',
          borderColor: anomaly?'rgba(255,195,7,0.5)':'var(--border-active)',
          boxShadow: anomaly?'0 0 24px -8px rgba(255,195,7,0.3)':'0 0 24px -8px var(--acid-glow)' }}>
          <div style={{ position:'relative', width:74, height:74, margin:'6px auto 12px' }}>
            <svg width="74" height="74" viewBox="0 0 74 74" style={{ filter:'drop-shadow(0 0 8px '+(anomaly?'rgba(255,195,7,0.4)':'var(--acid-glow)')+')' }}>
              <circle cx="37" cy="37" r="34" fill="none" stroke="var(--raised-2)" strokeWidth="2.5" />
              <circle className={anomaly?'':'proven-ring'} cx="37" cy="37" r="34" fill="none" stroke={anomaly?'var(--amber)':'var(--acid)'} strokeWidth="2.5" strokeLinecap="round" transform="rotate(-90 37 37)" />
            </svg>
            <div className={anomaly?'':'lock-pop'} style={{ position:'absolute', inset:0, display:'grid', placeItems:'center' }}>
              <Icon name={anomaly?'alert':'lock'} size={28} color={anomaly?'var(--amber)':'var(--acid)'} /></div>
          </div>
          <div className="display-lg" style={{ fontSize:22, color: anomaly?'var(--amber)':'var(--acid)' }}>{anomaly?'REVIEW REQUIRED':'PROOF ACCEPTED'}</div>
          <div className="muted" style={{ fontSize:12.5, marginTop:6 }}>{anomaly?'One signal looks inconsistent. Review before submitting.':'All integrity checks passed. Proof locked.'}</div>
        </div>
        <SectionLabel>INTEGRITY CHECKS</SectionLabel>
        <Panel pad={false}>{checks.map(([l,ok],i)=>(
          <div key={i} className="row between" style={{ padding:'12px 14px', borderBottom:i<checks.length-1?'1px solid var(--hairline)':'none' }}>
            <span style={{ fontSize:13.5, color:'var(--bone-muted)' }}>{l}</span>
            <span className="label-mono" style={{ color: ok?'var(--acid)':'var(--amber)' }}>{ok?'● PASS':'▲ FLAG'}</span></div>))}</Panel>
        <SectionLabel>PROOF CONFIDENCE</SectionLabel>
        <Panel><div className="row between" style={{ marginBottom:9 }}><ConfPill level={conf} />
          <span className="num-mono" style={{ color: anomaly?'var(--amber)':'var(--acid)', fontWeight:600 }}>{anomaly?'74':'96'}%</span></div>
          <div style={{ height:7, borderRadius:4, background:'var(--raised-2)', overflow:'hidden' }}>
            <div style={{ height:'100%', width:(anomaly?74:96)+'%', background: anomaly?'var(--amber)':'var(--acid)', borderRadius:4 }} /></div></Panel>
      </PushView>
    );
  }

  // ---------- RATING / DEBRIEF ----------
  function RatingDebrief() {
    const nav = useNav();
    const [rpe, setRpe] = useState(7);
    const [mental, setMental] = useState(6);
    const [vals, setVals] = useState({ quality:4, enjoyment:3, usefulness:5, soreness:2, repeat:4 });
    const [safety, setSafety] = useState(false);
    const Stars = ({k}) => (
      <div className="row" style={{ gap:6 }}>{[1,2,3,4,5].map(n=>(
        <button key={n} onClick={()=>setVals(v=>({...v,[k]:n}))} style={{ background:'none', border:'none', cursor:'pointer', padding:0 }}>
          <Icon name="spark" size={20} color={n<=vals[k]?'var(--acid)':'var(--steel-dim)'} fill={n<=vals[k]?'var(--acid)':'none'} /></button>))}</div>);
    const foot = <button className="btn-primary" onClick={()=>nav.push('MissionComplete')}>COMPLETE MISSION<span className="sub">RECORD OUTCOME</span></button>;
    return (
      <PushView title="DEBRIEF" footer={foot}>
        <SectionLabel style={{ marginTop:10 }}>PHYSICAL DIFFICULTY · <span className="acid">{rpe}/10</span></SectionLabel>
        <input type="range" min="1" max="10" value={rpe} onChange={e=>setRpe(+e.target.value)} className="htd-range" style={{ width:'100%' }} />
        <SectionLabel>MENTAL DIFFICULTY · <span className="acid">{mental}/10</span></SectionLabel>
        <input type="range" min="1" max="10" value={mental} onChange={e=>setMental(+e.target.value)} className="htd-range" style={{ width:'100%' }} />
        <SectionLabel>OUTCOME SIGNALS</SectionLabel>
        <Panel pad={false}>{[['Completion quality','quality'],['Enjoyment','enjoyment'],['Usefulness','usefulness'],['Soreness','soreness'],['Repeat willingness','repeat']].map(([l,k],i)=>(
          <div key={k} className="row between" style={{ padding:'12px 14px', borderBottom:i<4?'1px solid var(--hairline)':'none' }}>
            <span style={{ fontSize:13.5, color:'var(--bone-muted)' }}>{l}</span><Stars k={k} /></div>))}</Panel>
        <label className="row between panel panel-pad" style={{ marginTop:12, cursor:'pointer' }}>
          <div className="row" style={{ gap:10 }}><Icon name="alert" size={17} color={safety?'var(--danger)':'var(--steel)'} />
            <span style={{ fontSize:13.5, color:'var(--bone)' }}>Flag a safety concern</span></div>
          <span onClick={()=>setSafety(s=>!s)} style={{ width:42, height:24, borderRadius:12, background: safety?'var(--danger)':'var(--raised-2)',
            border:'1px solid var(--hairline-2)', position:'relative' }}>
            <span style={{ position:'absolute', top:2, left: safety?20:2, width:18, height:18, borderRadius:'50%', background: safety?'#fff':'var(--steel)', transition:'left .15s' }} /></span>
        </label>
        <SectionLabel>REFLECTION</SectionLabel>
        <textarea placeholder="What did today's standard teach you?" rows={3}
          style={{ width:'100%', background:'var(--panel)', border:'1px solid var(--hairline-2)', borderRadius:'var(--r)',
            color:'var(--bone)', fontFamily:'var(--ui)', fontSize:14, padding:12, outline:'none', resize:'none' }} />
        <div className="label-mono" style={{ marginTop:12, color:'var(--steel)' }}>↳ FEEDS RECOMMENDATION LEARNING ENGINE</div>
      </PushView>
    );
  }

  // ---------- MISSION COMPLETE ----------
  function MissionComplete() {
    const nav = useNav();
    const { useCountUp } = window.HTDMotion;
    const score = Math.round(useCountUp(842));
    const delta = Math.round(useCountUp(14, 700));
    const foot = <button className="btn-primary" onClick={()=>nav.push('ShareStudio')}>SHARE PROOF<span className="sub">TURN COMPLETION INTO A RECEIPT</span></button>;
    return (
      <PushView title="MISSION COMPLETE" onBack={()=>nav.popToRoot()} footer={foot}>
        <div style={{ textAlign:'center', padding:'18px 0 8px' }} className="screen-enter">
          <div style={{ position:'relative', width:84, height:84, margin:'0 auto 14px' }}>
            <svg width="84" height="84" viewBox="0 0 84 84" style={{ filter:'drop-shadow(0 0 8px var(--acid-glow))' }}>
              <circle cx="42" cy="42" r="35" fill="none" stroke="var(--raised-2)" strokeWidth="3" />
              <circle className="proven-ring" cx="42" cy="42" r="35" fill="none" stroke="var(--acid)" strokeWidth="3" strokeLinecap="round" transform="rotate(-90 42 42)" />
            </svg>
            <div className="lock-pop" style={{ position:'absolute', inset:0, display:'grid', placeItems:'center' }}><Icon name="check" size={34} color="var(--acid)" /></div>
          </div>
          <div className="display-xl" style={{ fontSize:36, color:'var(--acid)' }}>MISSION PROVEN</div>
          <div className="muted" style={{ fontSize:13.5, marginTop:6 }}>{F.today.title}</div>
        </div>
        <Panel glow style={{ marginTop:6 }} className="scan-host">
          <div className="row between"><span className="label-mono">RESILIENCE SCORE</span>
            <span className="num-mono acid delta-pulse" style={{ fontWeight:700 }}>+{delta}</span></div>
          <div className="row" style={{ alignItems:'baseline', gap:8, marginTop:4 }}>
            <span style={{ fontFamily:'var(--display)', fontWeight:700, fontSize:40, color:'var(--bone)' }}>{score}</span>
            <span className="label-mono acid">▲ FROM 828 · ELITE</span></div>
        </Panel>
        <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:10, marginTop:12 }}>
          {[['STREAK','19 DAYS','MAINTAINED','flame'],['CREW RANK','#2','▲ +1','crew'],['CHALLENGE','+120','HTD 30 PTS','trophy'],['PROOF','HIGH','96% CONF','shieldCheck']].map(([l,v,s,ic])=>(
            <Panel key={l}><div className="row between"><div className="label-mono">{l}</div><Icon name={ic} size={15} color="var(--steel)" /></div>
              <div style={{ fontFamily:'var(--display)', fontWeight:700, fontSize:22, marginTop:6 }}>{v}</div>
              <div className="label-mono acid" style={{ marginTop:2 }}>{s}</div></Panel>))}
        </div>
        <SectionLabel>NEXT MISSION PREVIEW</SectionLabel>
        <Panel onClick={()=>{}}><div className="row between"><div>
          <div style={{ fontFamily:'var(--display)', fontWeight:600, fontSize:18 }}>BACK SQUAT 5×5</div>
          <div className="label-mono" style={{ marginTop:3 }}>STRENGTH · TOMORROW · 06:00</div></div>
          <Icon name="chevronRight" size={20} color="var(--steel)" /></div></Panel>
      </PushView>
    );
  }

  // ---------- SHARE STUDIO ----------
  function ShareStudio() {
    const nav = useNav();
    const cards = ['HIGHLIGHT 15S','MISSION COMPLETE','WEEKLY REPORT','CHALLENGE RANK','CREW WIN','COMEBACK','EARN YOUR FREEDOM'];
    const [card, setCard] = useState('HIGHLIGHT 15S');
    const [fmt, setFmt] = useState('4:5');
    const [hideMetrics, setHideMetrics] = useState(false);
    const toast = window.HTDUI.toast;
    const FMTS = { '9:16':'9/16', '1:1':'1/1', '4:5':'4/5', 'LINK':'auto' };
    const targets = [['INSTAGRAM','camera'],['TIKTOK','feed'],['X','x'],['THREADS','comment'],['SAVE','upload'],['COPY LINK','share']];
    const foot = <button className="btn-primary" onClick={()=>nav.popToRoot()}>DONE<span className="sub">PROOF IS POWER</span></button>;
    return (
      <PushView title="SHARE STUDIO" onBack={()=>nav.popToRoot()} footer={foot}>
        <SectionLabel style={{ marginTop:8 }}>CARD TYPE</SectionLabel>
        <div className="row" style={{ flexWrap:'wrap', gap:8 }}>{cards.map(c=>(
          <button key={c} onClick={()=>setCard(c)} className="label-mono" style={{ padding:'8px 11px', borderRadius:6, cursor:'pointer',
            background: card===c?'rgba(152,255,16,0.08)':'var(--panel)', border:'1px solid '+(card===c?'var(--acid)':'var(--hairline-2)'),
            color: card===c?'var(--acid)':'var(--bone-muted)' }}>{c}</button>))}</div>

        <div className="row between" style={{ marginTop:18 }}>
          <span className="label-mono">PREVIEW · {fmt}</span>
          <div className="row" style={{ gap:6 }}>
            {Object.keys(FMTS).map(f=>(
              <button key={f} onClick={()=>setFmt(f)} className="label-mono" style={{ padding:'6px 10px', borderRadius:5, cursor:'pointer',
                background: fmt===f?'rgba(152,255,16,0.08)':'transparent', border:'1px solid '+(fmt===f?'var(--acid)':'var(--hairline-2)'),
                color: fmt===f?'var(--acid)':'var(--steel)' }}>{f}</button>))}
          </div>
        </div>
        <div style={{ marginTop:10, borderRadius:'var(--r-lg)', overflow:'hidden', border:'1px solid var(--hairline-2)', position:'relative',
          background:'linear-gradient(160deg,#10140d,#060706)', padding: fmt==='LINK'?14:20, aspectRatio: fmt==='LINK'?undefined:FMTS[fmt], display:'flex', flexDirection: fmt==='LINK'?'row':'column',
          alignItems: fmt==='LINK'?'center':undefined, gap: fmt==='LINK'?14:0,
          maxWidth: fmt==='9:16'?240:'100%', margin:'10px auto 0', width:'100%', transition:'aspect-ratio .2s' }}>
          {fmt==='LINK' ? (
            <>
              <div style={{ width:54, height:54, borderRadius:10, flex:'0 0 auto', border:'1px solid var(--border-active)', display:'grid', placeItems:'center', boxShadow:'0 0 16px -6px var(--acid-glow)' }}>
                <Icon name="shieldCheck" size={26} color="var(--acid)" /></div>
              <div style={{ minWidth:0 }}>
                <div style={{ fontFamily:'var(--display)', fontWeight:700, fontSize:16, letterSpacing:.3 }}>MISSION PROVEN · {F.today.title}</div>
                <div className="muted" style={{ fontSize:12, marginTop:3 }}>{hideMetrics?'10.02 KM · metrics private':'10.02 KM · 4:58 /KM · 49:52'}</div>
                <div className="label-mono acid" style={{ marginTop:6 }}>HTD.APP/P/X92K4 · #PROVEIT</div>
              </div>
            </>
          ) : card==='HIGHLIGHT 15S' ? (
            <>
              <image-slot id="share-highlight" placeholder="Drop proof footage still" shape="rect"
                style={{ position:'absolute', inset:0, width:'100%', height:'100%', opacity:.45 }}></image-slot>
              <div className="label-mono acid" style={{ display:'flex', alignItems:'center', gap:6, position:'relative', pointerEvents:'none' }}>
                <span style={{ width:7, height:7, borderRadius:'50%', background:'var(--danger)', boxShadow:'0 0 7px var(--danger)' }} />
                AUTO-EDIT · STATS OVER PROOF FOOTAGE</div>
              <div style={{ flex:1, display:'grid', placeItems:'center', position:'relative', pointerEvents:'none' }}>
                <div style={{ position:'absolute', inset:'10% 0', borderRadius:10,
                  background:'repeating-linear-gradient(135deg, rgba(152,255,16,0.03) 0 10px, transparent 10px 20px)' }} />
                <div style={{ textAlign:'center', position:'relative' }}>
                  <div className="label-mono">KM 7 SPLIT</div>
                  <div style={{ fontFamily:'var(--display)', fontWeight:700, fontSize:56, color:'var(--acid)', lineHeight:.95,
                    textShadow:'0 0 30px var(--acid-glow)' }}>4:51</div>
                  <div className="label-mono" style={{ marginTop:6 }}>{hideMetrics?'METRICS PRIVATE':'HR 144 · NEGATIVE SPLIT'}</div>
                </div>
              </div>
              <div style={{ position:'relative', pointerEvents:'none' }}>
                <div className="row between" style={{ marginBottom:6 }}>
                  <span className="label-mono">▶ 0:07 / 0:15</span><span className="label-mono acid">9:16 · 1:1 · 4:5</span></div>
                <div style={{ height:4, borderRadius:2, background:'var(--raised-2)', overflow:'hidden' }}>
                  <div style={{ width:'47%', height:'100%', background:'var(--acid)' }} /></div>
              </div>
            </>
          ) : card==='EARN YOUR FREEDOM' ? (
            <div style={{ margin:'auto 0' }}>
              <div className="display-xl" style={{ fontSize:40, color:'var(--bone)' }}>NO ONE<br/>IS COMING.</div>
              <div className="display-xl acid" style={{ fontSize:40, marginTop:6 }}>EARN YOUR<br/>FREEDOM.</div>
            </div>
          ) : (
            <>
              <div className="display-lg" style={{ fontSize:18, color:'var(--bone-muted)' }}>MISSION</div>
              <div className="display-xl" style={{ fontSize:38, color:'var(--bone)' }}>COMPLETE</div>
              <div style={{ marginTop:'auto' }}>
                <div style={{ fontFamily:'var(--display)', fontWeight:600, fontSize:16, marginBottom:10 }}>{F.today.title}</div>
                <MetricRow items={hideMetrics ? [['10.02 KM','DISTANCE'],['•••','AVG PACE'],['•••','TIME']] : [['10.02 KM','DISTANCE'],['4:58 /KM','AVG PACE'],['49:52','TIME']]} />
                <div className="label-mono" style={{ marginTop:12, color:'var(--steel)' }}>PROOF · {hideMetrics?'VERIFIED':'GARMIN FENIX 7'}</div>
              </div>
            </>
          )}
          <div className="row between" style={{ marginTop:16, borderTop:'1px solid var(--hairline)', paddingTop:12, display: fmt==='LINK'?'none':'flex' }}>
            <span className="label-mono">HARD THINGS DAILY</span><span className="label-mono acid">#PROVEIT</span></div>
        </div>

        <label className="row between" style={{ marginTop:16, padding:'4px 2px', cursor:'pointer' }}>
          <span className="label-mono" style={{ color:'var(--bone-muted)' }}>HIDE PRIVATE METRICS</span>
          <span onClick={()=>setHideMetrics(h=>!h)} style={{ width:42, height:24, borderRadius:12, background: hideMetrics?'var(--acid)':'var(--raised-2)',
            border:'1px solid var(--hairline-2)', position:'relative', transition:'background .15s' }}>
            <span style={{ position:'absolute', top:2, left: hideMetrics?20:2, width:18, height:18, borderRadius:'50%', background: hideMetrics?'#0a1400':'var(--steel)', transition:'left .15s' }} /></span>
        </label>

        <div className="row" style={{ gap:10, marginTop:14 }}>
          <button className="btn-ghost" onClick={()=>nav.push('ShareLanding')}>PREVIEW LINK LANDING · HTD.APP</button>
        </div>

        <SectionLabel>SHARE TO</SectionLabel>
        <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr 1fr', gap:9 }}>
          {targets.map(([l,ic])=>(
            <button key={l} onClick={()=>toast(l==='COPY LINK'?'LINK COPIED · HTD.APP/P/X92K4':l==='SAVE'?'SAVED TO PHOTOS · '+fmt:'SHARED TO '+l+' · '+fmt)} className="panel" style={{ padding:'14px 6px', display:'flex', flexDirection:'column', alignItems:'center', gap:7, cursor:'pointer' }}>
              <Icon name={ic} size={20} color="var(--bone-muted)" /><span className="label-mono">{l}</span></button>))}
        </div>
      </PushView>
    );
  }

  window.HTDMission = { MissionDetail, ActiveMission, ProofCapture, ProofIntegrity, RatingDebrief, MissionComplete, ShareStudio };
})();
