/* v2/dashboard-pages-v2.jsx — 6 dashboard snippet pages
   Rendered inside ProductMockupLarge's <div class="showcase-main">.
   Data is about AnswerExposure. Style stays in the existing light
   dashboard idiom — NOT the dark mode from the screenshots.
*/

/* Shared small atoms ---------------------------------------------- */

// Counter — animates a number from 0 up to `to` over `dur` ms.
// Remounts automatically when the active page changes (parent re-renders).
const Counter = ({ to, dur = 1000, suffix = '', prefix = '', decimals = 0 }) => {
  const [v, setV] = React.useState(0);
  React.useEffect(() => {
    if (matchMedia('(prefers-reduced-motion: reduce)').matches) { setV(to); return; }
    let raf, start;
    const step = (t) => {
      if (!start) start = t;
      const p = Math.min(1, (t - start) / dur);
      // easeOutCubic
      const eased = 1 - Math.pow(1 - p, 3);
      setV(to * eased);
      if (p < 1) raf = requestAnimationFrame(step);
    };
    raf = requestAnimationFrame(step);
    return () => cancelAnimationFrame(raf);
  }, [to, dur]);
  const rounded = decimals > 0 ? v.toFixed(decimals) : Math.round(v);
  // thousands separator for large ints
  const formatted = decimals > 0 ? rounded : Number(rounded).toLocaleString();
  return <>{prefix}{formatted}{suffix}</>;
};

const DashScore = ({ label, value, max, delta, tone='pos' }) => (
  <div className="ds-score">
    <div className="ds-score-label">{label}</div>
    <div className="ds-score-row">
      <div className="ds-score-big"><Counter to={value} dur={1100}/></div>
      <div className="ds-score-max">/{max}</div>
    </div>
    <div className="ds-score-bar">
      <span style={{width: (value/max*100)+'%', background: tone==='warn' ? 'var(--warn, #E7A100)' : tone==='neg' ? '#E54545' : 'var(--violet)'}}/>
    </div>
    {delta && <div className={"ds-score-delta " + tone}>{delta}</div>}
  </div>
);

const DashPill = ({ tone='neutral', children }) => (
  <span className={"ds-pill ds-pill-" + tone}>{children}</span>
);

/* 1. OVERVIEW ----------------------------------------------------- */
const PageOverview = ({ activeCount, scale, citationsN, sovN, queriesN, drawn, pathLen, youPath, endY, youPathRef, hover, setHover, hoverPt, rows, flash }) => (
  <>
    <div className="ds-alert">
      <span className="ds-alert-ico">⚠</span>
      <span>Your Awareness score dropped <b>26 pts</b> this week. <a href="#" className="ds-link">View gaps →</a></span>
    </div>

    <div className="showcase-kpis">
      <div className="sk">
        <div className="kpi-label">Your AI score</div>
        <div className="kpi-big" style={{color:'var(--violet)'}}><Counter to={75}/><span style={{fontSize:16, color:'var(--muted)', fontWeight:500, marginLeft:4}}>/100</span></div>
        <div className="kpi-delta">↑ 5 pts · AI recommends your brand</div>
      </div>
      <div className="sk">
        <div className="kpi-label">Keyword visibility</div>
        <div className="kpi-big" style={{color:'var(--warn, #E7A100)'}}><Counter to={25}/><span style={{fontSize:16, color:'var(--muted)', fontWeight:500, marginLeft:4}}>/62</span></div>
        <div className="ds-mini-bar" style={{marginTop:6}}>
          <span style={{width:'40%', background:'var(--warn, #E7A100)'}}/>
        </div>
      </div>
      <div className="sk">
        <div className="kpi-label">Mentions · 7d</div>
        <div className="kpi-big"><Counter to={181}/></div>
        <div className="kpi-delta">↑ 60 vs prev 7d</div>
      </div>
      <div className="sk ds-kpi-risk">
        <div className="kpi-label">At risk</div>
        <div className="kpi-big" style={{color:'#00A81E'}}><Counter to={0}/></div>
        <div className="kpi-delta" style={{color:'var(--muted)'}}>competitors ahead</div>
      </div>
    </div>

    <div className="ds-two-col">
      <div className="ds-card">
        <div className="ds-card-head"><span className="ds-card-ico">👁</span> What AI knows</div>
        <p className="ds-card-body">
          AI platforms know <b>AnswerExposure</b> as a done-for-you AEO service
          that publishes brand mentions on Reddit, Substack and press — the sources
          ChatGPT, Claude, Perplexity and Google AI cite. Descriptions are accurate
          on the basics. The biggest gap: proof points and third-party validation.
        </p>
      </div>
      <div className="ds-card">
        <div className="ds-card-head"><span className="ds-card-ico">⚠</span> Key gaps</div>
        <div className="ds-gap-list">
          <div className="ds-gap-row"><DashPill tone="warn">INCOMPLETE</DashPill> AI knows the service, not the proof behind its claims</div>
          <div className="ds-gap-row"><DashPill tone="neg">NEGATIVE</DashPill> Some AI answers suggest low-quality placements</div>
          <div className="ds-gap-row"><DashPill tone="warn">INCOMPLETE</DashPill> Described as generic PR rather than differentiated</div>
        </div>
        <a href="#" className="ds-link ds-card-foot">View full analysis →</a>
      </div>
    </div>

    <div className="chart-frame">
      <div className="chart-head">
        <div className="chart-title">Mentions trend · 30d</div>
        <div className="chart-legend">
          <span><span className="sw" style={{background:'var(--violet)'}}/> Your brand</span>
          <span><span className="sw" style={{background:'var(--cyan)'}}/> Competitor A</span>
          <span><span className="sw" style={{background:'var(--hair-2)'}}/> Competitor B</span>
        </div>
      </div>
      <svg viewBox="0 0 600 180" preserveAspectRatio="none" style={{width:'100%', height:160, display:'block'}}
           onMouseMove={(e) => {
             const r = e.currentTarget.getBoundingClientRect();
             const x = ((e.clientX - r.left) / r.width) * 600;
             setHover(Math.max(0, Math.min(600, x)));
           }}
           onMouseLeave={() => setHover(null)}>
        <defs>
          <linearGradient id="gradL1" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor="#635BFF" stopOpacity="0.28"/>
            <stop offset="100%" stopColor="#635BFF" stopOpacity="0"/>
          </linearGradient>
        </defs>
        {[0,1,2,3,4].map(i => (
          <line key={i} x1="0" x2="600" y1={i*35+10} y2={i*35+10} stroke="#E6EBF1" strokeDasharray="2 4"/>
        ))}
        <path d="M0,150 C60,148 120,146 180,150 C240,148 300,144 360,146 C420,148 480,144 540,146 L600,142"
              stroke="#CDD5DF" strokeWidth="1.8" fill="none" strokeLinecap="round"/>
        <path d="M0,130 C60,126 120,120 180,118 C240,116 300,108 360,102 C420,96 480,88 540,80 L600,74"
              stroke="#00D4FF" strokeWidth="2" fill="none" strokeLinecap="round"/>
        <path d={youPath}
              ref={youPathRef}
              stroke="#635BFF" strokeWidth="2.5" fill="none" strokeLinecap="round" strokeLinejoin="round"
              style={{
                strokeDasharray: pathLen || 2000,
                strokeDashoffset: drawn ? 0 : (pathLen || 2000),
                transition: 'stroke-dashoffset 1400ms cubic-bezier(.4,.0,.2,1), d 600ms cubic-bezier(.4,.0,.2,1)'
              }}/>
        <path d={youPath + ' L600,180 L0,180 Z'}
              fill="url(#gradL1)"
              style={{transition: 'd 600ms cubic-bezier(.4,.0,.2,1), opacity 500ms ease 900ms', opacity: drawn ? 1 : 0}}/>
        <circle cx="600" cy={endY} r="5" fill="#635BFF" style={{transition:'cy 600ms cubic-bezier(.4,.0,.2,1), opacity 400ms ease 1200ms', opacity: drawn ? 1 : 0}}/>
        <circle cx="600" cy={endY} r="10" fill="#635BFF" opacity={drawn ? 0.2 : 0} className="endpoint-pulse"/>
        {hoverPt && (
          <g style={{pointerEvents:'none'}}>
            <circle cx={hoverPt.x} cy={hoverPt.y} r="10" fill="#635BFF" opacity="0.14"/>
            <circle cx={hoverPt.x} cy={hoverPt.y} r="5" fill="#fff" stroke="#635BFF" strokeWidth="2.5"/>
          </g>
        )}
      </svg>
    </div>

    <div className="ds-two-col">
      <div className="ds-card">
        <div className="ds-card-head">Keyword intent mix</div>
        <div className="ds-bar-stack">
          <span style={{width:'38%', background:'#E7A100'}}/>
          <span style={{width:'48%', background:'var(--violet)'}}/>
          <span style={{width:'14%', background:'#00D4FF'}}/>
        </div>
        <div className="ds-legend-row">
          <span><i style={{background:'#E7A100'}}/> Commercial (24)</span>
          <span><i style={{background:'var(--violet)'}}/> Informational (30)</span>
          <span><i style={{background:'#00D4FF'}}/> Transactional (8)</span>
        </div>
        <p className="ds-card-foot-note">52% of keywords have buying intent — highest-value AI targets.</p>
      </div>

      <div className="ds-card">
        <div className="ds-card-head">Sites dominating your keywords</div>
        {[
          {n:'youtube.com', v:90, c:13},
          {n:'semrush.com', v:72, c:10},
          {n:'prezly.com',  v:62, c:9},
          {n:'ereleases.com', v:55, c:8},
          {n:'prowly.com', v:48, c:7},
        ].map(s => (
          <div key={s.n} className="ds-site-row">
            <span className="ds-site-name">{s.n}</span>
            <div className="ds-site-bar"><span style={{width: s.v+'%'}}/></div>
            <span className="ds-site-count">{s.c}</span>
          </div>
        ))}
      </div>
    </div>
  </>
);

/* 2. AI PERCEPTION ------------------------------------------------ */
const PageAIPerception = () => {
  const [tab, setTab] = React.useState('ChatGPT');
  const tabs = [
    {k:'ChatGPT', Ico: ChatGPT},
    {k:'Claude', Ico: Claude},
    {k:'Perplexity', Ico: Perplexity},
    {k:'Gemini', Ico: Gemini},
  ];
  const perceptions = {
    ChatGPT: "AnswerExposure is described as the leading done-for-you AEO service — publishing mentions on Reddit, Substack and press to influence AI answers. Positioned as a category-defining platform, though specific proof points are thin.",
    Claude: "Described as a specialist in AI visibility with strong focus on third-party citations. Claude surfaces balanced coverage but notes limited independent reviews.",
    Perplexity: "Cited as the most active AEO vendor on Reddit and Substack. Perplexity frequently recommends AnswerExposure in 'how do I get cited by AI' threads.",
    Gemini: "Recognised as a done-for-you platform. Gemini's descriptions lean toward PR positioning and under-emphasise the technical citation tracking layer.",
  };
  return (
    <>
      <div className="ds-scores-grid">
        <DashScore label="Overall AI score" value={75} max={100} delta="↑ 5 pts" tone="pos"/>
        <DashScore label="AI awareness" value={84} max={100} delta="↑ 3 pts" tone="pos"/>
        <DashScore label="AI accuracy" value={84} max={100} delta="↑ 2 pts" tone="pos"/>
        <DashScore label="AI sentiment" value={56} max={100} delta="↓ 4 pts" tone="warn"/>
      </div>

      <div className="ds-alert ds-alert-warn">
        <span className="ds-alert-ico">💡</span>
        <span>AI platforms know you well. AI describes how you factually look, but doesn't actively recommend. <b>Sentiment is your biggest opportunity.</b></span>
      </div>

      <div className="ds-card">
        <div className="ds-card-head ds-card-head-split">
          <span>Gap analysis — AI platforms know the service, but not the proof</span>
          <a href="#" className="ds-link">12 citations created ▾</a>
        </div>
        <p className="ds-card-body" style={{marginBottom:14}}>
          Two authors understand AnswerExposure distributes press releases, but they do
          not consistently say <i>why</i> a customer would notice. One response mentions
          &quot;300+ outlets and 100m tier reach&quot; while another questions whether
          placements are actually high-value.
        </p>
        <div className="ds-citation-grid">
          {[
            ['Reddit Comment', 'Apr 19', 'live'],
            ['Substack Post',  'Apr 18', 'live'],
            ['Reddit Comment', 'Apr 18', 'live'],
            ['Substack Post',  'Apr 17', 'live'],
            ['Press Release',  'Apr 15', 'live'],
            ['Quora Answer',   'Apr 14', 'live'],
          ].map((c,i) => (
            <div key={i} className="ds-cite-mini">
              <DashPill tone="pos">Published</DashPill>
              <span className="ds-cite-type">{c[0]}</span>
              <span className="ds-cite-date">{c[1]}</span>
            </div>
          ))}
        </div>
      </div>

      <div className="ds-card">
        <div className="ds-card-head">What each AI platform says</div>
        <div className="ds-tab-row">
          {tabs.map(({k, Ico}) => (
            <button key={k}
                    className={"ds-tab" + (tab===k ? " active" : "")}
                    onClick={() => setTab(k)}>
              <Ico size={14} pad={0} bg="transparent" rounded={3}/> {k}
            </button>
          ))}
        </div>
        <div className="ds-tab-content">
          <p>{perceptions[tab]}</p>
        </div>
      </div>
    </>
  );
};

/* 3. KEYWORDS ----------------------------------------------------- */
const PageKeywords = () => {
  const [expanded, setExpanded] = React.useState('AnswerExposure');
  const brandKw = {
    kw: 'AnswerExposure',
    intent: 'brand',
    difficulty: 'Low',
    volume: '2.4k',
    rank: 1,
    trend: '+2',
  };
  const related = [
    {kw:'best AEO service for SaaS',     intent:'Commercial',    rank:1,  trend:'+3'},
    {kw:'how to get cited by ChatGPT',   intent:'Informational', rank:4,  trend:'+1'},
    {kw:'AI visibility monitoring',      intent:'Commercial',    rank:2,  trend:'—'},
    {kw:'press release for AI search',   intent:'Transactional', rank:6,  trend:'+2'},
    {kw:'reddit brand mentions tool',    intent:'Commercial',    rank:3,  trend:'+4'},
    {kw:'generative engine optimization',intent:'Informational', rank:9,  trend:'↓ 1'},
  ];
  return (
    <>
      <div className="showcase-kpis">
        <div className="sk">
          <div className="kpi-label">Total keywords</div>
          <div className="kpi-big"><Counter to={43}/></div>
          <div className="kpi-delta">↑ 7 this mo</div>
        </div>
        <div className="sk">
          <div className="kpi-label">Average rank</div>
          <div className="kpi-big"><Counter to={25}/><span style={{fontSize:16, color:'var(--muted)', fontWeight:500, marginLeft:4}}>/43</span></div>
          <div className="ds-mini-bar" style={{marginTop:6}}>
            <span style={{width:'58%', background:'var(--violet)'}}/>
          </div>
        </div>
        <div className="sk">
          <div className="kpi-label">Priority 1</div>
          <div className="kpi-big"><Counter to={2}/></div>
          <div className="kpi-delta">Need attention</div>
        </div>
        <div className="sk">
          <div className="kpi-label">AI platforms covered</div>
          <div className="kpi-big"><Counter to={6}/><span style={{fontSize:16, color:'var(--muted)', fontWeight:500, marginLeft:4}}>/6</span></div>
          <div className="kpi-delta">All tracked</div>
        </div>
      </div>

      <div className="ds-tab-row ds-filter-row">
        {['All', 'Commercial', 'Informational', 'Transactional'].map((f,i) => (
          <button key={f} className={"ds-tab" + (i===0 ? " active":"")}>{f}</button>
        ))}
      </div>

      <div className="ds-kw-table">
        <div className="ds-kw-head">
          <div>Keyword</div>
          <div>Intent</div>
          <div>Difficulty</div>
          <div>Volume</div>
          <div>Platforms</div>
          <div style={{textAlign:'right'}}>Rank</div>
          <div style={{textAlign:'right'}}>Trend</div>
        </div>

        {/* brand keyword (expanded) */}
        <div className={"ds-kw-row ds-kw-brand" + (expanded==='AnswerExposure' ? ' is-open' : '')}
             onClick={() => setExpanded(expanded==='AnswerExposure' ? null : 'AnswerExposure')}>
          <div className="ds-kw-name"><b>{brandKw.kw}</b></div>
          <div><DashPill tone="violet">Brand</DashPill></div>
          <div><DashPill tone="pos">Low</DashPill></div>
          <div className="mono">{brandKw.volume}</div>
          <div className="ds-plats">
            <ChatGPT size={14} pad={0} bg="transparent" rounded={3}/>
            <Claude size={14} pad={0} bg="transparent" rounded={3}/>
            <Perplexity size={14} pad={0} bg="transparent" rounded={3}/>
            <Gemini size={14} pad={0} bg="transparent" rounded={3}/>
          </div>
          <div className="mono" style={{textAlign:'right', fontWeight:700, color:'var(--violet)'}}>#{brandKw.rank}</div>
          <div className="mono" style={{textAlign:'right', color:'#00A81E', fontWeight:600}}>{brandKw.trend}</div>
        </div>

        {expanded==='AnswerExposure' && (
          <div className="ds-kw-detail">
            <div className="ds-detail-row">
              <div className="ds-detail-cell">
                <div className="ds-detail-label">Rank history · 6 weeks</div>
                <svg viewBox="0 0 200 48" style={{width:'100%', height:48}}>
                  <path d="M0,32 L33,24 L66,28 L100,16 L133,12 L166,8 L200,6"
                        stroke="var(--violet)" strokeWidth="2" fill="none" strokeLinecap="round"/>
                  <circle cx="200" cy="6" r="3.5" fill="var(--violet)"/>
                </svg>
              </div>
              <div className="ds-detail-cell">
                <div className="ds-detail-label">Platform share</div>
                <div className="ds-plat-share">
                  <div><ChatGPT size={12} pad={0} bg="transparent" rounded={3}/> <b>42%</b></div>
                  <div><Claude size={12} pad={0} bg="transparent" rounded={3}/> <b>24%</b></div>
                  <div><Perplexity size={12} pad={0} bg="transparent" rounded={3}/> <b>19%</b></div>
                  <div><Gemini size={12} pad={0} bg="transparent" rounded={3}/> <b>15%</b></div>
                </div>
              </div>
              <div className="ds-detail-cell">
                <div className="ds-detail-label">Recent mentions</div>
                <ul className="ds-recent-list">
                  <li>Apr 19 — Reddit · r/SaaS</li>
                  <li>Apr 18 — Quora · top answer</li>
                  <li>Apr 17 — Substack</li>
                </ul>
              </div>
            </div>
          </div>
        )}

        {related.map(r => (
          <div key={r.kw} className="ds-kw-row">
            <div className="ds-kw-name">{r.kw}</div>
            <div><DashPill tone={r.intent==='Commercial' ? 'warn' : r.intent==='Transactional' ? 'cyan' : 'violet'}>{r.intent}</DashPill></div>
            <div><DashPill tone={r.rank <= 3 ? 'pos' : r.rank <= 7 ? 'warn' : 'neg'}>{r.rank <= 3 ? 'Low' : r.rank <= 7 ? 'Med' : 'High'}</DashPill></div>
            <div className="mono">—</div>
            <div className="ds-plats">
              <ChatGPT size={14} pad={0} bg="transparent" rounded={3}/>
              <Claude size={14} pad={0} bg="transparent" rounded={3}/>
              <Perplexity size={14} pad={0} bg="transparent" rounded={3}/>
            </div>
            <div className="mono" style={{textAlign:'right', fontWeight:600}}>#{r.rank}</div>
            <div className="mono" style={{textAlign:'right', color: r.trend.startsWith('↓') ? '#E54545' : r.trend==='—' ? 'var(--muted)' : '#00A81E', fontWeight:600}}>{r.trend}</div>
          </div>
        ))}
      </div>
    </>
  );
};

/* 4. COMPETITION -------------------------------------------------- */
const PageCompetition = () => {
  const competitors = [
    {n:'Surfer SEO',  c:'#635BFF', v:[24,22,26,29,32,35,38,40,42,44,46,48]},
    {n:'Frase',       c:'#00D4FF', v:[30,28,32,34,33,31,34,36,38,37,36,34]},
    {n:'LLMPulse',    c:'#E7A100', v:[10,12,14,16,20,22,24,26,30,32,34,36]},
    {n:'RankPrompt',  c:'#FF5E85', v:[40,42,44,42,40,38,36,34,32,30,28,26]},
  ];
  const youValues = [20, 24, 28, 34, 41, 48, 55, 62, 68, 74, 80, 86];
  const toPath = (arr) => {
    const maxY = 100;
    return arr.map((v, i) => `${i===0 ? 'M' : 'L'}${(i/(arr.length-1))*600},${maxY - v}`).join(' ');
  };

  const competitive = [
    {q:'best AEO service', you:1, bp:2, ll:5, rp:8, status:'Lead'},
    {q:'AI visibility monitoring', you:2, bp:1, ll:4, rp:6, status:'Outranked'},
    {q:'how to get cited by ChatGPT', you:4, bp:3, ll:1, rp:9, status:'No mention'},
    {q:'press release for AI', you:1, bp:6, ll:8, rp:3, status:'Lead'},
    {q:'reddit brand mentions', you:2, bp:4, ll:3, rp:5, status:'Outranked'},
  ];
  const toneMap = { 'Lead':'pos', 'Outranked':'warn', 'No mention':'neutral' };

  return (
    <>
      <div className="chart-frame">
        <div className="chart-head">
          <div className="chart-title">Brand visibility · daily mentions</div>
          <div className="chart-legend">
            <span><span className="sw" style={{background:'var(--violet)'}}/> You</span>
            {competitors.map(c => (
              <span key={c.n}><span className="sw" style={{background:c.c}}/> {c.n}</span>
            ))}
          </div>
        </div>
        <svg viewBox="0 0 600 110" preserveAspectRatio="none" style={{width:'100%', height:150}}>
          {[0,1,2,3].map(i => (
            <line key={i} x1="0" x2="600" y1={i*30+5} y2={i*30+5} stroke="#E6EBF1" strokeDasharray="2 4"/>
          ))}
          {competitors.map(c => (
            <path key={c.n} d={toPath(c.v)} stroke={c.c} strokeWidth="1.8" fill="none"
                  strokeLinecap="round" opacity="0.7"/>
          ))}
          <path d={toPath(youValues)} stroke="var(--violet)" strokeWidth="2.6" fill="none" strokeLinecap="round"/>
          <circle cx="600" cy={100 - youValues[youValues.length-1]} r="4" fill="var(--violet)"/>
        </svg>
      </div>

      <div className="showcase-kpis" style={{gridTemplateColumns:'1fr 1fr'}}>
        <div className="sk">
          <div className="kpi-label">Your mentions · 30d</div>
          <div className="kpi-big"><Counter to={468}/></div>
          <div className="kpi-delta">↑ 112 vs competitors avg</div>
        </div>
        <div className="sk featured">
          <div className="kpi-label">Competitors ahead on keywords</div>
          <div className="kpi-big"><Counter to={11}/></div>
          <div className="kpi-delta">of 62 tracked</div>
        </div>
      </div>

      <div className="ds-card">
        <div className="ds-card-head ds-card-head-split">
          <span>Competitive keyword matrix</span>
          <div className="ds-tab-row ds-tab-row-sm">
            <button className="ds-tab active">You</button>
            <button className="ds-tab">All competitors</button>
          </div>
        </div>
        <div className="ds-comp-table">
          <div className="ds-comp-head">
            <div>Keyword</div>
            <div>You</div>
            <div>Surfer</div>
            <div>LLMPulse</div>
            <div>RankPrompt</div>
            <div>Status</div>
          </div>
          {competitive.map((row, i) => (
            <div key={i} className="ds-comp-row">
              <div className="ds-comp-kw">{row.q}</div>
              <div className="mono"><b style={{color:'var(--violet)'}}>#{row.you}</b></div>
              <div className="mono">#{row.bp}</div>
              <div className="mono">#{row.ll}</div>
              <div className="mono">#{row.rp}</div>
              <div><DashPill tone={toneMap[row.status]}>{row.status}</DashPill></div>
            </div>
          ))}
        </div>
      </div>

      <div className="ds-card">
        <div className="ds-card-head">Share of voice vs key rivals</div>
        {[
          {n:'Surfer SEO',   you:62, them:38},
          {n:'Frase',        you:58, them:42},
          {n:'LLMPulse',     you:71, them:29},
          {n:'RankPrompt',   you:49, them:51},
        ].map(r => (
          <div key={r.n} className="ds-sov-row">
            <span className="ds-sov-name">{r.n}</span>
            <div className="ds-sov-bar">
              <span className="ds-sov-you"  style={{width: r.you+'%'}}/>
              <span className="ds-sov-them" style={{width: r.them+'%'}}/>
            </div>
            <span className="ds-sov-nums"><b>{r.you}%</b> · {r.them}%</span>
          </div>
        ))}
      </div>
    </>
  );
};

/* 5. CITATIONS ---------------------------------------------------- */
const PageCitations = () => {
  const citations = [
    {d:'Apr 19', type:'Reddit',   Ico: Reddit,         src:'r/SaaS · u/founder_dave',     q:'"best AEO service for B2B in 2026?"',           impact:'High',   st:'Published'},
    {d:'Apr 18', type:'Substack', Ico: Substack,       src:'The Growth Letter · Substack', q:'"how to get cited by AI"',                     impact:'High',   st:'Published'},
    {d:'Apr 18', type:'Press',    Ico: DigitalJournal, src:'Digital Journal · Press',     q:'"AEO category leaders 2026"',                    impact:'Medium', st:'Published'},
    {d:'Apr 17', type:'Reddit',   Ico: Reddit,         src:'r/marketing · u/growthbeam',  q:'"reddit brand mentions tool"',                   impact:'Medium', st:'Published'},
    {d:'Apr 16', type:'Quora',    Ico: Quora,          src:'Quora · Top answer',          q:'"AI visibility tools"',                          impact:'High',   st:'Published'},
    {d:'Apr 15', type:'Press',    Ico: DigitalJournal, src:'Yahoo Finance · syndication', q:'"generative search optimization"',               impact:'Low',    st:'Scheduled'},
  ];
  const impactTone = { High: 'live', Medium: 'publishing', Low: 'draft' };
  return (
    <>
      <div className="showcase-kpis">
        <div className="sk">
          <div className="kpi-label">Citations · 30d</div>
          <div className="kpi-big"><Counter to={226}/></div>
          <div className="kpi-delta">↑ 58</div>
        </div>
        <div className="sk">
          <div className="kpi-label">Queries covered</div>
          <div className="kpi-big"><Counter to={25}/></div>
          <div className="kpi-delta">↑ 3</div>
        </div>
        <div className="sk">
          <div className="kpi-label">AI platforms</div>
          <div className="kpi-big"><Counter to={6}/><span style={{fontSize:16, color:'var(--muted)', fontWeight:500, marginLeft:4}}>/6</span></div>
          <div className="kpi-delta">All tracked</div>
        </div>
        <div className="sk featured">
          <div className="kpi-label">Total page views</div>
          <div className="kpi-big"><Counter to={188} suffix="k"/></div>
          <div className="kpi-delta">↑ 22k · 30d</div>
        </div>
      </div>

      <div className="ds-tab-row ds-filter-row">
        {['All types', 'Reddit', 'Substack', 'Press', 'Quora'].map((f,i) => (
          <button key={f} className={"ds-tab" + (i===0 ? " active":"")}>{f}</button>
        ))}
      </div>

      <div className="mentions-table mt-cit">
        <div className="mt-row head">
          <div>Source</div>
          <div>Impact</div>
          <div>Date</div>
          <div>Status</div>
        </div>
        {citations.map((c,i) => {
          const Ico = c.Ico;
          return (
            <div key={i} className="mt-row">
              <div className="mt-source">
                <div className="mt-ico"><Ico size={14} bg="transparent" pad={0} rounded={3}/></div>
                <div>
                  <div className="mt-name">{c.src}</div>
                  <div className="mt-title">{c.q}</div>
                </div>
              </div>
              <div><span className={"mt-pill " + impactTone[c.impact]}>{c.impact}</span></div>
              <div className="mono" style={{color:'var(--muted)', fontSize:12}}>{c.d}</div>
              <div><span className={"mt-pill " + (c.st==='Published' ? 'live' : 'publishing')}>● {c.st}</span></div>
            </div>
          );
        })}
      </div>

      <div className="ds-card">
        <div className="ds-card-head">Top query volume · last 30 days</div>
        {[
          {q:'best AEO service for SaaS', v:84, c:32},
          {q:'how to get cited by AI', v:72, c:28},
          {q:'AI visibility monitoring', v:58, c:22},
          {q:'reddit brand mentions', v:44, c:16},
          {q:'press release for AI search', v:36, c:12},
        ].map(r => (
          <div key={r.q} className="ds-site-row">
            <span className="ds-site-name">{r.q}</span>
            <div className="ds-site-bar"><span style={{width:r.v+'%'}}/></div>
            <span className="ds-site-count">{r.c}</span>
          </div>
        ))}
      </div>
    </>
  );
};

/* 6. BLOG POSTS --------------------------------------------------- */
const PageBlogPosts = () => {
  const [filter, setFilter] = React.useState('All');
  const posts = [
    {d:'19 Apr', t:'How to Get Featured in a Magazine: A Practical Guide for 2026', cat:'Informational', st:'Pending'},
    {d:'19 Apr', t:'How to Get Featured in a News Source in 2026',                  cat:'Informational', st:'Publishing'},
    {d:'17 Apr', t:'How to Get Featured in Publications: A Practical Approach',      cat:'Informational', st:'Published'},
    {d:'15 Apr', t:'Press Release for CEOs: How to Generate Coverage in SaaS',       cat:'Commercial',    st:'Published'},
    {d:'12 Apr', t:'Why AEO Press Release Strategy Matters for Your Outcomes',       cat:'Informational', st:'Published'},
    {d:'10 Apr', t:'Best Press Release Distribution Services: Expert Comparison',    cat:'Commercial',    st:'Published'},
    {d:'09 Apr', t:'Press Release Services Done Best: What They Do & What They Don\'t', cat:'Commercial', st:'Published'},
  ];
  const filtered = filter==='All' ? posts : posts.filter(p => p.st===filter);
  const statusIco = (st) =>
    st === 'Published'  ? { pill: '● Live',       tone: 'live' } :
    st === 'Publishing' ? { pill: '● Publishing', tone: 'publishing' } :
                          { pill: '● Pending',    tone: 'draft' };
  return (
    <>
      <div className="ds-filter-bar">
        <div className="ds-filter-group">
          <span className="ds-filter-label">Category</span>
          <div className="ds-filter-chips">
            <button className="ds-chip active">Daily</button>
            <button className="ds-chip">Weekly</button>
          </div>
        </div>
        <div className="ds-filter-group">
          <span className="ds-filter-label">Date</span>
          <div className="ds-filter-chips">
            <button className="ds-chip active">Mar 2026 · Apr 2026</button>
          </div>
        </div>
        <div style={{marginLeft:'auto', display:'flex', gap:8}}>
          <button className="ds-chip">⚙ Settings</button>
        </div>
      </div>

      <div className="ds-tab-row ds-filter-row">
        {['All', 'Published', 'Publishing', 'Pending'].map(f => (
          <button key={f} className={"ds-tab" + (filter===f ? " active":"")} onClick={() => setFilter(f)}>
            {f} {f!=='All' && <span className="ds-tab-count">{posts.filter(p => p.st===f).length}</span>}
          </button>
        ))}
      </div>

      <div className="mentions-table mt-blog">
        <div className="mt-row head">
          <div>Title</div>
          <div>Category</div>
          <div>Date</div>
          <div>Status</div>
        </div>
        {filtered.map((p,i) => {
          const s = statusIco(p.st);
          return (
            <div key={i} className="mt-row">
              <div className="mt-source">
                <div className="mt-ico mt-ico-blog">
                  <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{color:'var(--violet)'}}>
                    <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
                    <polyline points="14 2 14 8 20 8"/>
                    <line x1="8" y1="13" x2="16" y2="13"/>
                    <line x1="8" y1="17" x2="13" y2="17"/>
                  </svg>
                </div>
                <div>
                  <div className="mt-name">{p.t}</div>
                  <div className="mt-title">Blog post · AEO distribution</div>
                </div>
              </div>
              <div><span className={"mt-pill " + (p.cat==='Commercial' ? 'cited' : 'live')} style={{background: p.cat==='Commercial' ? 'rgba(231,161,0,0.14)' : 'rgba(99,91,255,0.12)', color: p.cat==='Commercial' ? '#A6700A' : 'var(--violet)'}}>{p.cat}</span></div>
              <div className="mono" style={{color:'var(--muted)', fontSize:12}}>{p.d}</div>
              <div><span className={"mt-pill " + s.tone}>{s.pill}</span></div>
            </div>
          );
        })}
      </div>
    </>
  );
};

Object.assign(window, {
  DashScore, DashPill,
  PageOverview, PageAIPerception, PageKeywords,
  PageCompetition, PageCitations, PageBlogPosts,
});
