// Site Links — internal linking structure, orphan pages, link depth

(function () {

function DepthBar({ depth, max, count }) {
  const pct = Math.min(100, Math.round((count/max)*100));
  const colors = ['var(--good)','var(--accent)','var(--warn)','var(--bad)','var(--ink-3)'];
  const color  = colors[Math.min(depth-1, colors.length-1)];
  return (
    <div style={{ display:'flex', alignItems:'center', gap:10 }}>
      <div style={{ width:55, fontSize:12.5, color:'var(--ink-3)', flexShrink:0 }}>Level {depth}</div>
      <div style={{ flex:1, height:7, 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-2)', textAlign:'right', flexShrink:0 }}>{count}</div>
    </div>
  );
}

function LinksPage({ go }) {
  const c    = window.CP_CLIENT || {};
  const lnk  = c.links || {};
  const intl = lnk.internal || {};
  const extl = lnk.external || {};

  const totalPages    = intl.totalPages    || 47;
  const orphanPages   = intl.orphanPages   || 6;
  const avgLinks      = intl.avgLinksPerPage || 3.2;
  const maxDepth      = intl.maxDepth      || 5;
  const topLinked     = intl.topLinked     || [
    { page:'Homepage',    links:42 },
    { page:'Custom Cakes',links:18 },
    { page:'Contact',     links:16 },
    { page:'Order Now',   links:14 },
  ];
  const outbound      = extl.outboundLinks || 12;
  const brokenOut     = extl.brokenOutbound|| 2;

  const depthData = [
    { depth:1, count:1   },
    { depth:2, count:8   },
    { depth:3, count:21  },
    { depth:4, count:13  },
    { depth:5, count:4   },
  ];
  const maxDepthCount = Math.max(...depthData.map(d=>d.count));

  const ORPHAN_PAGES = intl.orphanList || [
    '/blog/summer-baking-tips-2023',
    '/blog/easter-bread-2022',
    '/specials/valentines-2023',
    '/about/team',
    '/blog/sourdough-starter-guide',
    '/menu/seasonal-fall-2023',
  ];

  return (
    <div>
      <div style={{ marginBottom:24 }}>
        <h2 className="hk-h3" style={{ marginBottom:4 }}>Site Links</h2>
        <p className="hk-small" style={{ color:'var(--ink-3)' }}>
          Internal linking structure for <strong>{c.domain}</strong>
        </p>
      </div>

      {/* Stats */}
      <div style={{ display:'grid', gridTemplateColumns:'repeat(auto-fill,minmax(148px,1fr))', gap:10, marginBottom:24 }}>
        {[
          { label:'Total Pages',        value:totalPages,           color:'var(--ink)',    hint:'Total pages crawled on your website.' },
          { label:'Orphan Pages',       value:orphanPages,          color:'var(--bad)',    hint:'Pages with no internal links pointing to them. Google has difficulty finding and ranking these pages.' },
          { label:'Avg Links / Page',   value:avgLinks,             color:avgLinks>=5?'var(--good)':'var(--warn)', hint:'Average number of internal links per page. Under 3 means pages aren\'t well connected — Google uses links to discover and rank content.' },
          { label:'Max Click Depth',    value:maxDepth,             color:maxDepth<=3?'var(--good)':'var(--bad)', hint:'Clicks from homepage to reach the deepest page. Over 3 = Google may not crawl those pages often. Target: all important pages within 3 clicks.' },
          { label:'Outbound Links',     value:outbound,             color:'var(--ink)',    hint:'Links from your site to other websites. Linking to credible sources (suppliers, local directories) can help trust signals.' },
          { label:'Broken Outbound',    value:brokenOut,            color:brokenOut>0?'var(--bad)':'var(--good)', hint:'Links from your site that point to pages that no longer exist (404). These should be fixed or removed.' },
        ].map(m => (
          <div key={m.label} style={{ background:'var(--surface)', border:'1px solid var(--border)', borderRadius:'var(--r-3)', padding:'14px 16px' }}>
            <div style={{ fontSize:26, fontWeight:700, color:m.color, lineHeight:1, marginBottom:5 }}>{m.value}</div>
            <div style={{ display:'flex', alignItems:'center', gap:4 }}>
              <div className="hk-tiny" style={{ color:'var(--ink-3)' }}>{m.label}</div>
              <Hint text={m.hint} width={220}/>
            </div>
          </div>
        ))}
      </div>

      {/* Click depth + Top linked pages */}
      <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:12, marginBottom:24 }}>
        <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:4 }}>
            <span className="hk-h4">Page Depth Distribution</span>
            <Hint text="How many clicks from your homepage to reach each page. Pages at depth 4+ are hard for Google (and users) to find. Important content should be within 3 clicks." width={240}/>
          </div>
          <div className="hk-tiny" style={{ color:'var(--ink-3)', marginBottom:16 }}>{totalPages} pages total</div>
          <div style={{ display:'flex', flexDirection:'column', gap:10 }}>
            {depthData.map(d => <DepthBar key={d.depth} depth={d.depth} count={d.count} max={maxDepthCount}/>)}
          </div>
          {maxDepth > 3 && (
            <div style={{ marginTop:14, padding:'10px 12px', background:'var(--warn-soft)', borderRadius:'var(--r-2)' }}>
              <div className="hk-tiny" style={{ color:'var(--ink-2)', lineHeight:1.5 }}>
                {depthData.filter(d=>d.depth>=4).reduce((s,d)=>s+d.count,0)} pages are buried 4+ clicks deep. Move important content closer to the homepage.
              </div>
            </div>
          )}
        </div>

        <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:4 }}>
            <span className="hk-h4">Most Linked Pages</span>
            <Hint text="Pages with the most internal links get the most 'link equity' — Google sees them as your most important pages. Make sure your revenue pages (order, services) are highly linked." width={240}/>
          </div>
          <div className="hk-tiny" style={{ color:'var(--ink-3)', marginBottom:16 }}>By internal link count</div>
          <div style={{ display:'flex', flexDirection:'column', gap:10 }}>
            {topLinked.map((p,i) => {
              const pct = Math.round((p.links/topLinked[0].links)*100);
              return (
                <div key={i}>
                  <div style={{ display:'flex', justifyContent:'space-between', marginBottom:5 }}>
                    <span style={{ fontSize:13, color:'var(--ink-2)' }}>{p.page}</span>
                    <span style={{ fontSize:12.5, fontWeight:600, color:'var(--ink)' }}>{p.links} links</span>
                  </div>
                  <div style={{ height:6, background:'var(--surface-3)', borderRadius:99, overflow:'hidden' }}>
                    <div style={{ width:`${pct}%`, height:'100%', background:'var(--accent)', borderRadius:99 }}/>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </div>

      {/* Orphan pages — show 2, lock the rest */}
      <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:8, marginBottom:4 }}>
          <span className="hk-h4" style={{ color:'var(--bad)' }}>⚠ Orphan Pages ({orphanPages})</span>
          <Hint text="Orphan pages have zero internal links pointing to them. Google discovers pages through links — an orphan page may never be crawled or ranked." width={240}/>
        </div>
        <div className="hk-tiny" style={{ color:'var(--ink-3)', marginBottom:16 }}>
          These pages exist but nothing links to them — Google can't easily find or rank them
        </div>

        {/* Show first 2 */}
        <div style={{ display:'flex', flexDirection:'column', gap:8, marginBottom:10 }}>
          {ORPHAN_PAGES.slice(0,2).map((url,i) => (
            <div key={i} style={{ display:'flex', alignItems:'center', gap:10, padding:'10px 12px', background:'var(--bad-soft)', borderRadius:'var(--r-2)', border:'1px solid color-mix(in srgb,var(--bad) 20%,transparent)' }}>
              <Icon name="globe" size={14} style={{ color:'var(--bad)', flexShrink:0 }}/>
              <span style={{ fontSize:12.5, color:'var(--ink-2)', fontFamily:'var(--font-mono)' }}>{url}</span>
              <span style={{ marginLeft:'auto', fontSize:11, fontWeight:700, color:'var(--bad)', flexShrink:0 }}>0 links</span>
            </div>
          ))}
        </div>

        {/* Lock the rest */}
        <LockedSection
          label={`${orphanPages - 2} more orphan pages — Book a Call to get the full fix plan`}
          sub="See all orphan pages and get a step-by-step internal linking plan to connect them."
          ctaLabel="Get Link Audit"
        >
          <div style={{ display:'flex', flexDirection:'column', gap:8 }}>
            {ORPHAN_PAGES.slice(2).map((url,i) => (
              <div key={i} style={{ display:'flex', alignItems:'center', gap:10, padding:'10px 12px', background:'var(--bad-soft)', borderRadius:'var(--r-2)', border:'1px solid color-mix(in srgb,var(--bad) 20%,transparent)' }}>
                <Icon name="globe" size={14} style={{ color:'var(--bad)', flexShrink:0 }}/>
                <span style={{ fontSize:12.5, color:'var(--ink-2)', fontFamily:'var(--font-mono)' }}>{url}</span>
                <span style={{ marginLeft:'auto', fontSize:11, fontWeight:700, color:'var(--bad)', flexShrink:0 }}>0 links</span>
              </div>
            ))}
          </div>
        </LockedSection>
      </div>

      {/* Quick wins */}
      <div style={{ background:'var(--surface)', border:'1px solid var(--border)', borderRadius:'var(--r-3)', padding:'18px 20px' }}>
        <div className="hk-h4" style={{ marginBottom:14 }}>Internal Linking Quick Wins</div>
        {(lnk.quickWins || [
          { text:'Link from every blog post to your Custom Cakes page', impact:'High', hint:'Your money page — every blog reader should have a path to it.' },
          { text:'Add a "You might also like" section at the bottom of each recipe post', impact:'High' },
          { text:'Create a /sitemap or /all-posts page to connect orphan blog posts', impact:'Med' },
          { text:'Add breadcrumb navigation (helps depth + schema)', impact:'Med', hint:'Breadcrumbs reduce click depth AND qualify as BreadcrumbList schema for rich snippets.' },
          { text:'Fix 2 broken outbound links', impact:'Low' },
        ]).map((item,i) => (
          <div key={i} style={{ display:'flex', alignItems:'flex-start', gap:12, padding:'10px 0', borderBottom:i<4?'1px solid var(--surface-3)':'' }}>
            <div style={{ flex:1, display:'flex', alignItems:'center', gap:5 }}>
              <span style={{ fontSize:13, color:'var(--ink)', lineHeight:1.5 }}>{item.text}</span>
              {item.hint && <Hint text={item.hint} width={220}/>}
            </div>
            <span style={{ fontSize:11, fontWeight:700, padding:'2px 7px', borderRadius:4, flexShrink:0,
              color:item.impact==='High'?'var(--bad)':item.impact==='Med'?'var(--warn)':'var(--ink-3)',
              background:item.impact==='High'?'var(--bad-soft)':item.impact==='Med'?'var(--warn-soft)':'var(--surface-3)' }}>
              {item.impact}
            </span>
          </div>
        ))}
      </div>
    </div>
  );
}

CP_PAGES.links = { title: 'Site Links', component: LinksPage };

})();
