// Domain Authority — Ahrefs metrics, keywords, traffic, referrers

(function () {

function StatCard({ label, value, sub, color, hint }) {
  return (
    <div style={{ background:'var(--surface)', border:'1px solid var(--border)', borderRadius:'var(--r-3)', padding:'16px 18px' }}>
      <div style={{ fontSize:28, fontWeight:700, color:color||'var(--ink)', lineHeight:1, marginBottom:3 }}>
        {value}<span style={{ fontSize:14, color:'var(--ink-3)', fontWeight:400 }}>{sub||''}</span>
      </div>
      <div style={{ display:'flex', alignItems:'center', gap:5 }}>
        <div className="hk-tiny" style={{ color:'var(--ink-3)' }}>{label}</div>
        {hint && <Hint text={hint} width={200}/>}
      </div>
    </div>
  );
}

function PositionBar({ label, count, total, color }) {
  const pct = total > 0 ? Math.round((count/total)*100) : 0;
  return (
    <div style={{ display:'flex', alignItems:'center', gap:10 }}>
      <div style={{ width:70, fontSize:12.5, color:'var(--ink-3)', flexShrink:0 }}>{label}</div>
      <div style={{ flex:1, height:6, background:'var(--surface-3)', borderRadius:99, overflow:'hidden' }}>
        <div style={{ width:`${pct}%`, height:'100%', background:color, borderRadius:99 }}/>
      </div>
      <div style={{ width:26, fontSize:12.5, fontWeight:600, color:'var(--ink)', textAlign:'right', flexShrink:0 }}>{count}</div>
    </div>
  );
}

function TrafficChart({ data }) {
  if (!data || data.length < 2) return null;
  const vals = data.map(d => d.traffic);
  const min = 0, max = Math.max(...vals) * 1.1;
  const range = max - min || 1;
  const w = 100, h = 60;
  const pad = 4;
  const points = vals.map((v, i) => {
    const x = pad + (i / (vals.length-1)) * (w - pad*2);
    const y = h - pad - ((v-min)/range) * (h - pad*2);
    return `${x},${y}`;
  });
  const areaPoints = [...points, `${pad+(vals.length-1)/(vals.length-1)*(w-pad*2)},${h-pad}`, `${pad},${h-pad}`];
  return (
    <svg viewBox={`0 0 ${w} ${h}`} style={{ width:'100%', height:80 }}>
      <defs>
        <linearGradient id="tg" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="var(--accent)" stopOpacity="0.3"/>
          <stop offset="100%" stopColor="var(--accent)" stopOpacity="0.02"/>
        </linearGradient>
      </defs>
      <polygon points={areaPoints.join(' ')} fill="url(#tg)"/>
      <polyline points={points.join(' ')} fill="none" stroke="var(--accent)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
      {vals.map((v, i) => {
        const x = pad + (i/(vals.length-1))*(w-pad*2);
        const y = h - pad - ((v-min)/range)*(h-pad*2);
        return <circle key={i} cx={x} cy={y} r="2.5" fill="var(--accent)"/>;
      })}
    </svg>
  );
}

function DiffBadge({ diff }) {
  const color = diff < 30 ? 'var(--good)' : diff < 60 ? 'var(--warn)' : 'var(--bad)';
  return <span style={{ fontSize:11, color, fontWeight:600, padding:'1px 6px', background:'var(--surface-3)', borderRadius:4 }}>KD {diff}</span>;
}

function TrendArrow({ trend }) {
  if (trend === 'up')   return <span style={{ color:'var(--good)', fontSize:12 }}>↑</span>;
  if (trend === 'down') return <span style={{ color:'var(--bad)',  fontSize:12 }}>↓</span>;
  return <span style={{ color:'var(--ink-3)', fontSize:12 }}>–</span>;
}

function AuthorityPage({ go }) {
  const c    = window.CP_CLIENT || {};
  const auth = c.authority || {};
  const pos  = auth.positions || {};
  const total = (pos.top3||0) + (pos.top10||0) + (pos.top30||0) + (pos.below30||0);

  return (
    <div>
      <div style={{ marginBottom:24 }}>
        <h2 className="hk-h3" style={{ marginBottom:4 }}>Domain Authority</h2>
        <p className="hk-small" style={{ color:'var(--ink-3)' }}>
          Live data from Ahrefs for <strong>{c.domain}</strong> · Updated {auth.updatedAt || c.auditDate}
        </p>
      </div>

      {/* ── Core metrics ────────────────────────────────────── */}
      <div style={{ display:'grid', gridTemplateColumns:'repeat(auto-fill,minmax(155px,1fr))', gap:10, marginBottom:24 }}>
        <StatCard label="Domain Rating"      value={auth.domainRating ?? '—'} sub="/100"   color="var(--accent)"
          hint="Domain Rating (DR) measures the strength of your backlink profile on a 0–100 scale. Most local businesses score 10–30. Growing this takes time."/>
        <StatCard label="Monthly Traffic"    value={(auth.organicTraffic||0).toLocaleString()}
          hint="Estimated number of people visiting your site each month from Google search results (organic, not paid ads)."/>
        <StatCard label="Organic Keywords"   value={(auth.organicKeywords||0).toLocaleString()}
          hint="How many different search terms your site ranks for on Google. Even ranking on page 2 counts — those are opportunities to improve."/>
        <StatCard label="Backlinks"          value={(auth.backlinks||0).toLocaleString()}
          hint="Total number of links from other websites pointing to yours. Links are like 'votes of trust' — more quality links = higher Google rankings."/>
        <StatCard label="Referring Domains"  value={(auth.referringDomains||0).toLocaleString()}
          hint="Number of unique websites linking to you. 50 links from 50 different sites is much more valuable than 50 links from just one site."/>
        <StatCard label="Traffic Value (est)" value={`$${auth.trafficValue||0}`} color="var(--good)"
          hint="What your organic traffic would cost in Google Ads. It shows the real dollar value of your SEO — this is money you're NOT paying per click."/>
      </div>

      {/* ── Traffic trend + Position breakdown ──────────────── */}
      <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:12, marginBottom:24 }}>
        {/* Traffic chart */}
        <div style={{ background:'var(--surface)', border:'1px solid var(--border)', borderRadius:'var(--r-3)', padding:'16px 18px' }}>
          <div style={{ display:'flex', alignItems:'center', gap:6, marginBottom:4 }}>
            <span className="hk-h4">Traffic Trend</span>
            <Hint text="Estimated organic visitors per month from Google. Upward trend = your SEO is working. Flat or down = you need action." width={220}/>
          </div>
          <div className="hk-tiny" style={{ color:'var(--ink-3)', marginBottom:12 }}>Last 6 months · organic visits/mo</div>
          {auth.trafficTrend && <TrafficChart data={auth.trafficTrend}/>}
          {auth.trafficTrend && (
            <div style={{ display:'flex', justifyContent:'space-between', marginTop:8 }}>
              {auth.trafficTrend.map(d => (
                <div key={d.month} className="hk-tiny" style={{ color:'var(--ink-3)', textAlign:'center' }}>
                  <div style={{ color:'var(--ink-2)', fontWeight:600, fontSize:12 }}>{d.traffic}</div>
                  {d.month}
                </div>
              ))}
            </div>
          )}
        </div>

        {/* Position distribution */}
        <div style={{ background:'var(--surface)', border:'1px solid var(--border)', borderRadius:'var(--r-3)', padding:'16px 18px' }}>
          <div style={{ display:'flex', alignItems:'center', gap:6, marginBottom:4 }}>
            <span className="hk-h4">Keyword Rankings</span>
            <Hint text="Shows how your keywords are distributed across Google's search results pages. Top 3 gets ~60% of all clicks — that's the sweet spot." width={210}/>
          </div>
          <div className="hk-tiny" style={{ color:'var(--ink-3)', marginBottom:16 }}>{total} keywords tracked</div>
          <div style={{ display:'flex', flexDirection:'column', gap:10 }}>
            <PositionBar label="Top 3"    count={pos.top3||0}    total={total} color="var(--good)"/>
            <PositionBar label="Top 10"   count={pos.top10||0}   total={total} color="var(--accent)"/>
            <PositionBar label="Top 30"   count={pos.top30||0}   total={total} color="var(--warn)"/>
            <PositionBar label="31+"      count={pos.below30||0} total={total} color="var(--surface-3)"/>
          </div>
          <div style={{ marginTop:16, display:'flex', gap:16, flexWrap:'wrap' }}>
            {[['Top 3',pos.top3,pos.top3>0?'good':'ink-3'],['Top 10',pos.top10,'ink-2'],['Top 30',pos.top30,'ink-3']].map(([l,v,c])=>(
              <div key={l} style={{ textAlign:'center' }}>
                <div style={{ fontSize:20, fontWeight:700, color:`var(--${c})` }}>{v||0}</div>
                <div className="hk-tiny" style={{ color:'var(--ink-3)' }}>{l}</div>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* ── Top keywords table ───────────────────────────────── */}
      <div style={{ background:'var(--surface)', border:'1px solid var(--border)', borderRadius:'var(--r-3)', padding:'18px 20px', marginBottom:24 }}>
        <div className="hk-h4" style={{ marginBottom:14 }}>Top Organic Keywords</div>
        <div style={{ overflowX:'auto' }}>
          <table style={{ width:'100%', borderCollapse:'collapse', fontSize:13 }}>
            <thead>
              <tr style={{ borderBottom:'1px solid var(--border)' }}>
                {[
                  { label:'Keyword' },
                  { label:'Pos.' },
                  { label:'Volume', hint:'How many times per month people search this term on Google.' },
                  { label:'Traffic', hint:'How many of those searches actually come to your site.' },
                  { label:'Difficulty', hint:'KD = Keyword Difficulty. 0–100. Under 30 = easier to rank. Over 60 = very competitive — needs strong backlinks.' },
                  { label:'Trend' },
                ].map(({ label, hint }) => (
                  <th key={label} style={{ textAlign:label==='Keyword'?'left':'center', padding:'0 10px 10px', color:'var(--ink-3)', fontWeight:600, fontSize:11.5, whiteSpace:'nowrap' }}>
                    <span style={{ display:'inline-flex', alignItems:'center', gap:4 }}>
                      {label}
                      {hint && <Hint text={hint} width={210}/>}
                    </span>
                  </th>
                ))}
              </tr>
            </thead>
            <tbody>
              {(auth.topKeywords||[]).map((kw, i) => (
                <tr key={i} style={{ borderBottom:'1px solid var(--surface-3)' }}>
                  <td style={{ padding:'10px 10px', color:'var(--ink)', fontWeight:500 }}>{kw.keyword}</td>
                  <td style={{ padding:'10px 10px', textAlign:'center' }}>
                    <span style={{ fontWeight:700, color: kw.pos<=3?'var(--good)':kw.pos<=10?'var(--accent)':'var(--ink-2)' }}>#{kw.pos}</span>
                  </td>
                  <td style={{ padding:'10px 10px', textAlign:'center', color:'var(--ink-2)' }}>{kw.vol?.toLocaleString()}</td>
                  <td style={{ padding:'10px 10px', textAlign:'center', color:'var(--accent)', fontWeight:600 }}>{kw.traffic}</td>
                  <td style={{ padding:'10px 10px', textAlign:'center' }}><DiffBadge diff={kw.diff}/></td>
                  <td style={{ padding:'10px 10px', textAlign:'center' }}><TrendArrow trend={kw.trend}/></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {/* ── Top referrers ────────────────────────────────────── */}
      <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:12 }}>
        <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:14 }}>
            <span className="hk-h4">Top Referring Domains</span>
            <Hint text="Websites linking to you. 'Dofollow' links pass SEO value; 'nofollow' links don't. DR score shows how strong that linking site is." width={230}/>
          </div>

          {/* First 2 referrers — always visible */}
          <div style={{ display:'flex', flexDirection:'column', gap:10, marginBottom:10 }}>
            {(auth.topReferrers||[]).slice(0,2).map((r, i) => (
              <div key={i} style={{ display:'flex', alignItems:'center', gap:10 }}>
                <div style={{ width:28, height:28, borderRadius:6, background:'var(--surface-3)', display:'flex', alignItems:'center', justifyContent:'center', fontSize:11, fontWeight:700, color:'var(--ink-3)', flexShrink:0 }}>
                  {r.dr}
                </div>
                <div style={{ flex:1, minWidth:0 }}>
                  <div style={{ fontSize:13, fontWeight:500, color:'var(--ink)', whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{r.domain}</div>
                  <div className="hk-tiny" style={{ color:'var(--ink-3)' }}>"{r.anchor}"</div>
                </div>
                <span style={{ fontSize:11, fontWeight:600, padding:'2px 7px', borderRadius:4,
                  color: r.dofollow?'var(--good)':'var(--ink-3)',
                  background: r.dofollow?'var(--good-soft)':'var(--surface-3)' }}>
                  {r.dofollow?'dofollow':'nofollow'}
                </span>
              </div>
            ))}
          </div>

          {/* Remaining referrers — locked */}
          {(auth.topReferrers||[]).length > 2 && (
            <LockedSection
              label="Full Backlink Profile Unlocked on Call"
              sub={`${(auth.topReferrers||[]).length - 2} more referring domains analyzed — see which sites link to you and which need disavowing.`}
              ctaLabel="See Full Backlink Report"
            >
              <div style={{ display:'flex', flexDirection:'column', gap:10 }}>
                {(auth.topReferrers||[]).slice(2).map((r, i) => (
                  <div key={i} style={{ display:'flex', alignItems:'center', gap:10 }}>
                    <div style={{ width:28, height:28, borderRadius:6, background:'var(--surface-3)', display:'flex', alignItems:'center', justifyContent:'center', fontSize:11, fontWeight:700, color:'var(--ink-3)', flexShrink:0 }}>
                      {r.dr}
                    </div>
                    <div style={{ flex:1, minWidth:0 }}>
                      <div style={{ fontSize:13, fontWeight:500, color:'var(--ink)' }}>{r.domain}</div>
                      <div className="hk-tiny" style={{ color:'var(--ink-3)' }}>"{r.anchor}"</div>
                    </div>
                    <span style={{ fontSize:11, fontWeight:600, padding:'2px 7px', borderRadius:4,
                      color: r.dofollow?'var(--good)':'var(--ink-3)',
                      background: r.dofollow?'var(--good-soft)':'var(--surface-3)' }}>
                      {r.dofollow?'dofollow':'nofollow'}
                    </span>
                  </div>
                ))}
              </div>
            </LockedSection>
          )}
        </div>

        {/* Traffic by country */}
        <div style={{ background:'var(--surface)', border:'1px solid var(--border)', borderRadius:'var(--r-3)', padding:'18px 20px' }}>
          <div className="hk-h4" style={{ marginBottom:14 }}>Traffic by Country</div>
          <div style={{ display:'flex', flexDirection:'column', gap:12 }}>
            {(auth.countries||[]).map((ct, i) => (
              <div key={i} style={{ display:'flex', alignItems:'center', gap:10 }}>
                <span style={{ fontSize:18, flexShrink:0 }}>{ct.flag}</span>
                <div style={{ flex:1, minWidth:0 }}>
                  <div style={{ display:'flex', justifyContent:'space-between', marginBottom:4 }}>
                    <span style={{ fontSize:13, color:'var(--ink)', fontWeight:500 }}>{ct.country}</span>
                    <span style={{ fontSize:12.5, color:'var(--ink-2)', fontWeight:600 }}>{ct.share}%</span>
                  </div>
                  <div style={{ height:5, background:'var(--surface-3)', borderRadius:99, overflow:'hidden' }}>
                    <div style={{ width:`${ct.share}%`, height:'100%', background:'var(--accent)', borderRadius:99 }}/>
                  </div>
                </div>
                <div style={{ fontSize:12, color:'var(--ink-3)', flexShrink:0, width:36, textAlign:'right' }}>{ct.traffic}</div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

CP_PAGES.authority = { title: 'Domain Authority', component: AuthorityPage };

})();
