/* HTD Program 5 — Proof Network (Feed / Detail / Public Profile) */
(function () {
  const { useState } = React;
  const Icon = window.HTDIcon;
  const { useNav, PushView, SectionLabel, Panel, Segmented, Avatar, MetricRow, GPSMap, ConfPill } = window.HTDUI;
  const F = window.HTD_FIX;

  function MediaPreview({ post, height=120 }) {
    if (post.kind==='gps') return <GPSMap height={height} />;
    return (
      <div style={{ height, position:'relative', borderRadius:6, overflow:'hidden',
        background:'repeating-linear-gradient(135deg,#0c0f0b 0 8px,#0a0d0a 8px 16px)', display:'grid', placeItems:'center' }}>
        <Icon name={post.kind==='watch'?'watch':'droplet'} size={30} color="var(--steel)" />
        <div className="label-mono" style={{ position:'absolute', bottom:8, left:12 }}>{post.device}</div>
      </div>
    );
  }

  function ReactionRail({ post, onComment }) {
    const [liked, setLiked] = useState(false);
    const likes = post.likes + (liked?1:0);
    const Item = ({ic,n,on,onClick,fill}) => (
      <button onClick={onClick} className="row" style={{ gap:6, background:'none', border:'none', cursor:'pointer', padding:0,
        color: on?'var(--acid)':'var(--bone-muted)' }}>
        <Icon name={ic} size={18} color={on?'var(--acid)':'var(--bone-muted)'} fill={fill&&on?'var(--acid)':'none'} />
        <span className="num-mono" style={{ fontSize:12 }}>{n}</span></button>);
    return (
      <div className="row between" style={{ paddingTop:12, marginTop:12, borderTop:'1px solid var(--hairline)' }}>
        <div className="row" style={{ gap:22 }}>
          <Item ic="heart" n={likes} on={liked} fill onClick={()=>setLiked(l=>!l)} />
          <Item ic="comment" n={post.comments} onClick={onComment} />
          <Item ic="share" n={post.shares} onClick={()=>window.HTDUI.toast('PROOF LINK COPIED')} />
        </div>
        <button className="iconbtn" style={{ width:24, height:24 }}><Icon name="more" size={18} /></button>
      </div>
    );
  }

  function PostCard({ post }) {
    const nav = useNav();
    return (
      <div className="panel panel-pad" style={{ marginBottom:14 }}>
        <div className="row between" style={{ marginBottom:12 }}>
          <button className="row" style={{ gap:11, background:'none', border:'none', cursor:'pointer', padding:0 }} onClick={()=>nav.push('PublicProfile',{post})}>
            <Avatar color={post.avatar} label={post.user[0]} />
            <div style={{ textAlign:'left' }}>
              <div style={{ fontFamily:'var(--display)', fontWeight:600, fontSize:15, letterSpacing:.3 }}>{post.user}</div>
              <div className="label-mono">{post.handle}</div>
            </div>
          </button>
          <span className="label-mono">{post.ago}</span>
        </div>
        <button onClick={()=>nav.push('ProofDetail',{post})} style={{ display:'block', width:'100%', textAlign:'left', background:'none', border:'none', padding:0, cursor:'pointer' }}>
          <div className="display-lg" style={{ fontSize:20, marginBottom:12 }}>{post.mission}</div>
          <MetricRow items={post.metrics} />
          <div style={{ marginTop:13 }}><MediaPreview post={post} /></div>
          {post.avgHr!=='—' && <div className="row" style={{ gap:8, marginTop:9 }}>
            <span className="label-mono">AVG HR</span><span className="num-mono" style={{ fontSize:12, color:'var(--bone)' }}>{post.avgHr}</span></div>}
        </button>
        <ReactionRail post={post} onComment={()=>nav.push('ProofDetail',{post})} />
      </div>
    );
  }

  function StoryCard({ s }) {
    const nav = useNav();
    return (
      <div className="panel panel-pad" style={{ marginBottom:14, borderColor:'var(--border-active)', boxShadow:'0 0 20px -10px var(--acid-glow)' }}>
        <div className="label-mono acid" style={{ marginBottom:12 }}>■ TRANSFORMATION · HUMANS OF HTD</div>
        <image-slot id="story-marcus" placeholder="Drop Marcus's day-90 photo" shape="rounded" radius="8"
          style={{ display:'block', width:'100%', height:'150px', marginBottom:14 }}></image-slot>
        <div className="display-lg" style={{ fontSize:21, lineHeight:1.1 }}>{s.headline}</div>
        <div style={{ display:'flex', flexDirection:'column', gap:0, margin:'14px 0' }}>
          {s.arc.map(([d,what],i)=>(
            <div key={d} className="row" style={{ gap:12, alignItems:'stretch' }}>
              <div style={{ display:'flex', flexDirection:'column', alignItems:'center', width:14 }}>
                <span style={{ width:8, height:8, borderRadius:'50%', flex:'0 0 auto', marginTop:5,
                  background: i===s.arc.length-1?'var(--acid)':'var(--steel)', boxShadow: i===s.arc.length-1?'0 0 8px var(--acid)':'none' }} />
                {i<s.arc.length-1 && <span style={{ width:1, flex:1, background:'var(--hairline-2)' }} />}
              </div>
              <div style={{ paddingBottom: i<s.arc.length-1?14:0 }}>
                <div className="label-mono" style={{ color: i===s.arc.length-1?'var(--acid)':'var(--steel)' }}>{d}</div>
                <div style={{ fontFamily:'var(--ui)', fontWeight:600, fontSize:14.5, marginTop:2 }}>{what}</div>
              </div>
            </div>))}
        </div>
        <div style={{ padding:'12px 14px', borderLeft:'2px solid var(--acid)', background:'rgba(152,255,16,0.03)',
          fontStyle:'italic', fontSize:13.5, lineHeight:1.5, color:'var(--bone-muted)' }}>“{s.quote}”</div>
        <div className="row between" style={{ marginTop:13, paddingTop:12, borderTop:'1px solid var(--hairline)' }}>
          <div className="row" style={{ gap:9 }}>
            <Avatar color={s.avatar} label={s.name[0]} size={28} />
            <span style={{ fontFamily:'var(--display)', fontWeight:600, fontSize:13 }}>{s.name} · DAY {s.days}</span></div>
          <div className="row" style={{ gap:14 }}>
            <span className="label-mono acid">♥ {s.respect}</span>
            <button className="label-mono" onClick={()=>window.HTDUI.toast('STORY LINK COPIED · SEND IT TO SOMEONE WHO NEEDS IT')}
              style={{ background:'none', border:'1px solid var(--hairline-2)', borderRadius:5, padding:'6px 10px', cursor:'pointer', color:'var(--bone-muted)' }}>SHARE</button>
          </div>
        </div>
      </div>
    );
  }

  // tab-root Feed
  function ProofFeed({ tweaks }) {
    const nav = useNav();
    const [tab, setTab] = useState('ALL');
    if (tweaks && tweaks.emptyStates) return (
      <div className="screen-enter">
        <Segmented items={['ALL','FOLLOWING','CREW','TOP']} value={tab} onChange={setTab} style={{ paddingTop:6 }} />
        <div style={{ textAlign:'center', padding:'64px 30px 0' }}>
          <div style={{ width:60, height:60, borderRadius:14, margin:'0 auto 18px', border:'1px solid var(--hairline-2)', display:'grid', placeItems:'center' }}>
            <Icon name="feed" size={26} color="var(--steel)" /></div>
          <div className="display-lg" style={{ fontSize:22 }}>NO PROOF YET</div>
          <div className="muted" style={{ fontSize:13.5, marginTop:10, lineHeight:1.5 }}>The feed is earned, not scrolled. Complete today’s mission and your proof starts the record.</div>
          <button className="btn-primary" style={{ marginTop:22 }} onClick={()=>nav.go('home')}>START TODAY’S MISSION</button>
        </div>
      </div>
    );
    return (
      <div className="screen-enter">
        <div className="row between" style={{ position:'sticky', top:0, background:'var(--void)', zIndex:3, paddingTop:6 }}>
          <Segmented items={['ALL','FOLLOWING','CREW','TOP']} value={tab} onChange={setTab} style={{ padding:0 }} />
          <button onClick={()=>nav.push('ProofReels')} className="row" style={{ gap:6, height:30, padding:'0 12px', cursor:'pointer', flex:'0 0 auto',
            background:'rgba(152,255,16,0.08)', border:'1px solid var(--acid)', borderRadius:'var(--r-sm)',
            color:'var(--acid)', fontFamily:'var(--mono)', fontSize:10, letterSpacing:1.5 }}>▶ REELS</button>
        </div>
        <div style={{ marginTop:8 }}>
          <PostCard post={F.feed[0]} />
          <StoryCard s={F.stories[0]} />
          {F.feed.slice(1).map(p=><PostCard key={p.id} post={p} />)}
        </div>
        <div className="label-mono" style={{ textAlign:'center', padding:'8px 0 4px', color:'var(--steel)' }}>● END OF PROOF FEED</div>
      </div>
    );
  }

  // pushed Proof Detail
  function ProofDetail({ params }) {
    const nav = useNav(); const post = params.post;
    const toast = window.HTDUI.toast;
    const [comments, setComments] = useState(F.comments);
    const [draft, setDraft] = useState('');
    const submit = () => { if (!draft.trim()) return;
      setComments(c=>[...c, { user:'YOU', handle:'HARDCASE', avatar:'#3a4a2a', ago:'now', text:draft.trim() }]);
      setDraft(''); toast('RESPECT POSTED'); };
    const foot = (
      <div className="row" style={{ gap:10 }}>
        <input placeholder="Add to the standard…" value={draft} onChange={e=>setDraft(e.target.value)}
          onKeyDown={e=>e.key==='Enter'&&submit()}
          style={{ flex:1, height:46, background:'var(--panel)', border:'1px solid var(--hairline-2)',
          borderRadius:'var(--r)', color:'var(--bone)', fontFamily:'var(--ui)', fontSize:14, padding:'0 14px', outline:'none' }} />
        <button className="btn-primary" style={{ width:'auto', padding:'0 18px', fontSize:14 }} onClick={submit}>POST</button>
      </div>);
    return (
      <PushView title="PROOF" right={['more']} footer={foot}>
        <div className="row between" style={{ marginTop:8, marginBottom:14 }}>
          <button className="row" style={{ gap:11, background:'none', border:'none', cursor:'pointer', padding:0 }} onClick={()=>nav.push('PublicProfile',{post})}>
            <Avatar color={post.avatar} label={post.user[0]} />
            <div style={{ textAlign:'left' }}><div style={{ fontFamily:'var(--display)', fontWeight:600, fontSize:16 }}>{post.user}</div>
              <div className="label-mono">{post.handle} · {post.ago}</div></div>
          </button>
          <ConfPill level={post.conf} />
        </div>
        <div className="display-xl" style={{ fontSize:30, marginBottom:12 }}>{post.mission}</div>
        <Panel pad={false} style={{ overflow:'hidden' }}><MediaPreview post={post} height={170} /></Panel>
        <div style={{ marginTop:14 }}><MetricRow items={post.metrics} big /></div>
        <SectionLabel>PROOF SUMMARY</SectionLabel>
        <Panel><div className="row between"><span className="label-mono">DEVICE</span><span style={{ fontSize:13, color:'var(--bone)' }}>{post.device}</span></div>
          <div className="row between" style={{ marginTop:9 }}><span className="label-mono">AVG HR</span><span style={{ fontSize:13, color:'var(--bone)' }}>{post.avgHr}</span></div>
          <div className="row between" style={{ marginTop:9 }}><span className="label-mono">CONFIDENCE</span><ConfPill level={post.conf} /></div></Panel>
        <SectionLabel>RESPECT · {comments.length}</SectionLabel>
        {comments.map((c,i)=>(
          <div key={i} className="row" style={{ gap:11, padding:'11px 0', borderBottom:'1px solid var(--hairline)', alignItems:'flex-start' }}>
            <Avatar color={c.avatar} label={c.user[0]} size={32} />
            <div style={{ flex:1 }}><div className="row" style={{ gap:8, alignItems:'baseline' }}>
              <span style={{ fontFamily:'var(--display)', fontWeight:600, fontSize:13 }}>{c.user}</span><span className="label-mono">{c.ago}</span></div>
              <div style={{ fontSize:13.5, color:'var(--bone-muted)', marginTop:3, lineHeight:1.45 }}>{c.text}</div></div>
          </div>))}
        <button className="btn-ghost" style={{ marginTop:14, color:'var(--danger)', borderColor:'rgba(255,59,48,0.35)' }}
          onClick={()=>toast('REPORT SUBMITTED · MODERATION QUEUE')}>⚑ REPORT PROOF</button>
      </PushView>
    );
  }

  // pushed Public Profile
  function PublicProfile({ params }) {
    const nav = useNav(); const post = params.post;
    const [following, setFollowing] = useState(false);
    return (
      <PushView title={post.handle} right={['more']}>
        <div style={{ textAlign:'center', padding:'16px 0 6px' }}>
          <div style={{ display:'inline-block' }}><Avatar color={post.avatar} label={post.user[0]} size={76} /></div>
          <div className="display-lg" style={{ fontSize:24, marginTop:12 }}>{post.user}</div>
          <div className="label-mono">{post.handle}</div>
        </div>
        <Panel glow style={{ marginTop:8, textAlign:'center' }}>
          <div className="label-mono">RESILIENCE SCORE</div>
          <div style={{ fontFamily:'var(--display)', fontWeight:700, fontSize:44, color:'var(--acid)', lineHeight:1, marginTop:4 }}>814</div>
          <div className="label-mono acid">ELITE TIER</div>
        </Panel>
        <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr 1fr', gap:10, marginTop:12 }}>
          {[['128','PROOFS'],['3','CREWS'],['5','CHALLENGES']].map(([v,l])=>(
            <Panel key={l} style={{ textAlign:'center' }}><div style={{ fontFamily:'var(--display)', fontWeight:700, fontSize:24 }}>{v}</div>
              <div className="label-mono" style={{ marginTop:3 }}>{l}</div></Panel>))}
        </div>
        <div className="row" style={{ gap:10, marginTop:14 }}>
          <button className={following?'btn-ghost':'btn-primary'} style={following?{}:{fontSize:15}} onClick={()=>setFollowing(f=>!f)}>{following?'FOLLOWING':'FOLLOW'}</button>
          <button className="btn-ghost" style={{ width:'auto', padding:'0 18px' }} onClick={()=>window.HTDUI.toast('INVITE LINK COPIED')}>INVITE</button>
        </div>
        <SectionLabel>RECENT PROOFS</SectionLabel>
        {[post.mission,'COLD PLUNGE 5:00','BACK SQUAT 5×5'].map((m,i)=>(
          <div key={i} className="row between" style={{ padding:'13px 2px', borderBottom:'1px solid var(--hairline)' }}>
            <div className="row" style={{ gap:11 }}><Icon name="check" size={16} color="var(--acid)" />
              <span style={{ fontFamily:'var(--ui)', fontWeight:600, fontSize:14 }}>{m}</span></div>
            <span className="label-mono">{i===0?'2H':i+'D'}</span></div>))}
      </PushView>
    );
  }

  window.HTDFeed = { ProofFeed, ProofDetail, PublicProfile };
})();
