// Syndication · Backlinks — outbound + inbound links, paid inventory, health, revenue attribution.

function SyndBacklinks(){
  const [links, setLinks] = React.useState(()=> (window.BACKLINKS||[]).map(x=>({...x})));
  const [filter, setFilter] = React.useState('All');
  const inv = window.PAID_LINK_INVENTORY||[];

  const shown = links.filter(l=>{
    if(filter==='Outbound') return l.dir==='Outbound';
    if(filter==='Inbound')  return l.dir==='Inbound';
    if(filter==='Paid')     return l.paid;
    if(filter==='Broken')   return l.health==='Broken';
    return true;
  });

  function recheck(id){
    setLinks(ls=>ls.map(l=> l.id===id ? {...l, health:'Live', checked:'just now'} : l));
  }

  const paidRev = links.filter(l=>l.paid).reduce((s,l)=>s+(parseInt((l.rev||'').replace(/[^0-9]/g,''))||0),0);
  const broken = links.filter(l=>l.health==='Broken').length;
  const doFollow = links.filter(l=>l.rel==='do-follow').length;

  function healthMeta(h){ return h==='Live'?['live','LIVE']:h==='Broken'?['bad','BROKEN']:['warn','PENDING']; }

  return (
    <div>
      <div className="split-4" style={{marginBottom:18}}>
        <Stat n={String(links.length)} l="Tracked backlinks" d={`${links.filter(l=>l.dir==='Inbound').length} in · ${links.filter(l=>l.dir==='Outbound').length} out`}/>
        <Stat n={String(doFollow)} l="Do-follow (SEO weight)" d="passing authority"/>
        <Stat n={'$'+paidRev.toLocaleString()} l="Paid link revenue · mo" d="placements live" up={true}/>
        <Stat n={String(broken)} l="Broken / needs repair" d={broken?'action needed':'all healthy'} up={broken?false:undefined}/>
      </div>

      <div style={{display:'grid',gridTemplateColumns:'1.7fr 1fr',gap:18,alignItems:'flex-start'}}>
        <Card title="Backlink ledger" meta={`${shown.length} shown`}
          actions={<Seg value={filter} onChange={setFilter} options={['All','Outbound','Inbound','Paid','Broken']}/>}>
          <table className="tbl" style={{marginLeft:-14,marginRight:-14,width:'calc(100% + 28px)'}}>
            <thead><tr><th>ID</th><th>DIR</th><th>PARTNER / ANCHOR</th><th>REL</th><th className="r">REV</th><th>HEALTH</th><th></th></tr></thead>
            <tbody>
              {shown.map(l=>{
                const [hk,hl]=healthMeta(l.health);
                return (
                  <tr key={l.id}>
                    <td className="id">{l.id}</td>
                    <td><Pill k={l.dir==='Inbound'?'info':'muted'}>{l.dir==='Inbound'?'↓ IN':'↑ OUT'}</Pill></td>
                    <td style={{maxWidth:240}}>
                      <div style={{fontSize:12,fontWeight:600,display:'flex',alignItems:'center',gap:6}}>{l.partner}{l.paid && <Pill k="warn">PAID {l.price}</Pill>}</div>
                      <div className="mono" style={{fontSize:9,color:'var(--mute)',letterSpacing:'.02em',whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>“{l.anchor}” {l.da!=='—'&&`· ${l.da}`}</div>
                    </td>
                    <td><Pill k={l.rel==='do-follow'?'live':'muted'}>{l.rel==='do-follow'?'DO-FOLLOW':'NO-FOLLOW'}</Pill></td>
                    <td className="r mono num" style={{fontWeight:600,color:l.rev!=='—'?'var(--green)':'var(--mute)'}}>{l.rev}</td>
                    <td><Pill k={hk}>{hl}</Pill></td>
                    <td className="r">{l.health!=='Live' && <button className="btn gh s" onClick={()=>recheck(l.id)}>Recheck</button>}</td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </Card>

        <div style={{display:'flex',flexDirection:'column',gap:14}}>
          <Card title="Paid backlink inventory" meta="rate card">
            {inv.map(p=>(
              <div key={p.tier} style={{padding:'9px 0',borderBottom:'1px solid var(--rule-line)'}}>
                <div style={{display:'grid',gridTemplateColumns:'1fr auto',gap:10,alignItems:'baseline'}}>
                  <span style={{fontSize:12.5,fontWeight:600}}>{p.tier}</span>
                  <span className="mono num" style={{fontSize:11.5,fontWeight:700,color:'var(--green)'}}>{p.price}</span>
                </div>
                <div style={{display:'flex',gap:8,alignItems:'center',marginTop:4}}>
                  <Pill k={p.rel==='do-follow'?'live':'muted'}>{p.rel.toUpperCase()}</Pill>
                  <Pill k={p.avail==='Open'?'info':'warn'}>{p.avail.toUpperCase()}</Pill>
                  <span className="mono" style={{fontSize:9,color:'var(--mute)',letterSpacing:'.02em'}}>{p.note}</span>
                </div>
              </div>
            ))}
            <button className="btn gh" style={{width:'100%',marginTop:12}}>Send rate card to a partner →</button>
          </Card>

          <Card title="Link health monitor">
            <div style={{display:'flex',flexDirection:'column',gap:9}}>
              {[['Do-follow live',doFollow,'var(--green)'],['No-follow live',links.filter(l=>l.rel==='no-follow'&&l.health==='Live').length,'var(--navy)'],['Pending crawl',links.filter(l=>l.health==='Pending').length,'var(--gold-2)'],['Broken',broken,'var(--red)']].map(([k,n,c])=>(
                <div key={k} style={{display:'grid',gridTemplateColumns:'1fr auto',gap:10,alignItems:'center'}}>
                  <span style={{fontSize:12,color:'var(--ink-2)'}}>{k}</span>
                  <span className="mono num" style={{fontSize:13,fontWeight:700,color:c}}>{n}</span>
                </div>
              ))}
            </div>
            <div className="mono" style={{fontSize:9.5,color:'var(--mute)',marginTop:12,lineHeight:1.55,letterSpacing:'.02em'}}>
              Crawler checks every backlink daily for status, rel attribute drift, and anchor changes. Broken links flag for repair.
            </div>
          </Card>
        </div>
      </div>
    </div>
  );
}

window.SyndBacklinks = SyndBacklinks;
