// Backlink Profile — anchor distribution, quality bands, issues

(function () {

function BacklinkPage({ go }) {
  const c  = window.CP_CLIENT || {};
  const bl = c.backlinks || {};
  const score = bl.score ?? 0;
  const scoreColor = score>=70?'var(--good)':score>=50?'var(--warn)':'var(--bad)';

  return (
    <div>
      <div style={{ marginBottom:24 }}>
        <h2 className="hk-h3" style={{ marginBottom:4 }}>Backlink Profile</h2>
        <p className="hk-small" style={{ color:'var(--ink-3)' }}>
          Inbound link analysis for <strong>{c.domain}</strong> · Via Ahrefs
        </p>
      </div>

      {/* ── Score + core numbers ────────────────────────────── */}
      <div style={{ display:'grid', gridTemplateColumns:'auto 1fr', gap:12, marginBottom:24, alignItems:'stretch' }}>
        {/* Score card */}
        <div style={{ background:'var(--surface)', border:'1px solid var(--border)', borderRadius:'var(--r-3)', padding:'20px 24px', display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center', minWidth:140 }}>
          <div style={{ fontSize:52, fontWeight:700, color:scoreColor, lineHeight:1 }}>{score}</div>
          <div style={{ fontSize:12, color:'var(--ink-3)', marginTop:4 }}>Backlink Health</div>
          <div style={{ fontSize:12, fontWeight:700, color:scoreColor, marginTop:6 }}>{score>=70?'Healthy':score>=50?'Needs Work':'Weak'}</div>
        </div>

        {/* Metrics grid */}
        <div style={{ display:'grid', gridTemplateColumns:'repeat(auto-fill,minmax(130px,1fr))', gap:10 }}>
          {[
            { label:'Total Backlinks',     value:(bl.total||0).toLocaleString(),            color:'var(--ink)',   hint:null },
            { label:'Dofollow',            value:(bl.dofollow||0).toLocaleString(),          color:'var(--good)', hint:'Dofollow links pass SEO value ("link juice") from the linking site to yours. More dofollow from quality sites = higher rankings.' },
            { label:'Nofollow',            value:(bl.nofollow||0).toLocaleString(),          color:'var(--ink-2)',hint:"Nofollow links tell Google not to pass SEO value. They still bring traffic but don't help your rankings directly." },
            { label:'Referring Domains',   value:(bl.referringDomains||0).toLocaleString(),  color:'var(--ink)',   hint:'Unique websites linking to you. Quality counts more than quantity — one link from a news site is worth more than 100 from random blogs.' },
            { label:'Gained (30d)',        value:`+${bl.newLast30||0}`,                       color:'var(--good)', hint:null },
            { label:'Lost (30d)',          value:`-${bl.lostLast30||0}`,                      color:'var(--bad)', hint:null },
            { label:'Toxic links',         value:bl.toxicLinks||0,                            color:'var(--bad)', hint:'Links from spammy, low-quality, or penalized sites can actually hurt your rankings. These may need to be disavowed (removed from Google\'s count).' }
          ].map(m => (
            <div key={m.label} style={{ background:'var(--surface)', border:'1px solid var(--border)', borderRadius:'var(--r-2)', padding:'12px 14px' }}>
              <div style={{ fontSize:22, fontWeight:700, color:m.color, lineHeight:1, marginBottom:3 }}>{m.value}</div>
              <div style={{ display:'flex', alignItems:'center', gap:4 }}>
                <div className="hk-tiny" style={{ color:'var(--ink-3)' }}>{m.label}</div>
                {m.hint && <Hint text={m.hint} width={220}/>}
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* ── Anchor text + Quality bands ─────────────────────── */}
      <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:12, marginBottom:24 }}>
        {/* Anchor text */}
        <div style={{ background:'var(--surface)', border:'1px solid var(--border)', borderRadius:'var(--r-3)', padding:'18px 20px' }}>
          <div style={{ display:'flex', alignItems:'center', gap:6, marginBottom:16 }}>
            <span className="hk-h4">Anchor Text Distribution</span>
            <Hint text="Anchor text is the clickable words in a link pointing to your site. A natural mix (brand name, URL, generic, and some keywords) looks better to Google than all keyword links." width={240}/>
          </div>
          <div style={{ display:'flex', flexDirection:'column', gap:10 }}>
            {(bl.anchors||[]).map((a, i) => {
              const colors = ['var(--accent)','var(--good)','var(--warn)','var(--bad)','var(--ink-3)'];
              return (
                <div key={i}>
                  <div style={{ display:'flex', justifyContent:'space-between', marginBottom:5 }}>
                    <span style={{ fontSize:13, color:'var(--ink-2)' }}>{a.type}</span>
                    <span style={{ fontSize:12.5, fontWeight:600, color:'var(--ink)' }}>{a.pct}% <span style={{ color:'var(--ink-3)', fontWeight:400 }}>({a.count})</span></span>
                  </div>
                  <div style={{ height:6, background:'var(--surface-3)', borderRadius:99, overflow:'hidden' }}>
                    <div style={{ width:`${a.pct}%`, height:'100%', background:colors[i%colors.length], borderRadius:99 }}/>
                  </div>
                </div>
              );
            })}
          </div>
          <div style={{ marginTop:16, padding:'10px 12px', background:'var(--surface-3)', borderRadius:'var(--r-2)' }}>
            <div className="hk-tiny" style={{ color:'var(--ink-3)', lineHeight:1.6 }}>
              <strong style={{ color:'var(--ink-2)' }}>Healthy ratio:</strong> 40–50% branded, 20–30% naked URL, &lt;15% keyword-rich.
              Keyword-rich anchors above 15% can trigger Google's spam filter.
            </div>
          </div>
        </div>

        {/* Quality bands */}
        <div style={{ background:'var(--surface)', border:'1px solid var(--border)', borderRadius:'var(--r-3)', padding:'18px 20px' }}>
          <div className="hk-h4" style={{ marginBottom:16 }}>Link Quality Distribution</div>
          <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
            {(bl.quality||[]).map((q, i) => {
              const colorKey = q.color==='good'?'var(--good)':q.color==='warn'?'var(--warn)':'var(--bad)';
              return (
                <div key={i}>
                  <div style={{ display:'flex', justifyContent:'space-between', marginBottom:5 }}>
                    <span style={{ fontSize:13, color:'var(--ink-2)' }}>{q.label}</span>
                    <span style={{ fontSize:12.5, fontWeight:600, color:'var(--ink)' }}>{q.count} <span style={{ color:'var(--ink-3)', fontWeight:400 }}>({q.pct}%)</span></span>
                  </div>
                  <div style={{ height:8, background:'var(--surface-3)', borderRadius:99, overflow:'hidden' }}>
                    <div style={{ width:`${q.pct}%`, height:'100%', background:colorKey, borderRadius:99 }}/>
                  </div>
                </div>
              );
            })}
          </div>
          <div style={{ marginTop:20 }}>
            <div style={{ display:'flex', justifyContent:'space-between', padding:'10px 0', borderTop:'1px solid var(--border)', alignItems:'center' }}>
              <span style={{ display:'flex', alignItems:'center', gap:5 }} className="hk-small">
                <span style={{ color:'var(--ink-3)' }}>Dofollow ratio</span>
                <Hint text="The percentage of your links that pass SEO value. Higher is better. Under 30% means most of your links don't help your rankings." width={210}/>
              </span>
              <span style={{ fontSize:13.5, fontWeight:700, color: bl.dofollow/bl.total>0.3?'var(--good)':'var(--warn)' }}>
                {bl.total>0?Math.round((bl.dofollow/bl.total)*100):0}%
              </span>
            </div>
            <div style={{ display:'flex', justifyContent:'space-between', padding:'10px 0', borderTop:'1px solid var(--border)' }}>
              <span className="hk-small" style={{ color:'var(--ink-3)' }}>Toxic links detected</span>
              <span style={{ fontSize:13.5, fontWeight:700, color:bl.toxicLinks>0?'var(--bad)':'var(--good)' }}>{bl.toxicLinks||0}</span>
            </div>
          </div>
        </div>
      </div>

      {/* ── Link velocity ────────────────────────────────────── */}
      <div style={{ background:'var(--surface)', border:'1px solid var(--border)', borderRadius:'var(--r-3)', padding:'18px 20px', marginBottom:24 }}>
        <div style={{ display:'flex', alignItems:'center', gap:6, marginBottom:6 }}>
          <span className="hk-h4">Link Velocity (Last 30 Days)</span>
          <Hint text="How many backlinks you're gaining vs. losing each month. Steady growth is healthy. Sudden large spikes can look suspicious to Google." width={230}/>
        </div>
        <div className="hk-tiny" style={{ color:'var(--ink-3)', marginBottom:16 }}>Net: {(bl.newLast30||0)-(bl.lostLast30||0) >= 0 ? '+':''}{(bl.newLast30||0)-(bl.lostLast30||0)} links</div>
        <div style={{ display:'flex', gap:16, flexWrap:'wrap' }}>
          <div style={{ display:'flex', alignItems:'center', gap:10, padding:'10px 16px', background:'var(--good-soft)', border:'1px solid color-mix(in srgb,var(--good) 25%,transparent)', borderRadius:'var(--r-2)' }}>
            <Icon name="arrowUp" size={18} style={{ color:'var(--good)' }}/>
            <div>
              <div style={{ fontSize:22, fontWeight:700, color:'var(--good)' }}>+{bl.newLast30||0}</div>
              <div className="hk-tiny" style={{ color:'var(--ink-3)' }}>Links gained</div>
            </div>
          </div>
          <div style={{ display:'flex', alignItems:'center', gap:10, padding:'10px 16px', background:'var(--bad-soft)', border:'1px solid color-mix(in srgb,var(--bad) 25%,transparent)', borderRadius:'var(--r-2)' }}>
            <Icon name="arrowDn" size={18} style={{ color:'var(--bad)' }}/>
            <div>
              <div style={{ fontSize:22, fontWeight:700, color:'var(--bad)' }}>-{bl.lostLast30||0}</div>
              <div className="hk-tiny" style={{ color:'var(--ink-3)' }}>Links lost</div>
            </div>
          </div>
          {(bl.lostLast30||0) > (bl.newLast30||0) && (
            <div style={{ flex:1, padding:'10px 14px', background:'var(--warn-soft)', border:'1px solid color-mix(in srgb,var(--warn) 30%,transparent)', borderRadius:'var(--r-2)', display:'flex', alignItems:'center', gap:8 }}>
              <Icon name="info" size={16} style={{ color:'var(--warn)', flexShrink:0 }}/>
              <div className="hk-tiny" style={{ color:'var(--ink-2)', lineHeight:1.5 }}>
                You're losing links faster than gaining. Investigate lost pages and set up 301 redirects for any moved content.
              </div>
            </div>
          )}
        </div>
      </div>

      {/* ── Issues ───────────────────────────────────────────── */}
      <div style={{ background:'var(--surface)', border:'1px solid var(--border)', borderRadius:'var(--r-3)', padding:'18px 20px' }}>
        <div className="hk-h4" style={{ marginBottom:16 }}>Issues & Recommendations</div>
        <div style={{ display:'flex', flexDirection:'column', gap:10 }}>
          {(bl.issues||[]).map((issue, i) => {
            const sevColor = issue.sev==='critical'?'var(--bad)':issue.sev==='major'?'var(--warn)':'var(--ink-3)';
            return (
              <IssueCard key={i} issue={issue} sevColor={sevColor}/>
            );
          })}
        </div>
      </div>
    </div>
  );
}

function IssueCard({ issue, sevColor }) {
  const [open, setOpen] = React.useState(false);
  return (
    <div style={{ border:'1px solid var(--border)', borderRadius:'var(--r-2)', overflow:'hidden' }}>
      <div onClick={() => setOpen(o => !o)}
        style={{ display:'flex', alignItems:'flex-start', gap:12, padding:'12px 14px', cursor:'pointer', background:'var(--surface-3)' }}>
        <div style={{ width:7, height:7, borderRadius:'50%', background:sevColor, marginTop:5, flexShrink:0 }}/>
        <div style={{ flex:1 }}>
          <div style={{ fontSize:13.5, fontWeight:600, color:'var(--ink)' }}>{issue.title}</div>
        </div>
        <Icon name={open?'chevUp':'chev'} size={14} style={{ color:'var(--ink-3)', flexShrink:0, marginTop:2 }}/>
      </div>
      {open && (
        <div style={{ padding:'12px 14px 14px 33px', background:'var(--surface)', borderTop:'1px solid var(--border)' }}>
          <p className="hk-small" style={{ color:'var(--ink-2)', marginBottom:12, lineHeight:1.6 }}>{issue.detail}</p>
          <LockedSection
            label="Fix Guide — Book a Free Strategy Call"
            sub="Get step-by-step instructions to fix this issue and every other problem found in your audit."
            ctaLabel="Get the Fix"
          >
            <div style={{ padding:'10px 12px', background:'var(--surface-3)', borderRadius:'var(--r-1)', borderLeft:'3px solid var(--accent)' }}>
              <div className="hk-tiny" style={{ color:'var(--ink-3)', fontWeight:600, marginBottom:3, textTransform:'uppercase', letterSpacing:'0.06em' }}>Fix</div>
              <div className="hk-small" style={{ color:'var(--ink)', lineHeight:1.6 }}>{issue.fix}</div>
            </div>
          </LockedSection>
        </div>
      )}
    </div>
  );
}

CP_PAGES.backlinks = { title: 'Backlink Profile', component: BacklinkPage };

})();
