// outreach-runtime.jsx — per-contact runtime view + enrollment flow.
const { useState: useStateRt } = React;
const RSrt = window.RaiseShell;

function ChMini({ id }){ const B=window.OXBits; return B ? <B.ChTag id={id} /> : null; }

// ── Contact runtime view: where they are, what's next, what's been sent ──
function RuntimeView({ contact, onClose }){
  const OX = window.OX, R = window.RAISE;
  const c = contact;
  const st = OX.enrollStatus(c);
  const seqId = c.seq && c.seq!=='—' ? c.seq.trim()[0] : null;
  const seq = seqId ? OX.Store.seq(seqId) : null;
  const m = /(\d+)\s*of\s*(\d+)/i.exec(c.step||'');
  const stepNum = m ? +m[1] : null;
  const nextStep = seq && stepNum ? seq.steps[Math.min(stepNum-1, seq.steps.length-1)] : null;
  const log = R.personLog(c).slice().sort((a,b)=>a.ago-b.ago);
  const act = (label)=>{ RSrt.toast(label); onClose(); };
  return (
    <div className="note-overlay" onClick={onClose}>
      <div className="rt-doc" onClick={e=>e.stopPropagation()}>
        <div className="rt-hd">
          <RSrt.Avatar name={c.name} anchor={c.anchor} />
          <div style={{flex:1,minWidth:0}}>
            <div className="rt-nm">{c.name}</div>
            <div className="rt-sub">{c.firm} · {c.seq && c.seq!=='—' ? c.seq : 'No active sequence'}</div>
          </div>
          <button className="sheet-x" onClick={onClose}>✕</button>
        </div>
        <div className="rt-body scroll">
          <div className="rt-statusbar" style={{ background:st.color+'1c', color:st.color, border:'1px solid '+st.color+'44' }}>
            <span className="erdot" style={{ background:st.color }} /> {st.label}
            {st.key==='replied' && <span style={{marginLeft:'auto',fontWeight:500,opacity:.85}}>Cadence auto-paused — reply detected</span>}
            {st.key==='paused' && <span style={{marginLeft:'auto',fontWeight:500,opacity:.85}}>No reply — nudge or move to nurture</span>}
          </div>

          {nextStep ? (
            <div className="rt-next">
              <div className="rn-k">Next touch · step {stepNum} of {m[2]}</div>
              <div className="rn-row">
                <ChMini id={nextStep.ch} />
                <span className="rn-lbl">{nextStep.label}</span>
                <span className="enr-prog track" style={{marginLeft:'auto',width:60}}><i style={{width:Math.round(stepNum/(+m[2])*100)+'%',background:st.color}} /></span>
              </div>
              <div style={{marginTop:9,display:'flex',gap:7}}>
                <button className="btn primary sm" onClick={()=>{ localStorage.setItem('raiseos.outreach.view','coach'); localStorage.setItem('raiseos.outreach.composeFor',c.id); localStorage.setItem('raiseos.outreach.composeChannel',nextStep.ch); RSrt.toast('Opening Draft Coach for '+c.name); onClose(); document.querySelector('[title="Outreach"]')?.click(); }}>Draft this touch →</button>
              </div>
            </div>
          ) : (
            <div className="rt-next"><div className="rn-k">Status</div><div className="rn-row"><span className="rn-lbl">{c.step || 'Not enrolled in a sequence.'}</span></div></div>
          )}

          <div className="intel-lab">Activity · what's been sent</div>
          <div className="rt-timeline">
            {log.map((e,i)=>{
              const reply = /\brepl/i.test(e.text);
              return (
                <div key={i} className={'rt-ev '+(reply?'reply':e.type==='email'||e.type==='touch'?'sent':'')+(i===log.length-1?' last':'')}>
                  <div className="rt-rail"><div className="rt-knob" /><div className="rt-line" /></div>
                  <div className="rt-evb"><div className="rt-evt">{e.text}</div><div className="rt-evd">{e.ago===0?'today':e.ago+'d ago'} · {e.type}</div></div>
                </div>
              );
            })}
          </div>
        </div>
        <div className="rt-foot">
          <button className="btn sm" onClick={()=>act('Paused — sequence holds until you resume')}>Pause</button>
          <button className="btn sm" onClick={()=>act('Advanced to the next step')}>Advance</button>
          <button className="btn sm" onClick={()=>act('Removed from sequence')} style={{color:'var(--rose)'}}>Remove</button>
        </div>
      </div>
    </div>
  );
}

// ── Enrollment flow: pick contact → pick sequence → preview → confirm ──
function EnrollModal({ onClose, preselect }){
  const OX = window.OX, R = window.RAISE;
  const seqs = OX.Store.seqs();
  const [cid, setCid] = useStateRt(preselect || R.contacts.find(c=>c.stage==='outreach')?.id || R.contacts[0].id);
  const [seqId, setSeqId] = useStateRt(seqs[0].id);
  const c = R.contactById(cid);
  const seq = OX.Store.seq(seqId);
  const matches = OX.segmentMatch(seq, c);
  const days = seq.steps.reduce((a,s,i)=>a+(i===0?0:(s.wait||0)),0);
  const confirm = ()=>{ RSrt.toast(c.name+' enrolled in '+seq.id+' · '+seq.name); onClose(); };
  return (
    <div className="note-overlay" onClick={onClose}>
      <div className="enr-modal" onClick={e=>e.stopPropagation()}>
        <div className="enr-modal-hd">
          <div style={{flex:1}}>
            <div className="em-t">Enroll a contact</div>
            <div className="em-s">Pick the contact and sequence, preview the cadence, confirm.</div>
          </div>
          <button className="sheet-x" onClick={onClose}>✕</button>
        </div>
        <div className="enr-modal-body scroll">
          <div className="intel-lab" style={{marginTop:0}}>Contact</div>
          <RSrt.PersonCombo value={cid} onChange={setCid} allowSelf={false} />

          <div className="intel-lab">Sequence</div>
          <div className="enr-pick">
            {seqs.map(s=>(
              <button key={s.id} className={'enr-pick-row'+(seqId===s.id?' on':'')} onClick={()=>setSeqId(s.id)}>
                <span className="stag" style={{width:24,height:24,borderRadius:7,background:'var(--ink)',color:'var(--surface)',fontFamily:'var(--mono)',fontSize:12,fontWeight:600,display:'flex',alignItems:'center',justifyContent:'center',flex:'none'}}>{s.id}</span>
                <div className="epm"><div className="epn">{s.name}</div><div className="eps">{s.icp}</div></div>
                <div className="epstat">{s.replyRate}% reply · {s.meetings} mtgs</div>
              </button>
            ))}
          </div>

          {matches
            ? <div className="seg-ok"><span>✓</span> <b style={{fontWeight:600}}>{R.ICP[c.icp].short}</b> matches this sequence's <b style={{fontWeight:600}}>{seq.segment}</b> segment.</div>
            : <div className="seg-warn"><span>⚠</span> Heads up — {c.name} is <b style={{fontWeight:600}}>{R.ICP[c.icp].short}</b>, but this sequence targets <b style={{fontWeight:600}}>{seq.segment}</b>. Enroll anyway?</div>}

          <div className="enr-preview">
            <div className="ep-h">Cadence preview · {seq.steps.length} steps over {days} days</div>
            {seq.steps.map((st,i)=>(
              <div className="enr-prev-step" key={st.id}>
                <span className="eps-n">{i+1}</span>
                <ChMini id={st.ch} />
                <span style={{minWidth:0,overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}}>{st.label}</span>
                <span className="eps-day">{i===0?'Day 0':'+'+st.wait+'d'}</span>
              </div>
            ))}
          </div>
        </div>
        <div className="enr-modal-foot">
          <span style={{fontSize:11.5,color:'var(--ink-3)',flex:1}}>506(c): cold outreach is permitted — no relationship gate here.</span>
          <button className="btn sm" onClick={onClose}>Cancel</button>
          <button className="btn primary sm" onClick={confirm}>Confirm enrollment</button>
        </div>
      </div>
    </div>
  );
}

window.OXRuntime = RuntimeView;
window.OXEnroll = EnrollModal;
