/* HTD Program 12 + 13 — Offline / Sync + Degraded states */
(function () {
  const { useState } = React;
  const Icon = window.HTDIcon;
  const { useNav, PushView, SectionLabel, Panel } = window.HTDUI;

  const SYNC_STAGES = ['ONLINE','OFFLINE CACHE','DRAFT CREATED','RECONNECTING','SYNCING','SYNC SUCCESS'];

  function OfflineSync() {
    const nav = useNav();
    const [offline, setOffline] = useState(true);
    const [stage, setStage] = useState(2);
    const queue = [
      ['Proof media', 'RUN 10K FASTED', 'upload'],
      ['Proof submit', 'RUN 10K FASTED', 'shieldCheck'],
      ['Completion', 'Debrief outcome', 'check'],
      ['Recommendation outcome', 'Learning signal', 'pulse'],
    ];
    const sync = () => { setStage(3); setTimeout(()=>setStage(4),500); setTimeout(()=>{setStage(5); setOffline(false);},1100); };
    return (
      <PushView title="OFFLINE & SYNC"
        footer={offline ? <button className="btn-primary" onClick={sync}>RECONNECT & SYNC<span className="sub">MEDIA → PROOF → COMPLETION → OUTCOME</span></button>
                        : <button className="btn-ghost" onClick={()=>{setOffline(true); setStage(2);}}>SIMULATE OFFLINE AGAIN</button>}>
        <Panel glow={!offline} style={{ marginTop:8, borderColor: offline?'rgba(255,195,7,0.5)':'var(--border-active)' }}>
          <div className="row between"><div className="row" style={{ gap:11 }}>
            <Icon name={offline?'alert':'check'} size={20} color={offline?'var(--amber)':'var(--acid)'} />
            <div><div style={{ fontFamily:'var(--display)', fontWeight:600, fontSize:16, color: offline?'var(--amber)':'var(--acid)' }}>{offline?'OFFLINE MODE':'SYNCED'}</div>
              <div className="label-mono" style={{ marginTop:2 }}>{offline?'CACHED MISSION AVAILABLE':'ALL DATA UP TO DATE'}</div></div></div>
            <span className="label-mono">{offline? (queue.length+' PENDING'):'0 PENDING'}</span></div>
        </Panel>

        <SectionLabel>SYNC STATE</SectionLabel>
        <Panel><div className="row" style={{ gap:4 }}>
          {SYNC_STAGES.map((s,i)=>(
            <div key={i} style={{ flex:1 }}>
              <div style={{ height:4, borderRadius:2, background: i<=stage?'var(--acid)':'var(--raised-2)' }} />
              <div className="label-mono" style={{ fontSize:6.5, marginTop:5, textAlign:'center', color: i===stage?'var(--acid)':'var(--steel)' }}>{s}</div></div>))}
        </div></Panel>

        <SectionLabel>RETRY QUEUE · ORDERED</SectionLabel>
        <Panel pad={false}>{queue.map(([l,sub,ic],i)=>{
          const synced = !offline;
          return (
            <div key={i} className="row between" style={{ padding:'13px 14px', borderBottom:i<queue.length-1?'1px solid var(--hairline)':'none' }}>
              <div className="row" style={{ gap:11 }}><Icon name={ic} size={16} color={synced?'var(--acid)':'var(--steel)'} />
                <div><div style={{ fontSize:13.5, color:'var(--bone)' }}>{l}</div><div className="label-mono" style={{ marginTop:1 }}>{sub}</div></div></div>
              <span className="label-mono" style={{ color: synced?'var(--acid)':'var(--amber)' }}>{synced?'● SYNCED':'○ QUEUED'}</span></div>);
        })}</Panel>
        <div className="muted" style={{ fontSize:12, marginTop:12, lineHeight:1.5, textAlign:'center' }}>
          Proof drafts are never lost. The queue replays in order on reconnect.</div>
        <button className="btn-ghost" style={{ marginTop:16 }} onClick={()=>nav.push('ErrorStates')}>VIEW RECOVERY STATES</button>
      </PushView>
    );
  }

  function ErrorStates() {
    const states = [
      ['API UNAVAILABLE','Backend unreachable. Showing cached data.','alert','var(--amber)','RETRY'],
      ['SESSION EXPIRED','Your session timed out. Log in to continue.','lock','var(--amber)','LOG IN'],
      ['PROVIDER MISSING','Wearable provider keys not yet configured.','watch','var(--steel)','USE MANUAL'],
      ['UPLOAD FAILED','Proof media failed to upload. Saved as draft.','upload','var(--danger)','RETRY UPLOAD'],
      ['PROOF REJECTED','Integrity check failed. Re-capture required.','x','var(--danger)','RE-CAPTURE'],
      ['CHALLENGE JOIN FAILED','Could not join. Try again shortly.','trophy','var(--danger)','RETRY'],
      ['ENTITLEMENT LOCKED','Premium feature requires an upgrade.','lock','var(--acid)','VIEW PLANS'],
    ];
    return (
      <PushView title="RECOVERY STATES">
        <div className="muted" style={{ fontSize:12.5, marginTop:10, lineHeight:1.5 }}>
          Every failure resolves to a polished, honest recovery state — never a blank screen.</div>
        <div style={{ marginTop:14, display:'flex', flexDirection:'column', gap:10 }}>
          {states.map(([t,d,ic,c,cta])=>(
            <Panel key={t}><div className="row between"><div className="row" style={{ gap:12 }}>
              <div style={{ width:38, height:38, borderRadius:9, background:'var(--raised-2)', border:'1px solid var(--hairline-2)', display:'grid', placeItems:'center', flex:'0 0 auto' }}>
                <Icon name={ic} size={18} color={c} /></div>
              <div><div style={{ fontFamily:'var(--display)', fontWeight:600, fontSize:14.5, letterSpacing:.3, color:c }}>{t}</div>
                <div className="muted" style={{ fontSize:12, marginTop:2, lineHeight:1.4 }}>{d}</div></div></div></div>
              <button onClick={()=>window.HTDUI.toast(t+' · '+cta+' · DEMO RESPONSE')} className="label-mono" style={{ marginTop:11, width:'100%', padding:'9px', borderRadius:6, cursor:'pointer',
                background:'transparent', border:'1px solid var(--hairline-2)', color:'var(--bone-muted)' }}>{cta}</button></Panel>))}
        </div>
      </PushView>
    );
  }

  window.HTDSystem = { OfflineSync, ErrorStates };
})();
