// Blog Analytics — content performance, freshness, traffic by post

(function () {

function RankBadge({ pos }) {
  if (!pos) return <span style={{ fontSize:12, color:'var(--ink-3)' }}>Not ranked</span>;
  const color = pos <= 5 ? 'var(--good)' : pos <= 20 ? 'var(--accent)' : 'var(--ink-3)';
  return <span style={{ fontWeight:700, color, fontSize:13 }}>#{pos}</span>;
}

function TimeBar({ seconds, max }) {
  const pct = Math.min(100, Math.round((seconds/max)*100));
  const color = pct > 60 ? 'var(--good)' : pct > 30 ? 'var(--warn)' : 'var(--bad)';
  return (
    <div style={{ display:'flex', alignItems:'center', gap:8 }}>
      <div style={{ flex:1, height:5, background:'var(--surface-3)', borderRadius:99, overflow:'hidden' }}>
        <div style={{ width:`${pct}%`, height:'100%', background:color, borderRadius:99 }}/>
      </div>
    </div>
  );
}

function BlogPage({ go }) {
  const c   = window.CP_CLIENT || {};
  const bl  = c.blog || {};

  const posts = bl.topPosts || [
    { title:'How to Make the Perfect Sourdough at Home', visits:342, avgTime:'3:12', avgSec:192, ranking:7,  category:'Recipes',  updated:'Jan 2025' },
    { title:'Chicago\'s Best Birthday Cake Traditions',  visits:189, avgTime:'2:45', avgSec:165, ranking:14, category:'Local',    updated:'Oct 2024' },
    { title:'Gluten-Free Baking: Our Story',             visits:94,  avgTime:'1:58', avgSec:118, ranking:22, category:'Story',    updated:'Aug 2024' },
    { title:'Easter Bread Guide 2025',                   visits:67,  avgTime:'2:10', avgSec:130, ranking:31, category:'Seasonal', updated:'Mar 2024' },
  ];

  const totalPosts = bl.totalPosts ?? 8;
  const needUpdate = bl.postsNeedingUpdate ?? 3;
  const maxSec     = Math.max(...posts.map(p => p.avgSec || 60));

  return (
    <div>
      <div style={{ marginBottom:24 }}>
        <h2 className="hk-h3" style={{ marginBottom:4 }}>Blog Analytics</h2>
        <p className="hk-small" style={{ color:'var(--ink-3)' }}>
          Content performance for <strong>{c.domain}</strong> · {c.auditDate}
        </p>
      </div>

      {/* Stats */}
      <div style={{ display:'grid', gridTemplateColumns:'repeat(auto-fill,minmax(150px,1fr))', gap:10, marginBottom:24 }}>
        {[
          { label:'Total Posts',      value:totalPosts,  color:'var(--ink)',    hint:'Total blog posts published on your site.' },
          { label:'Bringing Traffic', value:posts.filter(p=>p.ranking&&p.ranking<=30).length, color:'var(--good)', hint:'Posts currently ranking on Google (position 1–30) and sending visitors to your site.' },
          { label:'Need Update',      value:needUpdate,  color:'var(--warn)',   hint:'Posts older than 12 months — Google favors fresh content, especially for seasonal or location-based topics.' },
          { label:'Total Readers',    value:posts.reduce((s,p)=>s+(p.visits||0),0).toLocaleString(), color:'var(--accent)', hint:'Estimated total monthly readers from organic search across all blog posts.' },
        ].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={210}/>
            </div>
          </div>
        ))}
      </div>

      {/* Top posts table */}
      <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:16 }}>
          <span className="hk-h4">Top Performing Posts</span>
          <Hint text="Blog posts driving the most organic traffic. Time on page shows how engaging the content is — over 2 min is good for a recipe or story post." width={240}/>
        </div>
        <div style={{ display:'flex', flexDirection:'column', gap:0 }}>
          {/* Header */}
          <div style={{ display:'grid', gridTemplateColumns:'1fr 70px 80px 100px 80px', gap:12, padding:'0 0 10px', borderBottom:'1px solid var(--border)' }}>
            {['Post','Visitors','Avg Time','Ranking','Updated'].map(h => (
              <div key={h} style={{ fontSize:11.5, fontWeight:600, color:'var(--ink-3)', textAlign:h==='Post'?'left':'center' }}>{h}</div>
            ))}
          </div>
          {posts.length === 0 && (
            <div style={{ padding:'18px 4px', fontSize:13, color:'var(--ink-3)', lineHeight:1.6 }}>
              No posts found on your domain. Your blog currently lives on <strong style={{ color:'var(--ink-2)' }}>{bl.offDomain || 'a third-party platform'}</strong>, so its content builds <em>that</em> domain — not yours. Migrating it on-domain is the #1 content opportunity in this audit.
            </div>
          )}
          {posts.map((p,i) => (
            <div key={i} style={{ display:'grid', gridTemplateColumns:'1fr 70px 80px 100px 80px', gap:12, padding:'12px 0', borderBottom:i<posts.length-1?'1px solid var(--surface-3)':'' }}>
              <div style={{ minWidth:0 }}>
                <div style={{ fontSize:13, fontWeight:500, color:'var(--ink)', overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap', marginBottom:3 }}>{p.title}</div>
                <span style={{ fontSize:11, fontWeight:600, padding:'1px 6px', borderRadius:4, background:'var(--surface-3)', color:'var(--ink-3)' }}>{p.category}</span>
              </div>
              <div style={{ textAlign:'center', fontSize:13.5, fontWeight:700, color:'var(--ink-2)', paddingTop:4 }}>{(p.visits||0).toLocaleString()}</div>
              <div style={{ paddingTop:4 }}>
                <div style={{ fontSize:13, fontWeight:600, color:'var(--ink-2)', textAlign:'center', marginBottom:5 }}>{p.avgTime}</div>
                <TimeBar seconds={p.avgSec||60} max={maxSec}/>
              </div>
              <div style={{ textAlign:'center', paddingTop:4 }}><RankBadge pos={p.ranking}/></div>
              <div style={{ textAlign:'center', fontSize:12, color:'var(--ink-3)', paddingTop:6 }}>{p.updated}</div>
            </div>
          ))}
        </div>
      </div>

      {/* Content health */}
      <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:14 }}>
            <span className="hk-h4">Content Freshness</span>
            <Hint text="Google gives a ranking boost to recently updated content. Pages older than 12 months, especially seasonal ones, should be refreshed regularly." width={230}/>
          </div>
          {(bl.freshness || [
            { label:'Updated < 3 months', count:1, color:'var(--good)' },
            { label:'3–6 months old',     count:2, color:'var(--accent)' },
            { label:'6–12 months old',    count:2, color:'var(--warn)' },
            { label:'Over 12 months',     count:3, color:'var(--bad)' },
          ]).map((row,i) => (
            <div key={i} style={{ display:'flex', alignItems:'center', justifyContent:'space-between', padding:'8px 0', borderBottom:i<3?'1px solid var(--surface-3)':'' }}>
              <div style={{ display:'flex', alignItems:'center', gap:8 }}>
                <span style={{ width:8, height:8, borderRadius:'50%', background:row.color, display:'inline-block', flexShrink:0 }}/>
                <span style={{ fontSize:13, color:'var(--ink-2)' }}>{row.label}</span>
              </div>
              <span style={{ fontSize:14, fontWeight:700, color:row.color }}>{row.count} posts</span>
            </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:14 }}>
            <span className="hk-h4">Content Quick Wins</span>
          </div>
          {(bl.quickWins || [
            { text:'Refresh Easter Bread Guide with 2025 dates',  impact:'High', icon:'⚡' },
            { text:'Add schema markup to all recipe posts',        impact:'High', icon:'⚡' },
            { text:'Interlink bakery posts to Custom Cakes page',  impact:'Med',  icon:'↗' },
            { text:'Add FAQ section to Gluten-Free post',          impact:'Med',  icon:'↗' },
          ]).map((item,i) => (
            <div key={i} style={{ display:'flex', alignItems:'flex-start', gap:10, padding:'9px 0', borderBottom:i<3?'1px solid var(--surface-3)':'' }}>
              <span style={{ fontSize:16, flexShrink:0, lineHeight:1.4 }}>{item.icon}</span>
              <div style={{ flex:1, minWidth:0 }}>
                <div style={{ fontSize:13, color:'var(--ink)', lineHeight:1.5 }}>{item.text}</div>
              </div>
              <span style={{ fontSize:11, fontWeight:700, padding:'2px 7px', borderRadius:4, flexShrink:0,
                color:item.impact==='High'?'var(--bad)':'var(--warn)',
                background:item.impact==='High'?'var(--bad-soft)':'var(--warn-soft)' }}>
                {item.impact}
              </span>
            </div>
          ))}
        </div>
      </div>

      {/* Locked: full content strategy */}
      <LockedSection
        label="Full Content Strategy — Book a Call"
        sub="Get a 12-month content calendar, topic clusters, and content briefs written specifically for your business and target search trends."
        ctaLabel="Get Content Strategy"
      >
        <div style={{ background:'var(--surface)', border:'1px solid var(--border)', borderRadius:'var(--r-3)', padding:'18px 20px' }}>
          <div className="hk-h4" style={{ marginBottom:14 }}>Recommended Content Plan</div>
          {(bl.contentPlan || ['April: "Best Easter Brunch Spots Chicago 2025"','May: "How to Order a Custom Wedding Cake in Chicago"','June: "Summer Birthday Party Cake Ideas"','August: "Back-to-School Cupcake Decorating Guide"']).map((t,i) => (
            <div key={i} style={{ padding:'10px 0', borderBottom:'1px solid var(--surface-3)', fontSize:13, color:'var(--ink)' }}>{t}</div>
          ))}
        </div>
      </LockedSection>
    </div>
  );
}

CP_PAGES.blog = { title: 'Blog Analytics', component: BlogPage };

})();
