// Publisher intelligence · ONE scorecard for every publisher TUEPAC knows about:
// Active members, Pipeline prospects, acquisition Targets, and Inactive/quiet feeds.

function unifiedRoster(){
  const members = (window.PUBLISHERS_EXT||[]).map(p=>{
    const quiet = p.id==='gb'; // demo: Goldsboro feed silent
    return { key:'m-'+p.id, name:p.name, city:p.city, bucket: quiet?'Inactive':'Active',
      da:p.da, postsWk: quiet?0:(p.cadence==='Daily'?9:p.cadence==='2×/wk'?2:1), score:p.score, quiet,
      note: quiet?'Feed silent 21 days':'' };
  });
  const prospects = (window.CONTACTS||[]).filter(c=>c.type==='Publisher' && c.stage!=='Active').map(c=>(
    { key:'p-'+c.id, name:c.org, city:c.city, bucket:'Pipeline', da:null, postsWk:null, score:c.score, quiet:false, note:'Stage · '+c.stage }
  ));
  const targets = (window.ACQ||[]).map(t=>(
    { key:'t-'+t.id, name:t.target, city:t.city, bucket:'Target', da:null, postsWk:null, score:t.fit, quiet:false, note:t.stage+' · succession '+t.succession.toLowerCase() }
  ));
  return members.concat(prospects, targets);
}

function PublisherIntel({setRoute}){
  const all = unifiedRoster();
  const [tab, setTab] = React.useState('All');
  const [swept, setSwept] = React.useState(false);
  const buckets = ['Active','Pipeline','Target','Inactive'];
  const counts = Object.fromEntries(buckets.map(b=>[b, all.filter(x=>x.bucket===b).length]));
  const rows = (tab==='All' ? all : all.filter(x=>x.bucket===tab)).sort((a,b)=>(b.score||0)-(a.score||0));

  return (
    <AdminShell route="pubintel" setRoute={setRoute} title="Publisher intelligence" breadcrumb="NETWORK · ONE ROSTER, EVERY PUBLISHER"
      actions={<button className="btn k" onClick={()=>setSwept(true)}>{swept?'✓ Sweep complete (demo)':'Run intel sweep'}</button>}>

      {swept && <div className="mono" style={{padding:'8px 12px',marginBottom:14,border:'1px solid var(--rule-line)',background:'var(--canvas)',fontSize:9.5,letterSpacing:'.08em',color:'var(--green)'}}>✓ DEMO SWEEP · DA, POSTS/WK, AND SCORES REFRESH FOR ALL {all.length} PUBLISHERS · ENGINEERING WIRES THIS TO AN SEO API + RSS COUNTS</div>}

      <div className="split-4" style={{marginBottom:18}}>
        {buckets.map(b=>(
          <Stat key={b} n={counts[b]} l={b} d={b==='Active'?'in network':b==='Pipeline'?'in outreach':b==='Target'?'acquisition':'quiet 14+ days'}/>
        ))}
      </div>

      <Card title="Scorecard" meta="every publisher · one table"
        actions={<Seg value={tab} onChange={setTab} options={['All','Active','Pipeline','Target','Inactive']}/>}>
        <table className="tbl" style={{width:'100%',tableLayout:'fixed'}}>
          <colgroup><col/><col style={{width:86}}/><col style={{width:46}}/><col style={{width:70}}/><col style={{width:110}}/></colgroup>
          <thead><tr><th>PUBLISHER</th><th>STATUS</th><th className="r">DA</th><th className="r">POSTS/WK</th><th className="r">SCORE</th></tr></thead>
          <tbody>
            {rows.map(x=>(
              <tr key={x.key}>
                <td style={{overflow:'hidden'}}>
                  <div style={{fontSize:12.5,fontWeight:600,whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>{x.name}</div>
                  <div className="mono" style={{fontSize:9.5,color:x.quiet?'var(--red)':'var(--mute)',letterSpacing:'.06em',whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>{x.city.toUpperCase()}{x.note?' · '+x.note.toUpperCase():''}</div>
                </td>
                <td><Pill k={x.bucket==='Active'?'live':x.bucket==='Pipeline'?'info':x.bucket==='Target'?'warn':'bad'}>{x.bucket.toUpperCase()}</Pill></td>
                <td className="r num">{x.da==null?' · ':x.da}</td>
                <td className="r num" style={{color:x.quiet?'var(--red)':'inherit',fontWeight:x.quiet?700:400}}>{x.postsWk==null?' · ':x.postsWk}</td>
                <td className="r"><Score n={x.score||0}/></td>
              </tr>
            ))}
            {rows.length===0 && <tr><td colSpan="5" className="mono" style={{textAlign:'center',padding:'20px 0',fontSize:10,letterSpacing:'.1em',color:'var(--mute)'}}>NONE IN THIS BUCKET</td></tr>}
          </tbody>
        </table>
        <div className="mono" style={{fontSize:9.5,color:'var(--mute)',letterSpacing:'.08em',marginTop:10}}>PIPELINE ROWS COME FROM THE PIPELINE SECTION · TARGETS FROM ACQUISITION · A CONTACT GOING ACTIVE JOINS AS ACTIVE AUTOMATICALLY · A FEED SILENT 14+ DAYS FLAGS INACTIVE</div>
      </Card>
    </AdminShell>
  );
}

window.PublisherIntel = PublisherIntel;
