/* HTD Soul Layer — Manifesto, Identity Arc, Crew Check-in, Weekly Debrief, Referral */
(function () {
  const { useState, useEffect } = React;
  const Icon = window.HTDIcon;
  const { useNav, PushView, SectionLabel, Panel, Avatar, toast } = window.HTDUI;
  const { StatusBar } = window.HTDShell;
  const F = window.HTD_FIX;

  // ---------- MANIFESTO (cinematic open, phase between boot and intro) ----------
  function Manifesto() {
    const nav = useNav();
    const [i, setI] = useState(0);
    const lines = F.manifesto;
    const last = i === lines.length - 1;
    useEffect(() => {
      const t = setTimeout(() => { last ? nav.setPhase('intro') : setI(n => n + 1); }, 1500);
      return () => clearTimeout(t);
    }, [i]);
    return (
      <div onClick={() => last ? nav.setPhase('intro') : setI(n => n + 1)}
        style={{ position:'absolute', inset:0, background:'#000', display:'flex', flexDirection:'column',
          alignItems:'center', justifyContent:'center', cursor:'pointer', overflow:'hidden' }}>
        <div key={i} className="screen-enter" style={{ textAlign:'center', padding:'0 30px' }}>
          <div style={{ fontFamily:'var(--display)', fontWeight:700, fontSize:54, lineHeight:.95, whiteSpace:'pre-line',
            color: last ? 'var(--acid)' : 'var(--bone)', letterSpacing:1, textTransform:'uppercase',
            textShadow: last ? '0 0 50px var(--acid-glow)' : 'none' }}>{lines[i]}</div>
        </div>
        <div className="row" style={{ position:'absolute', bottom:52, gap:6 }}>
          {lines.map((_, j) => (
            <span key={j} style={{ width: j===i?18:6, height:3, borderRadius:2, background: j<=i?'var(--acid)':'var(--hairline-2)', transition:'width .2s' }} />))}
        </div>
        <button onClick={(e)=>{ e.stopPropagation(); nav.setPhase('intro'); }} className="label-mono"
          style={{ position:'absolute', top:58, right:20, background:'none', border:'none', cursor:'pointer', color:'var(--steel)', padding:8 }}>SKIP</button>
      </div>
    );
  }

  // ---------- IDENTITY ARC + RANK CEREMONY ----------
  function IdentityArc() {
    const nav = useNav(); const I = F.identity;
    return (
      <PushView title="IDENTITY ARC"
        footer={<button className="btn-primary" onClick={()=>nav.push('ShareStudio')}>SHARE YOUR RANK<span className="sub">{I.daysToNext} DAYS TO {I.next}</span></button>}>
        <div style={{ textAlign:'center', padding:'26px 0 8px' }} className="screen-enter">
          <div className="label-mono">YOU ARE</div>
          <div style={{ fontFamily:'var(--display)', fontWeight:700, fontSize:52, color:'var(--acid)', lineHeight:.95,
            margin:'10px 0', textShadow:'0 0 40px var(--acid-glow)' }}>{I.current}</div>
          <div className="muted" style={{ fontSize:13.5, fontStyle:'italic' }}>{I.creed}</div>
        </div>
        <SectionLabel>THE ARC · EARNED, NEVER GIVEN</SectionLabel>
        <Panel pad={false}>
          {I.ranks.map(([rank, req, earned], i) => {
            const current = rank === I.current;
            return (
              <div key={rank} className="row" style={{ gap:13, padding:'14px', borderBottom: i<I.ranks.length-1?'1px solid var(--hairline)':'none',
                background: current?'rgba(152,255,16,0.05)':'transparent' }}>
                <div style={{ width:34, height:34, borderRadius:'50%', display:'grid', placeItems:'center', flex:'0 0 auto',
                  border:'1px solid '+(earned?'var(--acid)':'var(--hairline-2)'),
                  boxShadow: current?'0 0 14px -2px var(--acid-glow)':'none' }}>
                  <Icon name={earned?'check':'lock'} size={15} color={earned?'var(--acid)':'var(--steel)'} />
                </div>
                <div style={{ flex:1 }}>
                  <div style={{ fontFamily:'var(--display)', fontWeight:700, fontSize:17, letterSpacing:.5,
                    color: current?'var(--acid)':earned?'var(--bone)':'var(--steel)' }}>{rank}</div>
                  <div className="label-mono" style={{ marginTop:2 }}>{req}</div>
                </div>
                {current && <span className="label-mono acid">CURRENT</span>}
              </div>);
          })}
        </Panel>
        <SectionLabel>NEXT THRESHOLD</SectionLabel>
        <Panel glow>
          <div className="row between">
            <div><div style={{ fontFamily:'var(--display)', fontWeight:700, fontSize:20 }}>{I.next}</div>
              <div className="label-mono" style={{ marginTop:3 }}>100 PROVEN DAYS · CEREMONY AWAITS</div></div>
            <div style={{ textAlign:'right' }}>
              <div style={{ fontFamily:'var(--display)', fontWeight:700, fontSize:26, color:'var(--acid)' }}>{F.identity.daysToNext}</div>
              <div className="label-mono">DAYS OUT</div></div>
          </div>
          <div style={{ height:6, borderRadius:3, background:'var(--raised-2)', marginTop:12, overflow:'hidden' }}>
            <div style={{ width:'82%', height:'100%', background:'var(--acid)' }} />
          </div>
        </Panel>
        <button className="btn-ghost" style={{ marginTop:14 }} onClick={()=>nav.push('RankCeremony')}>PREVIEW THE CEREMONY</button>
      </PushView>
    );
  }

  function RankCeremony() {
    const nav = useNav();
    return (
      <div className="pushview grid-bg" style={{ position:'absolute', inset:0, zIndex:50, background:'var(--void)',
        display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center', padding:'0 30px' }}>
        <button className="iconbtn" onClick={()=>nav.pop()} style={{ position:'absolute', top:58, right:14 }}><Icon name="x" size={20} /></button>
        <div className="screen-enter" style={{ textAlign:'center' }}>
          <div className="label-mono acid" style={{ letterSpacing:3 }}>DAY 100 · RANK CEREMONY</div>
          <div style={{ width:96, height:96, margin:'26px auto', borderRadius:'50%', display:'grid', placeItems:'center',
            border:'2px solid var(--acid)', boxShadow:'0 0 50px -6px var(--acid-glow)' }}>
            <Icon name="shield" size={42} color="var(--acid)" />
          </div>
          <div className="label-mono">YOU ARE NOW</div>
          <div style={{ fontFamily:'var(--display)', fontWeight:700, fontSize:56, color:'var(--acid)', lineHeight:.95,
            margin:'10px 0 14px', textShadow:'0 0 50px var(--acid-glow)' }}>UNBREAKABLE</div>
          <div className="muted" style={{ fontSize:14, lineHeight:1.6, maxWidth:280, margin:'0 auto' }}>
            100 days. 14 before dawn. 2 comebacks. Nothing was given.</div>
        </div>
        <div style={{ position:'absolute', bottom:44, left:20, right:20, zIndex:10 }}>
          <button className="btn-primary" onClick={()=>{ nav.pop(); nav.push('ShareStudio'); }}>SHARE THE CEREMONY<span className="sub">YOUR CREW GETS NOTIFIED</span></button>
        </div>
      </div>
    );
  }

  // ---------- CREW CHECK-IN THREAD ----------
  function CrewCheckin() {
    const [mine, setMine] = useState(null);
    const [backed, setBacked] = useState(false);
    const C = F.checkins;
    const states = { IN: ['var(--acid)', '● IN'], OUT: ['var(--steel)', '○ OUT'], STRUGGLING: ['var(--amber)', '▲ STRUGGLING'] };
    return (
      <PushView title="CREW CHECK-IN">
        <SectionLabel style={{ marginTop:8 }}>YOUR STATUS · TODAY</SectionLabel>
        <div className="row" style={{ gap:8 }}>
          {['IN','STRUGGLING','OUT'].map(s => (
            <button key={s} onClick={()=>{ setMine(s); toast(s==='STRUGGLING' ? 'CREW NOTIFIED · THEY’VE GOT YOU' : 'CHECKED IN · ' + s); }}
              style={{ flex:1, height:44, cursor:'pointer', borderRadius:'var(--r-sm)', fontFamily:'var(--mono)', fontSize:10.5, letterSpacing:1,
                background: mine===s?'rgba(152,255,16,0.08)':'var(--panel)',
                border:'1px solid '+(mine===s?(s==='STRUGGLING'?'var(--amber)':'var(--acid)'):'var(--hairline-2)'),
                color: mine===s?(s==='STRUGGLING'?'var(--amber)':'var(--acid)'):'var(--bone-muted)' }}>{s}</button>))}
        </div>
        <div className="label-mono" style={{ marginTop:10, color:'var(--steel)' }}>STRUGGLING PINGS THE CREW. NO SHAME IN THE SIGNAL.</div>

        <SectionLabel>TODAY'S THREAD · 9/12 IN</SectionLabel>
        <Panel pad={false}>
          {C.today.map(([name, col, st, note, ago], i) => (
            <div key={name} style={{ padding:'13px 14px', borderBottom:i<C.today.length-1?'1px solid var(--hairline)':'none',
              background: st==='STRUGGLING'?'rgba(255,195,7,0.04)':'transparent' }}>
              <div className="row between">
                <div className="row" style={{ gap:10 }}>
                  <Avatar color={col} label={name[0]} size={30} />
                  <span style={{ fontFamily:'var(--display)', fontWeight:600, fontSize:14, whiteSpace:'nowrap' }}>{name}</span>
                </div>
                <div className="row" style={{ gap:10 }}>
                  <span className="label-mono" style={{ color: states[st][0] }}>{states[st][1]}</span>
                  <span className="label-mono">{ago}</span>
                </div>
              </div>
              <div style={{ fontSize:13, color:'var(--bone-muted)', marginTop:7, paddingLeft:40 }}>{note}</div>
              {st==='STRUGGLING' && (
                <div className="row" style={{ gap:8, marginTop:10, paddingLeft:40 }}>
                  <button onClick={()=>{ setBacked(true); toast('MARCUS HAS YOUR BACK-UP · '+(C.backups+1)+' CREW IN'); }}
                    className="label-mono" style={{ padding:'8px 12px', borderRadius:6, cursor:'pointer',
                      background: backed?'rgba(152,255,16,0.08)':'transparent',
                      border:'1px solid '+(backed?'var(--acid)':'var(--amber)'), color: backed?'var(--acid)':'var(--amber)' }}>
                    {backed?'✓ BACKING HIM UP':'BACK HIM UP'}</button>
                  <span className="label-mono" style={{ alignSelf:'center' }}>{C.backups + (backed?1:0)} CREW RESPONDED</span>
                </div>)}
            </div>))}
        </Panel>
        <div className="label-mono" style={{ textAlign:'center', marginTop:14, color:'var(--steel)' }}>CHECK-INS RESET AT EACH DROP · 05:00</div>
      </PushView>
    );
  }

  // ---------- WEEKLY DEBRIEF (Claude-synthesized) ----------
  function WeeklyDebrief() {
    const nav = useNav(); const D = F.debrief;
    const [out, setOut] = useState(null);
    const [busy, setBusy] = useState(true);
    useEffect(() => {
      let dead = false;
      (async () => {
        try {
          const txt = await window.claude.complete(
            `You are the HTD Resilience Architect writing a weekly debrief for a discipline-training athlete. Voice: direct, short, specific, no markdown, no emoji, plain text. Week data: 6 of 7 missions proven; hardest was a fasted 10K on 6 hours sleep; one miss Tuesday (5:30AM session delayed to evening, third early-morning avoidance this month); readiness trending up (HRV +5); streak 18 days; crew completion 78%. Write EXACTLY three sections, each 1-2 sentences, separated by "|||": (1) what they proved, (2) the pattern they avoided, (3) next week's arc (keep difficulty 8.0, schedule two pre-7AM efforts).`);
          if (!dead && txt) {
            const parts = txt.split('|||').map(s => s.trim()).filter(Boolean);
            setOut(parts.length >= 3 ? { proved: parts[0], avoided: parts[1], arc: parts[2] } : D.fallback);
          } else if (!dead) setOut(D.fallback);
        } catch (e) { if (!dead) setOut(D.fallback); }
        if (!dead) setBusy(false);
      })();
      return () => { dead = true; };
    }, []);
    const Section = ({ label, color, text }) => (
      <Panel style={{ marginBottom:10, borderColor: color==='var(--amber)'?'rgba(255,195,7,0.35)':undefined }}>
        <div className="label-mono" style={{ color, marginBottom:8 }}>{label}</div>
        <div style={{ fontSize:13.5, lineHeight:1.55, color:'var(--bone)' }}>{text}</div>
      </Panel>);
    return (
      <PushView title="WEEKLY DEBRIEF"
        footer={<button className="btn-primary" onClick={()=>{ nav.pop(); }}>ACCEPT NEXT WEEK'S ARC<span className="sub">TWO PRE-DAWN EFFORTS · NO NEGOTIATION</span></button>}>
        <div className="row between" style={{ marginTop:8, marginBottom:14 }}>
          <div><div className="label-mono acid">{D.week} · SUNDAY RITUAL</div>
            <div className="display-lg" style={{ fontSize:24, marginTop:5 }}>THE DEBRIEF</div></div>
          <span className="label-mono" style={{ display:'flex', alignItems:'center', gap:6, color: busy?'var(--amber)':'var(--acid)' }}>
            <span style={{ width:7, height:7, borderRadius:'50%', background: busy?'var(--amber)':'var(--acid)', boxShadow:'0 0 7px currentColor' }} />
            {busy?'SYNTHESIZING':'AI SYNTHESIS'}</span>
        </div>
        {busy ? (
          <div>
            <div className="skel" style={{ height:84 }} />
            <div className="skel" style={{ height:84, marginTop:10 }} />
            <div className="skel" style={{ height:84, marginTop:10 }} />
          </div>
        ) : (
          <div className="screen-enter">
            <Section label="WHAT YOU PROVED" color="var(--acid)" text={out.proved} />
            <Section label="WHAT YOU AVOIDED" color="var(--amber)" text={out.avoided} />
            <Section label="NEXT WEEK'S ARC" color="var(--bone-muted)" text={out.arc} />
          </div>
        )}
        <div className="row" style={{ gap:10, marginTop:6 }}>
          <Panel style={{ flex:1, textAlign:'center' }}><div style={{ fontFamily:'var(--display)', fontWeight:700, fontSize:22, color:'var(--acid)' }}>6/7</div>
            <div className="label-mono" style={{ marginTop:3 }}>PROVEN</div></Panel>
          <Panel style={{ flex:1, textAlign:'center' }}><div style={{ fontFamily:'var(--display)', fontWeight:700, fontSize:22 }}>+42</div>
            <div className="label-mono" style={{ marginTop:3 }}>SCORE</div></Panel>
          <Panel style={{ flex:1, textAlign:'center' }}><div style={{ fontFamily:'var(--display)', fontWeight:700, fontSize:22, color:'var(--amber)' }}>1</div>
            <div className="label-mono" style={{ marginTop:3 }}>AVOIDED</div></Panel>
        </div>
      </PushView>
    );
  }

  // ---------- REFERRAL ----------
  function Referral() {
    const R = F.referral;
    return (
      <PushView title="BUILD THE STANDARD"
        footer={<button className="btn-primary" onClick={()=>toast('INVITE LINK COPIED · HTD.APP/J/'+R.code)}>COPY INVITE LINK<span className="sub">HTD.APP/J/{R.code}</span></button>}>
        <div style={{ textAlign:'center', padding:'22px 0 6px' }}>
          <div className="label-mono acid" style={{ letterSpacing:3 }}>INVITE 3 · EARN A SHIELD</div>
          <div className="display-xl" style={{ fontSize:30, margin:'10px 0' }}>DISCIPLINE IS<br/>CONTAGIOUS.</div>
          <div className="muted" style={{ fontSize:13 }}>{R.reward}</div>
        </div>
        <SectionLabel>YOUR THREE</SectionLabel>
        <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr 1fr', gap:10 }}>
          {R.invited.map(([name, st], i) => (
            <Panel key={i} style={{ textAlign:'center', padding:'16px 6px', borderColor: name?'var(--border-active)':'var(--hairline)',
              borderStyle: name?'solid':'dashed' }}>
              {name
                ? <><Icon name="check" size={18} color="var(--acid)" />
                    <div className="label-mono" style={{ marginTop:8, color:'var(--bone)' }}>{name}</div>
                    <div className="label-mono acid" style={{ marginTop:3, fontSize:7.5 }}>{st}</div></>
                : <><Icon name="plus" size={18} color="var(--steel)" />
                    <div className="label-mono" style={{ marginTop:8 }}>OPEN SLOT</div></>}
            </Panel>))}
        </div>
        <SectionLabel>PROGRESS</SectionLabel>
        <Panel glow>
          <div className="row between" style={{ marginBottom:10 }}>
            <span className="label-mono" style={{ color:'var(--bone)' }}>1 / 3 JOINED</span>
            <span className="label-mono acid">⛨ SHIELD AT 3</span></div>
          <div style={{ height:7, borderRadius:4, background:'var(--raised-2)', overflow:'hidden' }}>
            <div style={{ width:'33%', height:'100%', background:'var(--acid)' }} /></div>
        </Panel>
        <div className="row between panel panel-pad" style={{ marginTop:12 }}>
          <span className="label-mono">LIFETIME ATHLETES RECRUITED</span>
          <span style={{ fontFamily:'var(--display)', fontWeight:700, fontSize:20, color:'var(--acid)' }}>{R.lifetime}</span>
        </div>
      </PushView>
    );
  }

  window.HTDSoul = { Manifesto, IdentityArc, RankCeremony, CrewCheckin, WeeklyDebrief, Referral };
})();
