// person.jsx — global Person Profile drawer: the hub everything links to.
// Mounted once (<PersonHost/>); any tab calls RaiseStore.openPerson(id).
const { useState, useEffect } = React;
const PS = window.RaiseShell;

const EV = {
  meeting:{ c:'#8159bf', label:'Meeting' },
  email:  { c:'#4a78c8', label:'Email' },
  touch:  { c:'#4a78c8', label:'Touch' },
  stage:  { c:'#3f9560', label:'Stage' },
  note:   { c:'#c08a2a', label:'Note' },
  task:   { c:'#c96442', label:'Task' },
  todo:   { c:'#c96442', label:'Open to-do' },
  done:   { c:'#3f9560', label:'Completed' },
};
const agoLabel = (n)=> n<0 ? 'Open' : n===0 ? 'Today' : n>=7 ? Math.round(n/7)+'w ago' : n+'d ago';
function dateAgo(str){ try{ const t=new Date('2026-06-12'); const d=new Date(str); const n=Math.round((t-d)/864e5); return isNaN(n)?1:Math.max(0,n); }catch(e){ return 1; } }

function Timeline({ c, todos, notes }){
  const R = window.RAISE;
  const events = [
    ...(c.isSelf ? [] : R.personLog(c)),
    ...notes.map(n=>({ ago:dateAgo(n.date), type:'note', text:n.title })),
    ...todos.map(t=>({ ago:t.done?0:-1, type:t.done?'done':'todo', text:t.text })),
  ].sort((a,b)=>a.ago-b.ago);
  return (
    <div className="ptl">
      {events.map((e,i)=>{
        const m = EV[e.type] || EV.touch;
        return (
          <div key={i} className="ptl-row">
            <div className="ptl-rail"><span className="ptl-dot" style={{background:m.c}}/></div>
            <div className="ptl-body">
              <div className="ptl-text">{e.text}</div>
              <div className="ptl-meta mono"><span style={{color:m.c}}>{m.label}</span> · {agoLabel(e.ago)}</div>
            </div>
          </div>
        );
      })}
    </div>
  );
}

function PersonTodos({ c, todos }){
  const Store = window.RaiseStore;
  const [draft, setDraft] = useState('');
  const add = ()=>{ if(!draft.trim())return; Store.add({ text:draft.trim(), personId:c.id, listId:'l-followups', flagged:true }); setDraft(''); PS.toast('To-do added & linked to '+c.name.split(' ')[0]); };
  const open = todos.filter(t=>!t.done), done = todos.filter(t=>t.done);
  return (
    <div className="ptodos">
      <div className="addrow">
        <input className="addinp" placeholder={'Add a to-do for '+c.name.split(' ')[0]+'…'} value={draft}
               onChange={e=>setDraft(e.target.value)} onKeyDown={e=>e.key==='Enter'&&add()} />
        <button className="btn primary sm" onClick={add}>＋</button>
      </div>
      {todos.length===0 && <div className="muted" style={{fontSize:13,padding:'14px 2px'}}>No to-dos linked to this person yet.</div>}
      {open.map(t=>(
        <div key={t.id} className="prow">
          <button className="rcheck" onClick={(e)=>{ const r=e.currentTarget.getBoundingClientRect(); PS.celebrate(r.left+9,r.top+9); Store.complete(t.id); }} />
          <div className="prow-mid"><div className="prow-t">{t.text}</div>
            {(t.reminder||t.subtasks.length>0) && <div className="prow-s mono">{t.reminder && '⏰ '+t.reminder}{t.reminder&&t.subtasks.length>0&&'  ·  '}{t.subtasks.length>0 && t.subtasks.filter(s=>s.done).length+'/'+t.subtasks.length+' subtasks'}</div>}
          </div>
        </div>
      ))}
      {done.length>0 && <div className="psub mono">Completed</div>}
      {done.map(t=>(
        <div key={t.id} className="prow done">
          <button className="rcheck on" onClick={()=>Store.complete(t.id)}>✓</button>
          <div className="prow-mid"><div className="prow-t">{t.text}</div></div>
        </div>
      ))}
    </div>
  );
}

function PersonNotes({ c, notes }){
  const Store = window.RaiseStore;
  const [openId, setOpenId] = useState(null);
  const create = ()=>{ Store.addNote({ personId:c.id, title:'Meeting — '+c.name.split(' ')[0], body:'' }); PS.toast('Note created'); };
  return (
    <div className="pnotes">
      <button className="btn sm" style={{width:'100%',justifyContent:'center',marginBottom:10}} onClick={create}>＋ New meeting note</button>
      {notes.length===0 && <div className="muted" style={{fontSize:13,padding:'10px 2px'}}>No notes yet. Capture a call or meeting above.</div>}
      {notes.map(n=>(
        <div key={n.id} className="pnote">
          {openId===n.id ? (
            <>
              <input className="pnote-title" defaultValue={n.title} autoFocus
                     onBlur={e=>Store.patchNote(n.id,{title:e.target.value})} />
              <textarea className="pnote-body-edit" defaultValue={n.body} placeholder="Notes…"
                        onBlur={e=>Store.patchNote(n.id,{body:e.target.value})} />
              <div className="pnote-foot"><span className="mono">{n.date}</span>
                <div style={{display:'flex',gap:6}}>
                  <button className="linkbtn" onClick={()=>setOpenId(null)}>Done</button>
                  <button className="linkbtn" style={{color:'var(--rose)'}} onClick={()=>{Store.removeNote(n.id);setOpenId(null);}}>Delete</button>
                </div>
              </div>
            </>
          ) : (
            <div onClick={()=>setOpenId(n.id)} style={{cursor:'text'}}>
              <div className="pnote-title-show">{n.title}</div>
              {n.body && <div className="pnote-body">{n.body}</div>}
              <div className="pnote-date mono">{n.date}</div>
            </div>
          )}
        </div>
      ))}
    </div>
  );
}

function PersonSheet({ id, onClose }){
  const R = window.RAISE;
  const { Avatar, StageBadge, IcpTag, money } = PS;
  const todos = PS.useTodos();
  const notes = PS.useNotes();
  const [tab, setTab] = useState('activity');
  useEffect(()=>{ setTab('activity'); }, [id]);
  const c = R.contactById(id);
  if(!c) return null;
  const self = c.isSelf;
  const myTodos = todos.filter(t=>PS.ownedBy(t,id));
  const myNotes = notes.filter(n=>PS.ownedBy(n,id));
  const openCount = myTodos.filter(t=>!t.done).length;

  const meta = [
    ['Check', c.check ? money(c.check) : 'Aggregated'],
    ['Fit', c.fit ? c.fit+'/10' : '—'],
    ['Interest', c.interest ? c.interest+'/10' : 'Not scored'],
    ['Warmth', c.warmth],
    ['Source', c.source],
    ['Geo', c.geo],
  ];
  const TABS = [['activity','Activity'],['todos','To-Dos'+(openCount?' ('+openCount+')':'')],['notes','Notes'+(myNotes.length?' ('+myNotes.length+')':'')]];
  if(!self) TABS.push(['intel','Intel']);

  return (
    <>
      <div className="sheet-back" onClick={onClose} />
      <div className="sheet person">
        <div className="sheet-hd">
          <Avatar name={c.name} anchor={c.anchor} />
          <div style={{minWidth:0}}>
            <div className="nm">{c.name}</div>
            <div className="fm">{c.firm}</div>
            <div className="role">{c.role}</div>
            {self ? (
              <div style={{display:'flex',gap:6,marginTop:8}}>
                <span className="sbadge mono" style={{color:'var(--ink-2)',background:'var(--surface-3)'}}>Your workspace</span>
              </div>
            ) : (
              <div style={{display:'flex',gap:6,marginTop:8,flexWrap:'wrap'}}>
                <StageBadge id={c.stage} /><IcpTag icp={c.icp} />
                {c.anchor && <span className="sbadge mono" style={{color:'var(--primary-2)',background:'var(--primary-tint)'}}>★ Anchor</span>}
                {c.nurture && <span className="sbadge mono" style={{color:'var(--ink-2)',background:'var(--surface-3)'}}>Nurture</span>}
              </div>
            )}
          </div>
          <button className="sheet-x" onClick={onClose}>✕</button>
        </div>

        {!self && (
          <div className="sheet-meta tight">
            {meta.map((m,i)=>(<div key={i} className="m"><div className="mk">{m[0]}</div><div className="mv mono">{m[1]}</div></div>))}
          </div>
        )}

        <div className="psheet-tabs">
          {TABS.map(([k,l])=>(
            <button key={k} className={'psheet-tab'+(tab===k?' on':'')} onClick={()=>setTab(k)}>{l}</button>
          ))}
        </div>

        <div className="sheet-body scroll">
          {c.nextStep && tab==='activity' && (
            <div className="pnext"><span className="pnext-k mono">NEXT</span> {c.nextStep}</div>
          )}
          {tab==='activity' && <Timeline c={c} todos={myTodos} notes={myNotes} />}
          {tab==='todos' && <PersonTodos c={c} todos={myTodos} />}
          {tab==='notes' && <PersonNotes c={c} notes={myNotes} />}
          {tab==='intel' && (c.intel ? (
            <div className="pintel">
              <div className="intel-sec"><div className="lab">Background brief <span className="engine-tag">engine</span></div><p>{c.intel.brief}</p></div>
              <div className="intel-sec angle"><div className="lab">Suggested angle</div><p>{c.intel.angle}</p></div>
              <div className="intel-sec"><div className="lab">Pain-point hypothesis</div><ul>{c.intel.pains.map((p,i)=><li key={i}>{p}</li>)}</ul></div>
              <div className="intel-sec"><div className="lab">Commonality</div><p>{c.intel.commonality}</p></div>
              <div className="intel-sec"><div className="lab">Talking points</div><ul>{c.intel.talking.map((p,i)=><li key={i}>{p}</li>)}</ul></div>
            </div>
          ) : (
            <div className="nointel"><div style={{fontSize:13}}>No engine brief yet.</div>
              <div className="mono" style={{fontSize:12,marginTop:6,color:'var(--ink-3)'}}>Queue research — the engine writes the brief, fit score and angle on its next run.</div>
              <button className="btn primary sm">+ Queue research</button></div>
          ))}
        </div>

        <div className="psheet-foot">
          {self ? (
            <>
              <button className="btn primary sm" style={{flex:1,justifyContent:'center'}} onClick={()=>setTab('todos')}>+ Add to-do</button>
              <button className="btn sm" style={{flex:1,justifyContent:'center'}} onClick={()=>setTab('notes')}>+ Add note</button>
            </>
          ) : (
            <>
              <button className="btn primary sm" style={{flex:1,justifyContent:'center'}} onClick={()=>{ PS.toast('Opening in Outreach…'); }}>Open in Outreach</button>
              <button className="btn sm" style={{flex:1,justifyContent:'center'}} onClick={()=>setTab('todos')}>+ Add to-do</button>
            </>
          )}
        </div>
      </div>
    </>
  );
}

function PersonHost(){
  const id = PS.useActivePerson();
  const Store = window.RaiseStore;
  useEffect(()=>{
    const onKey = (e)=>{ if(e.key==='Escape') Store.closePerson(); };
    document.addEventListener('keydown', onKey);
    return ()=>document.removeEventListener('keydown', onKey);
  },[]);
  if(!id) return null;
  return <PersonSheet id={id} onClose={()=>Store.closePerson()} />;
}

window.PersonHost = PersonHost;
window.PersonSheet = PersonSheet;
