// outreach-vault.jsx — WS2 script library: shared, editable scripts. Add / edit / delete,
// personalized per contact. Backed by OX.Store (persists like sequences).
const { useState: useStateVault, useEffect: useEffectVault } = React;
const RSvault = window.RaiseShell;

// fill {tokens} in a script body from the active contact (delegates to the shared filler)
function personalize(text, c){ return window.OX.fillTokens(text, c); }

// highlight the substituted spans
function Personalized({ text, c }){
  if(!c) return <span>{(text||'').replace(/\{[^}]+\}/g,'…')}</span>;
  const parts = (text||'').split(/(\{[^}]+\})/g);
  return <>{parts.map((p,i)=> /^\{[^}]+\}$/.test(p)
    ? <mark key={i}>{personalize(p, c)}</mark>
    : <span key={i}>{p}</span>)}</>;
}

// ── edit form for one script ──────────────────────────────────────
function ScriptEditor({ script, onSaved, onCancel, onDelete }){
  const S = window.OX.Store;
  const [d, setD] = useStateVault(()=> JSON.parse(JSON.stringify(script)));
  const set = (k,v)=> setD(x=>({ ...x, [k]:v }));
  const setSec = (i,k,v)=> setD(x=>({ ...x, body:x.body.map((s,j)=> j===i?{...s,[k]:v}:s) }));
  const addSec = ()=> setD(x=>({ ...x, body:[...x.body, { h:'New section', t:'' }] }));
  const delSec = (i)=> setD(x=>({ ...x, body:x.body.filter((_,j)=>j!==i) }));
  const moveSec= (i,dir)=> setD(x=>{ const b=x.body.slice(); const j=i+dir; if(j<0||j>=b.length) return x; const [m]=b.splice(i,1); b.splice(j,0,m); return {...x, body:b}; });
  const save = ()=>{
    const tags = Array.isArray(d.tags) ? d.tags : String(d.tags||'').split(',').map(t=>t.trim()).filter(Boolean);
    S.patchScript(script.id, { name:d.name.trim()||'Untitled script', cat:d.cat.trim()||'Calls', use:d.use, mins:d.mins, blurb:d.blurb, body:d.body, tags });
    RSvault.toast('Script saved'); onSaved && onSaved();
  };
  const tagStr = Array.isArray(d.tags) ? d.tags.join(', ') : (d.tags||'');
  const cats = ['Calls','Objections','Referral','Email','Follow-up', ...S.scriptCats()].filter((v,i,a)=>a.indexOf(v)===i);
  return (
    <div className="vd-edit scroll">
      <div className="vde-row">
        <label className="vde-lab">Name</label>
        <input className="vde-inp" value={d.name} onChange={e=>set('name',e.target.value)} placeholder="Script name" />
      </div>
      <div className="vde-grid">
        <div className="vde-row">
          <label className="vde-lab">Category</label>
          <input className="vde-inp" list="vde-cats" value={d.cat} onChange={e=>set('cat',e.target.value)} placeholder="Calls" />
          <datalist id="vde-cats">{cats.map(c=> <option key={c} value={c} />)}</datalist>
        </div>
        <div className="vde-row">
          <label className="vde-lab">Used for</label>
          <input className="vde-inp" value={d.use||''} onChange={e=>set('use',e.target.value)} placeholder="Discovery call" />
        </div>
        <div className="vde-row">
          <label className="vde-lab">Length</label>
          <input className="vde-inp" value={d.mins||''} onChange={e=>set('mins',e.target.value)} placeholder="20 min" />
        </div>
      </div>
      <div className="vde-row">
        <label className="vde-lab">Summary</label>
        <input className="vde-inp" value={d.blurb||''} onChange={e=>set('blurb',e.target.value)} placeholder="One line on what this script is for" />
      </div>

      <div className="vde-seclab">Sections <span className="vde-hint">— use {'{first}'}, {'{firm}'}, {'{commonality}'} for live tokens</span></div>
      {d.body.map((s,i)=>(
        <div className="vde-sec" key={i}>
          <div className="vde-sec-hd">
            <input className="vde-inp tight" value={s.h} onChange={e=>setSec(i,'h',e.target.value)} placeholder="Section heading" />
            <button className="vde-sectool" disabled={i===0} onClick={()=>moveSec(i,-1)} title="Move up">↑</button>
            <button className="vde-sectool" disabled={i===d.body.length-1} onClick={()=>moveSec(i,1)} title="Move down">↓</button>
            <button className="vde-sectool del" onClick={()=>delSec(i)} title="Delete section">✕</button>
          </div>
          <textarea className="vde-area" value={s.t} onChange={e=>setSec(i,'t',e.target.value)} placeholder="Write the script text for this section…" rows={3} />
        </div>
      ))}
      <button className="vde-addsec" onClick={addSec}>＋ Add section</button>

      <div className="vde-row" style={{marginTop:14}}>
        <label className="vde-lab">Tags</label>
        <input className="vde-inp" value={tagStr} onChange={e=>set('tags',e.target.value)} placeholder="comma, separated, tags" />
      </div>

      <div className="vde-foot">
        <button className="btn ghost sm" style={{color:'var(--rose)',marginRight:'auto'}} onClick={onDelete}>Delete script</button>
        <button className="btn sm" onClick={onCancel}>Cancel</button>
        <button className="btn primary sm" onClick={save}>Save script</button>
      </div>
    </div>
  );
}

function VaultDoc({ script, contact, onClose, onPickContact, startEditing }){
  const S = window.OX.Store;
  const [editing, setEditing] = useStateVault(!!startEditing);
  if(!script) return null;
  const fullText = script.body.map(s=> s.h+'\n'+personalize(s.t, contact)).join('\n\n');
  const copy = ()=>{ try{ navigator.clipboard.writeText(fullText); }catch(e){} RSvault.toast('Script copied'+(contact?' · personalized for '+contact.name:'')); };
  const del = ()=>{ if(confirm('Delete “'+script.name+'”? This removes it from the library everywhere.')){ S.removeScript(script.id); RSvault.toast('Script deleted'); onClose(); } };
  return (
    <div className="note-overlay" onClick={onClose}>
      <div className="vault-doc" onClick={e=>e.stopPropagation()}>
        <div className="vd-hd">
          <div style={{flex:1,minWidth:0}}>
            <div className="vd-t">{script.name}</div>
            <div className="vd-s">{[script.use,script.mins,script.cat].filter(Boolean).join(' · ')}</div>
          </div>
          {!editing && <button className="btn sm" onClick={()=>setEditing(true)}>✎ Edit</button>}
          <button className="sheet-x" onClick={onClose}>✕</button>
        </div>

        {editing ? (
          <ScriptEditor script={script} onSaved={()=>setEditing(false)} onCancel={()=>{ if(startEditing) onClose(); else setEditing(false); }} onDelete={del} />
        ) : (
          <>
            <div className="vd-body scroll">
              {script.body.map((s,i)=>(
                <div className="vsec" key={i}>
                  <div className="vh">{s.h}</div>
                  <div className="vt"><Personalized text={s.t} c={contact} /></div>
                </div>
              ))}
              {(script.tags||[]).length>0 && (
                <div className="vd-tags">
                  {script.tags.map(t=> <span key={t} className="tchip">{t}</span>)}
                </div>
              )}
              <div className="vd-use-row">
                <button className="btn sm" onClick={()=>{ if(contact){ localStorage.setItem('raiseos.outreach.composeFor',contact.id); } if(window.__oxSetView){ window.__oxSetView('coach'); } RSvault.toast('Pulled “'+script.name+'” into Draft Coach'); onClose(); }}>Pull into Draft Coach →</button>
                <button className="btn sm" onClick={()=>{ if(window.__oxSetView){ window.__oxSetView('seq'); } RSvault.toast('Drop “'+script.name+'” onto a sequence step'); onClose(); }}>Drop into a sequence step →</button>
              </div>
            </div>
            <div className="vd-foot">
              <div className="vd-pers">
                {contact
                  ? <>Personalized for <RSvault.PersonChip id={contact.id} /></>
                  : <span>Pick a contact to personalize the <mark style={{background:'var(--primary-tint-2)',color:'var(--primary-2)',borderRadius:3,padding:'0 3px'}}>highlighted</mark> tokens.</span>}
              </div>
              <div style={{marginLeft:'auto',display:'flex',gap:8}}>
                <button className="btn sm" onClick={onPickContact}>{contact?'Change contact':'Personalize for…'}</button>
                <button className="btn primary sm" onClick={copy}>Copy script</button>
              </div>
            </div>
          </>
        )}
      </div>
    </div>
  );
}

function OXVault(){
  const OX = window.OX, R = window.RAISE, S = OX.Store;
  const [,bump] = useStateVault(0);
  useEffectVault(()=> S.subscribe(()=>bump(x=>x+1)), []);
  const [cat, setCat] = useStateVault('All');
  const [openId, setOpenId] = useStateVault(null);   // open script id
  const [freshId, setFreshId] = useStateVault(null);  // a just-created script → open in edit mode
  const [cid, setCid] = useStateVault('c-cedar');     // contact to personalize for
  const [picking, setPicking] = useStateVault(false);
  const contact = R.contactById(cid);
  const scripts = S.scripts();
  const cats = ['All', ...S.scriptCats()];
  const list = cat==='All' ? scripts : scripts.filter(s=>s.cat===cat);
  const open = scripts.find(s=>s.id===openId);

  const addNew = ()=>{ const s = S.addScript({ cat: cat==='All'?'Calls':cat }); setOpenId(s.id); setFreshId(s.id); };
  const delCard = (e,id,name)=>{ e.stopPropagation(); if(confirm('Delete “'+name+'”?')){ S.removeScript(id); RSvault.toast('Script deleted'); } };

  return (
    <div className="vault scroll">
      <div className="vault-top">
        <div className="vault-cats">
          {cats.map(ct=> <button key={ct} className={'vcat'+(cat===ct?' on':'')} onClick={()=>setCat(ct)}>{ct}</button>)}
        </div>
        <div className="vault-for">
          <button className="btn primary sm" onClick={addNew}>＋ New script</button>
          <span style={{width:1,height:18,background:'var(--border)'}} />
          Personalize for
          <div style={{width:190}}><RSvault.PersonCombo value={cid} onChange={setCid} allowSelf={false} /></div>
        </div>
      </div>

      <div className="vgrid">
        {list.map(s=>(
          <div key={s.id} className="vcard" onClick={()=>{ setOpenId(s.id); setFreshId(null); }}>
            <button className="vc-del" title="Delete script" onClick={e=>delCard(e,s.id,s.name)}>✕</button>
            <div className="vc-top">
              <div className="vc-name">{s.name}{s.custom && <span className="vc-mine">yours</span>}</div>
              <span className="vc-use">{s.cat}</span>
            </div>
            <div className="vc-blurb">{s.blurb||(s.body&&s.body[0]&&s.body[0].t)||'No description yet.'}</div>
            <div className="vc-perf">
              <span className={'vc-lift'+(s.replyLift==='—'?' flat':'')}>{s.replyLift==='—'?'— no lift yet':s.replyLift+' reply'}</span>
              <div className="vc-where">{(s.whereUsed||[]).map(w=> <span className="vc-wtag" key={w}>{w}</span>)}</div>
            </div>
            <div className="vc-foot">
              <span className="vc-mins">{s.mins||(s.body?s.body.length+' sections':'')}</span>
              <span className="vc-open">Open →</span>
            </div>
          </div>
        ))}
        {list.length===0 && <div className="muted" style={{gridColumn:'1/-1',padding:'30px 0',textAlign:'center',fontSize:13}}>No scripts in “{cat}”. <button className="linkbtn" onClick={addNew}>Add one →</button></div>}
      </div>

      {open && <VaultDoc script={open} contact={contact} startEditing={open.id===freshId}
        onClose={()=>{ setOpenId(null); setFreshId(null); }} onPickContact={()=>setPicking(true)} />}

      {picking && (
        <div className="note-overlay" onClick={()=>setPicking(false)}>
          <div className="combo-menu" style={{width:300,padding:14}} onClick={e=>e.stopPropagation()}>
            <div className="intel-lab" style={{marginTop:0}}>Personalize for…</div>
            <div className="combo-list" style={{maxHeight:340}}>
              {R.contacts.map(c=>(
                <button key={c.id} className={'combo-opt'+(cid===c.id?' on':'')} onClick={()=>{ setCid(c.id); setPicking(false); }}>
                  <span className={'combo-av mono'+(c.anchor?' anchor':'')}>{RSvault.initials(c.name)}</span>
                  <span className="combo-opt-nm">{c.name}<small>{c.firm}</small></span>
                </button>
              ))}
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

window.OXVault = OXVault;
