// tab-today.jsx — briefing · Top3 + quick todos · checkable blocks · due actions · scoreboard
const { useState } = React;
const TS = window.RaiseShell;

const BLOCKS = [];

// Non-sequence items (master plan) blended in after the live sequence touches.
const PLAN_SEED = [];

// Mini progress toward the call goal, with the next touch's channel.
function SeqState({ d }){
  const ChTag = window.OXBits && window.OXBits.ChTag;
  const pct = Math.round(d.stepNum/d.stepTotal*100);
  return (
    <div className="seqstate">
      {ChTag && <ChTag id={d.ch} />}
      <span className="ss-lbl">Step {d.stepNum}/{d.stepTotal}</span>
      <span className="track"><i style={{width:pct+'%', background:d.status==='over'?'var(--rose)':d.status==='quiet'?'var(--amber)':'var(--primary)'}} /></span>
      <span className="ss-goal" title={d.goal}>◎</span>
    </div>
  );
}

function fireAt(e, big){ const r=e.currentTarget.getBoundingClientRect(); TS.celebrate(r.left+r.width/2, r.top+r.height/2, big); }

function TabToday({ go }){
  const R = window.RAISE;
  const Store = window.RaiseStore;
  const todos = TS.useTodos();
  const myTodos = todos.filter(t=>t.flagged);
  const TOP3 = window.BRAIN ? window.BRAIN.topFocus() : [];
  const brainBrief = window.BRAIN ? window.BRAIN.brief() : '';
  const plan = window.BRAIN ? window.BRAIN.planFocus() : { tasks:[], week:1, total:0, doneCount:0, source:'seed' };
  const RLD = window.RaiseLiveData;
  const togglePlan = (t,e)=>{
    if(plan.source!=='live' || !RLD){ TS.toast('Switch to Live mode in Settings to track plan progress'); return; }
    if(!t.done && e) fireAt(e);
    RLD.setPlanDone(t.id, !t.done)
      .then(()=>{ if(!t.done) TS.toast('Plan task done ✓'); })
      .catch(()=>TS.toast('Could not save — check connection'));
  };
  const toggleSub = (t,s,e)=>{
    if(plan.source!=='live' || !RLD){ TS.toast('Switch to Live mode in Settings to track plan progress'); return; }
    if(!s.done && e) fireAt(e);
    RLD.setSubtaskDone(t.id, s.id, !s.done)
      .catch(()=>TS.toast('Could not save — check connection'));
  };
  const breakDown = (t)=>{
    if(plan.source!=='live' || !RLD){ TS.toast('Sign in to use AI breakdown'); return; }
    RLD.requestBreakdown(t.id)
      .then(()=>TS.toast('Queued — the Brain is generating sub-steps'))
      .catch(()=>TS.toast('Could not queue — check connection'));
  };
  const [draft, setDraft] = useState('');
  const [blocks, setBlocks] = useState(()=>BLOCKS.map(b=>({label:b[1],sub:b[2],time:b[0],dur:b[3],now:b[4],done:false})));
  const [due, setDue] = useState(()=>[...window.OX.liveSteps(), ...PLAN_SEED]);
  const overdueN = due.filter(d=>d.status==='over').length;
  const liveN = due.filter(d=>!d.plan).length;

  const draftFor = (d)=>{
    localStorage.setItem('raiseos.outreach.view','coach');
    localStorage.setItem('raiseos.outreach.composeFor', d.pid);
    localStorage.setItem('raiseos.outreach.composeChannel', d.ch||'email');
    go('outreach');
  };

  const toggleBlock = (i,e)=>{
    setBlocks(bs=>{
      const next = bs.map((b,j)=> j===i?{...b,done:!b.done}:b);
      if(!bs[i].done){ fireAt(e); if(next.every(b=>b.done)){ setTimeout(()=>{ TS.celebrate(window.innerWidth/2, window.innerHeight/2, true); TS.toast('Day cleared — every block done! 🎉'); },150); } }
      return next;
    });
  };
  const addTodo = ()=>{ if(!draft.trim())return; Store.add({ text:draft.trim(), flagged:true, listId:'l-raise' }); setDraft(''); };
  const checkTodo = (id,doneNow,e)=>{ if(!doneNow) fireAt(e); Store.complete(id); };
  const dueAction = (id,kind,e)=>{
    if(kind==='done'){ fireAt(e); TS.toast('Logged ✓ — activity recorded'); }
    if(kind==='snooze') TS.toast('Snoozed to tomorrow');
    if(kind==='delete') TS.toast('Removed from today');
    setDue(d=>d.filter(x=>x.id!==id));
  };

  const doneBlocks = blocks.filter(b=>b.done).length;

  return (
    <>
      <TS.TopBar title="Good morning, Austin" sub="Thu · Jun 12 2026 · Week 1 of 26">
        <div className="qpill">Touches <b>3/5</b></div>
        <div className="qpill">Follow-ups <b>2/3</b></div>
        <div className="qpill acc">Meetings <b>1/1</b></div>
      </TS.TopBar>

      <div className="today">
        {/* ── col 1 ── */}
        <div className="tcol scroll">
          <TS.Card title="Morning brief" tag="Brain · 7:02 AM">
            <p className="brief" dangerouslySetInnerHTML={{__html: brainBrief}} />
          </TS.Card>

          <TS.Card title="Top 3 today" tag="Brain · plan − gap">
            <div className="t3">
              {TOP3.map((x,i)=>(
                <div key={i} className={'row'+(x.due?' due':'')} onClick={()=>go(x.to)}>
                  <div className="n">{i+1}</div>
                  <div style={{minWidth:0}}>
                    <div className="tx">{x.t}</div>
                    <div className="mt">{x.m}</div>
                    {x.pid && <div style={{marginTop:7}}><TS.PersonChip id={x.pid} /></div>}
                  </div>
                </div>
              ))}
            </div>

            <div className="mytodos">
              <div className="mth">
                <span>Your to-dos</span>
                <button className="linkbtn" onClick={()=>go('todos')}>Open To-Dos →</button>
              </div>
              <div className="addrow">
                <input className="addinp" placeholder="Add a quick to-do…" value={draft}
                       onChange={e=>setDraft(e.target.value)} onKeyDown={e=>e.key==='Enter'&&addTodo()} />
                <button className="btn primary sm" onClick={addTodo}>Add</button>
              </div>
              {myTodos.length===0 && <div className="muted" style={{fontSize:12,padding:'4px 2px'}}>Nothing yet — add your own alongside the system priorities.</div>}
              {myTodos.map(t=>(
                <div key={t.id} className={'mtitem'+(t.done?' done':'')}>
                  <button className={'mcheck'+(t.done?' on':'')} onClick={e=>checkTodo(t.id,t.done,e)}>{t.done&&'✓'}</button>
                  <span className="mtt">{t.text}</span>
                  {t.reminder && <span className="rmd mono">⏰ {t.reminder}</span>}
                  <button className="xbtn" onClick={()=>Store.remove(t.id)}>✕</button>
                </div>
              ))}
            </div>
          </TS.Card>

          <TS.Card title="This week's plan" tag={`Week ${plan.week} · ${plan.doneCount}/${plan.total} done`}>
            <div className="planlane">
              {plan.tasks.length===0 && <div className="muted" style={{fontSize:12,padding:'4px 2px'}}>No plan tasks scheduled for this week.</div>}
              {plan.tasks.map(t=>(
                <div key={t.id}>
                  <div className={'mtitem'+(t.done?' done':'')}>
                    <button className={'mcheck'+(t.done?' on':'')} onClick={e=>togglePlan(t,e)}>{t.done&&'✓'}</button>
                    <span className="mtt">{t.title}</span>
                    {t.subs && t.subs.length>0
                      ? <span className="mono" style={{marginLeft:'auto',fontSize:11,color:'var(--ink-3)'}}>{t.subs.filter(s=>s.done).length}/{t.subs.length}</span>
                      : plan.source==='live' && (t.pending
                          ? <span style={{marginLeft:'auto',fontSize:11,color:'var(--primary)'}}>Generating…</span>
                          : <button className="linkbtn" style={{marginLeft:'auto',whiteSpace:'nowrap'}} onClick={()=>breakDown(t)}>✨ Break down</button>)}
                  </div>
                  {t.subs && t.subs.map(s=>(
                    <div key={s.id} className={'mtitem sub'+(s.done?' done':'')} style={{marginLeft:24}}>
                      <button className={'mcheck'+(s.done?' on':'')} onClick={e=>toggleSub(t,s,e)}>{s.done&&'✓'}</button>
                      <span className="mtt" style={{fontSize:13}}>{s.title}</span>
                    </div>
                  ))}
                </div>
              ))}
              {plan.source!=='live' && <div className="muted" style={{fontSize:11,padding:'6px 2px 0'}}>Preview from seed plan — switch to Live mode in Settings to load your real plan and save progress.</div>}
            </div>
          </TS.Card>
        </div>

        {/* ── col 2 ── */}
        <div className="tcol scroll">
          <TS.Card title="Today's blocks" tag={`${doneBlocks}/${blocks.length} · soft blocks`}>
            <div className="blocks">
              {blocks.map((b,i)=>(
                <div key={i} className={'blk2'+(b.now?' now':'')+(b.done?' done':'')}>
                  <button className={'bcheck'+(b.done?' on':'')} onClick={e=>toggleBlock(i,e)}>{b.done&&'✓'}</button>
                  <div className="btime mono">{b.time}</div>
                  <div className="bmid">
                    <div className="bt2">{b.label}</div>
                    <div className="bs">{b.sub}</div>
                  </div>
                  <span className="dur mono">{b.dur}</span>
                </div>
              ))}
            </div>
            <div className="blocknote">Soft blocks — guides your day, not synced to your calendar.</div>
          </TS.Card>

          {/* combined scoreboard */}
          <TS.Card title="Scoreboard" tag="Day · week · capital">
            <div className="sb">
              <div className="sbrow">
                <div className="ring" style={{background:`conic-gradient(var(--primary) 0 0%, var(--surface-3) 0% 100%)`}}>
                  <div className="inner"><b className="mono">0</b><small>/100</small></div>
                </div>
                <div className="sbmeta">
                  <div className="sblab">Day score</div>
                  <div className="muted" style={{fontSize:12,lineHeight:1.5}}>Quotas <b style={{color:'var(--ink)'}}>0%</b> · no activity logged yet</div>
                </div>
              </div>
              <div className="sbdiv"/>
              <div className="sblab">Weekly quotas</div>
              <div className="q" style={{marginTop:8}}>
                {R.quotas.weekly.map((x,i)=>(
                  <div key={i} className="qrow">
                    <span className="ql">{x.k}</span>
                    <span className="track"><i style={{width:Math.min(100,x.v/x.of*100)+'%',background:x.v>=x.of?'var(--green)':'var(--primary)'}}/></span>
                    <span className="qn">{x.v}/{x.of}</span>
                  </div>
                ))}
              </div>
              <div className="sbdiv"/>
              <div className="sblab">Capital raised <span className="muted">vs $10M</span></div>
              <div style={{display:'flex',alignItems:'baseline',gap:8,margin:'8px 0 8px'}}>
                <b className="mono" style={{fontSize:24,fontWeight:600}}>{TS.money(R.capital.wired)}</b>
                <span className="mono" style={{fontSize:12,color:'var(--ink-3)'}}>wired · {(R.capital.wired/R.capital.target*100).toFixed(1)}%</span>
              </div>
              <span className="track" style={{height:9}}><i style={{width:R.capital.wired/R.capital.target*100+'%',background:'var(--green)'}}/></span>
              <div style={{display:'flex',justifyContent:'space-between',marginTop:8,fontSize:11,color:'var(--ink-3)'}} className="mono">
                <span>Soft pipeline {TS.money(R.capital.soft)}</span><span>{R.capital.coverage.toFixed(1)}× coverage</span>
              </div>
            </div>
          </TS.Card>
        </div>

        {/* ── col 3 ── */}
        <div className="tcol scroll">
          <TS.Card title="Due actions" tag={`${liveN} live touch${liveN===1?'':'es'} · ${overdueN} overdue`}>
            <div className="dueq">
              {due.map(d=>(
                <div key={d.id} className="dueitem">
                  <div className="dtop">
                    <button className="dperson" onClick={()=>d.pid && Store.openPerson(d.pid)} disabled={!d.pid}>
                      <TS.Avatar name={d.name} anchor={d.anchor} />
                      <div className="dmid">
                        <div className="dn">{d.name}</div>
                        <div className="da">{d.stepLabel}</div>
                      </div>
                    </button>
                    <span className={'chip '+d.status}>{d.statusLabel}</span>
                  </div>
                  {!d.plan && <SeqState d={d} />}
                  <div className="dbot">
                    <span className={'srctag'+(d.plan?'':' manual')}>{d.plan ? d.seqName : d.seqId+' · '+d.seqName}</span>
                    <div className="dbtns">
                      {!d.plan && <button className="dbtn draft" title="Draft this touch in the Composer" onClick={()=>draftFor(d)}>Draft →</button>}
                      <button className="dbtn done" title="Mark done" onClick={e=>dueAction(d.id,'done',e)}>✓ Done</button>
                      <button className="dbtn" title="Snooze to tomorrow" onClick={e=>dueAction(d.id,'snooze',e)}>Snooze</button>
                      <button className="dbtn x" title="Delete" onClick={e=>dueAction(d.id,'delete',e)}>✕</button>
                    </div>
                  </div>
                </div>
              ))}
              {due.length===0 && <div className="muted" style={{fontSize:13,textAlign:'center',padding:'18px 0'}}>All clear — every due action handled. 🎉</div>}
            </div>
            <div className="blocknote">Live from each LP's sequence position — overdue and gone-quiet first. <b>Draft →</b> opens the Composer preloaded with that contact + channel. In-app touches log automatically.</div>
          </TS.Card>
        </div>
      </div>
    </>
  );
}
window.TabToday = TabToday;
