/* HTD Loop Closers — Failure Review, Comeback Protocol, Calendar, Activity Library */
(function () {
  const { useState } = React;
  const Icon = window.HTDIcon;
  const { useNav, PushView, SectionLabel, Panel, ConfPill } = window.HTDUI;
  const F = window.HTD_FIX;

  // ---------- FAILURE REVIEW (spec 27) ----------
  function FailureReview() {
    const nav = useNav();
    const [reason, setReason] = useState('AVOIDANCE');
    const fl = F.failure;
    const foot = (
      <div style={{ display:'flex', flexDirection:'column', gap:10 }}>
        <button className="btn-primary" onClick={()=>nav.push('ComebackProtocol')}>RUN COMEBACK PROTOCOL<span className="sub">MISSED DOES NOT MEAN DONE</span></button>
        <div className="row" style={{ gap:10 }}>
          <button className="btn-ghost" onClick={()=>nav.pop()}>RESCHEDULE</button>
          <button className="btn-ghost" onClick={()=>nav.pop()}>SCALE FUTURE</button>
        </div>
      </div>);
    return (
      <PushView title="FAILURE REVIEW" footer={foot}>
        <Panel style={{ marginTop:10, borderColor:'rgba(255,59,48,0.4)' }}>
          <div className="row between">
            <div><div className="label-mono danger-c">MISSED MISSION</div>
              <div style={{ fontFamily:'var(--display)', fontWeight:700, fontSize:22, marginTop:5 }}>{fl.missed.title}</div>
              <div className="label-mono" style={{ marginTop:3 }}>{fl.missed.when} · {fl.missed.category}</div></div>
            <Icon name="x" size={26} color="var(--danger)" />
          </div>
        </Panel>
        <SectionLabel>WHAT GOT IN THE WAY?</SectionLabel>
        <div className="row" style={{ flexWrap:'wrap', gap:8 }}>
          {fl.reasons.map(r=>(
            <button key={r} onClick={()=>setReason(r)} className="label-mono" style={{ padding:'9px 13px', borderRadius:6, cursor:'pointer',
              background: reason===r?'rgba(255,59,48,0.08)':'var(--panel)', border:'1px solid '+(reason===r?'var(--danger)':'var(--hairline-2)'),
              color: reason===r?'var(--danger)':'var(--bone-muted)' }}>{r}</button>))}
        </div>
        <SectionLabel>FRICTION PATTERN</SectionLabel>
        <Panel><div className="row" style={{ gap:11, alignItems:'flex-start' }}>
          <Icon name="pulse" size={17} color="var(--amber)" style={{ marginTop:2 }} />
          <div className="muted" style={{ fontSize:13, lineHeight:1.5 }}>{fl.pattern}</div></div></Panel>
        <SectionLabel>NOTE · OPTIONAL</SectionLabel>
        <textarea placeholder="What would have made this happen?" rows={2}
          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:10, color:'var(--steel)' }}>↳ FEEDS AVOIDANCE PATTERN DETECTION</div>
      </PushView>
    );
  }

  // ---------- COMEBACK PROTOCOL (spec 28) ----------
  function ComebackProtocol() {
    const nav = useNav();
    const c = F.failure.comeback;
    const foot = (
      <div style={{ display:'flex', flexDirection:'column', gap:10 }}>
        <button className="btn-primary" onClick={()=>{ nav.popToRoot(); nav.push('ActiveMission'); }}>START COMEBACK<span className="sub">REPAIR THE CHAIN</span></button>
        <button className="btn-ghost" onClick={()=>nav.pop()}>SCALE DOWN FURTHER</button>
      </div>);
    return (
      <PushView title="COMEBACK PROTOCOL" footer={foot}>
        <div className="label-mono acid" style={{ marginTop:10, letterSpacing:3 }}>COMEBACK MISSION</div>
        <div className="display-xl" style={{ fontSize:30, margin:'8px 0 6px' }}>{c.title}</div>
        <div className="muted" style={{ fontSize:13.5 }}>{c.sub}</div>
        <div className="row between panel panel-pad" style={{ marginTop:16 }}>
          <div><div className="label-mono">DURATION</div><div style={{ fontFamily:'var(--display)', fontWeight:600, fontSize:17, marginTop:2 }}>{c.duration}</div></div>
          <div><div className="label-mono">DIFFICULTY</div><div style={{ fontFamily:'var(--display)', fontWeight:600, fontSize:17, marginTop:2, color:'var(--acid)' }}>{c.difficulty.toFixed(1)}/10</div></div>
          <div><div className="label-mono">PROOF</div><div style={{ fontFamily:'var(--display)', fontWeight:600, fontSize:17, marginTop:2 }}>{c.proof}</div></div>
        </div>
        <SectionLabel>WHY EASIER</SectionLabel>
        <Panel glow><div className="muted" style={{ fontSize:13, lineHeight:1.55 }}>{c.why}</div></Panel>
        <SectionLabel>STREAK REPAIR RULES</SectionLabel>
        <Panel pad={false}>{c.rules.map((r,i)=>(
          <div key={i} className="row" style={{ gap:10, padding:'12px 14px', borderBottom:i<c.rules.length-1?'1px solid var(--hairline)':'none' }}>
            <Icon name={i===2?'alert':'check'} size={15} color={i===2?'var(--danger)':'var(--acid)'} />
            <span style={{ fontSize:13.5, color:'var(--bone-muted)' }}>{r}</span></div>))}</Panel>
        <SectionLabel>CREW PRESSURE</SectionLabel>
        <Panel><div className="row between">
          <div className="muted" style={{ fontSize:13 }}>9 / 12 IRONCROWN completed today.</div>
          <button className="label-mono acid" style={{ background:'none', border:'1px solid var(--border-active)', borderRadius:6, padding:'7px 11px', cursor:'pointer' }}
            onClick={()=>window.HTDUI.toast('CREW NUDGE ARMED · THEY’LL SEE YOUR COMEBACK')}>NUDGE ME</button>
        </div></Panel>
      </PushView>
    );
  }

  // ---------- CALENDAR HEATMAP (spec 17) ----------
  function CalendarHeatmap() {
    const [cat, setCat] = useState('ALL');
    const [sel, setSel] = useState(null);
    const M = F.calendarMeta;
    return (
      <PushView title="MISSION CALENDAR" right={['share']}>
        <div className="row between" style={{ marginTop:8 }}>
          <span className="display-lg" style={{ fontSize:20 }}>{M.month}</span>
          <div className="row" style={{ gap:14 }}>
            {[['COMPLETE','complete'],['PARTIAL','partial'],['MISSED','missed']].map(([l,c])=>(
              <span key={l} className="label-mono" style={{ display:'flex', alignItems:'center', gap:5 }}>
                <span className={'cal-cell '+c} style={{ width:9, height:9, borderRadius:2 }} />{l}</span>))}
          </div>
        </div>
        <div className="seg" style={{ flexWrap:'wrap', marginTop:10 }}>
          {M.categories.map(c=>(
            <button key={c} className={'seg-item'+(cat===c?' active':'')} onClick={()=>setCat(c)}>{c}</button>))}
        </div>
        <Panel style={{ marginTop:12 }}>
          <div className="cal-grid" style={{ marginBottom:5 }}>
            {['M','T','W','T','F','S','S'].map((d,i)=><div key={i} className="cal-head">{d}</div>)}
          </div>
          {F.calendar.map((week,wi)=>(
            <div key={wi} className="cal-grid" style={{ marginBottom:4 }}>
              {week.map(([num,cls],di)=>(
                <button key={di} onClick={()=>setSel(num?wi+'-'+di:null)}
                  className={'cal-cell '+cls} style={{ border: sel===wi+'-'+di?'2px solid var(--bone)':'none', cursor:'pointer' }}>{num}</button>))}
            </div>))}
        </Panel>
        {sel && (
          <Panel glow style={{ marginTop:12 }} key={sel}>
            <div className="row between"><span className="label-mono" style={{ color:'var(--bone)' }}>{M.dayDetail.day}</span><ConfPill level={M.dayDetail.conf} /></div>
            <div style={{ fontFamily:'var(--display)', fontWeight:700, fontSize:19, marginTop:7 }}>{M.dayDetail.mission}</div>
            <div className="row" style={{ gap:16, marginTop:8 }}>
              <span className="label-mono acid">{M.dayDetail.status}</span>
              <span className="label-mono">{M.dayDetail.proof}</span>
              <span className="label-mono acid">{M.dayDetail.score}</span>
            </div>
          </Panel>)}
        {!sel && <div className="label-mono" style={{ textAlign:'center', marginTop:12, color:'var(--steel)' }}>TAP A DAY FOR DETAIL</div>}
        <SectionLabel>MONTH STATS</SectionLabel>
        <div style={{ display:'grid', gridTemplateColumns:'repeat(4,1fr)', gap:8 }}>
          {M.stats.map(([v,l])=>(
            <Panel key={l} style={{ textAlign:'center', padding:'12px 4px' }}>
              <div style={{ fontFamily:'var(--display)', fontWeight:700, fontSize:20, color: l==='MISSED'?'var(--danger)':'var(--bone)' }}>{v}</div>
              <div className="label-mono" style={{ marginTop:3, fontSize:8 }}>{l}</div></Panel>))}
        </div>
      </PushView>
    );
  }

  // ---------- ACTIVITY LIBRARY (spec 25) ----------
  function ActivityLibrary() {
    const nav = useNav();
    const [cat, setCat] = useState('ALL');
    const acts = F.activities.filter(a=>cat==='ALL'||a.cat===cat);
    return (
      <PushView title="ACTIVITY LIBRARY">
        <div className="seg" style={{ flexWrap:'wrap', marginTop:8 }}>
          {['ALL','ENDURANCE','STRENGTH','MENTAL','RECOVERY'].map(c=>(
            <button key={c} className={'seg-item'+(cat===c?' active':'')} onClick={()=>setCat(c)}>{c}</button>))}
        </div>
        <Panel pad={false} style={{ marginTop:12 }}>
          {acts.map((a,i)=>(
            <button key={a.name} onClick={()=>nav.push('ProtocolDetail')} className="row between"
              style={{ width:'100%', padding:'13px 14px', background:'none', border:'none', textAlign:'left', cursor:'pointer',
                borderBottom:i<acts.length-1?'1px solid var(--hairline)':'none' }}>
              <div className="row" style={{ gap:11 }}>
                <Icon name={a.cat==='MENTAL'?'spark':a.cat==='RECOVERY'?'droplet':a.cat==='STRENGTH'?'zap':'pulse'} size={17}
                  color={a.safety==='OPT-IN'?'var(--amber)':'var(--acid)'} />
                <div><div style={{ fontFamily:'var(--ui)', fontWeight:600, fontSize:14.5, color:'var(--bone)' }}>{a.name}</div>
                  <div className="label-mono" style={{ marginTop:2 }}>{a.cat} · {a.dur} · {a.equip}{a.safety==='OPT-IN'?' · OPT-IN':''}</div></div></div>
              <span className="num-mono" style={{ fontSize:12, color: a.diff>=7?'var(--danger)':'var(--bone-muted)' }}>{a.diff.toFixed(1)}</span>
            </button>))}
        </Panel>
        <button className="btn-ghost" style={{ marginTop:14 }} onClick={()=>window.HTDUI.toast('REQUEST LOGGED · SHAPES THE CATALOG')}>REQUEST A MISSION TYPE</button>
      </PushView>
    );
  }

  window.HTDLoop = { FailureReview, ComebackProtocol, CalendarHeatmap, ActivityLibrary };
})();
