// Keywords — ranking overview, quick wins, opportunity gaps

(function () {

function KDBar({ diff }) {
  const color = diff < 30 ? 'var(--good)' : diff < 60 ? 'var(--warn)' : 'var(--bad)';
  return (
    <div style={{ display:'flex', alignItems:'center', gap:6 }}>
      <div style={{ flex:1, height:5, background:'var(--surface-3)', borderRadius:99, overflow:'hidden' }}>
        <div style={{ width:`${diff}%`, height:'100%', background:color, borderRadius:99 }}/>
      </div>
      <span style={{ fontSize:11.5, fontWeight:600, color, flexShrink:0, width:24, textAlign:'right' }}>{diff}</span>
    </div>
  );
}

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

function PosBadge({ pos }) {
  const color = pos <= 3 ? 'var(--good)' : pos <= 10 ? 'var(--accent)' : 'var(--ink-2)';
  return <span style={{ fontWeight:700, color }}>#{pos}</span>;
}

function KeywordsPage({ go }) {
  const c    = window.CP_CLIENT || {};
  const auth = c.authority || {};
  const pos  = auth.positions || {};
  const kws  = auth.topKeywords || [];

  const total     = (pos.top3||0) + (pos.top10||0) + (pos.top30||0) + (pos.below30||0);
  const quickWins = kws.filter(k => k.pos >= 4 && k.pos <= 10);

  const OPPORTUNITY_KWS = (c.authority && c.authority.opportunities) || [
    { keyword:'best croissant chicago',           vol:320,  kd:22 },
    { keyword:'custom wedding cake chicago',       vol:480,  kd:28 },
    { keyword:'gluten free bakery near me',        vol:1200, kd:35 },
    { keyword:'birthday cake delivery chicago',    vol:720,  kd:31 },
    { keyword:'artisan bread chicago',             vol:210,  kd:19 },
    { keyword:'french pastry chicago',             vol:390,  kd:26 },
  ];

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

      {/* Score cards */}
      <div style={{ display:'grid', gridTemplateColumns:'repeat(auto-fill,minmax(140px,1fr))', gap:10, marginBottom:24 }}>
        {[
          { label:'Total Keywords',   value:total,             color:'var(--ink)',    hint:'All search terms your site currently ranks for anywhere on Google.' },
          { label:'Top 3 (Best)',     value:pos.top3||0,       color:'var(--good)',   hint:'Positions 1–3 get ~60% of all clicks. These are your best-performing keywords.' },
          { label:'Page 1 (Top 10)', value:(pos.top10||0),    color:'var(--accent)', hint:'On page 1 of Google. Users almost never go to page 2.' },
          { label:'Quick Wins',       value:quickWins.length,  color:'var(--warn)',   hint:'Positions 4–10 — a small improvement can push these to top 3 and double your clicks.' },
        ].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:28, 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>

      {/* Quick Wins */}
      {quickWins.length > 0 && (
        <div style={{ background:'var(--surface)', border:'1px solid color-mix(in srgb,var(--warn) 30%,transparent)', borderRadius:'var(--r-3)', padding:'18px 20px', marginBottom:16 }}>
          <div style={{ display:'flex', alignItems:'center', gap:8, marginBottom:4 }}>
            <span className="hk-h4">⚡ Quick Wins</span>
            <Hint text="These keywords are already on page 1 (positions 4–10). A small SEO push — better content, a new backlink, or a title tweak — could move them to top 3." width={240}/>
          </div>
          <div className="hk-tiny" style={{ color:'var(--ink-3)', marginBottom:16 }}>
            Positions 4–10 — already on page 1, one nudge from the top
          </div>
          <div style={{ overflowX:'auto' }}>
            <table style={{ width:'100%', borderCollapse:'collapse', fontSize:13 }}>
              <thead>
                <tr style={{ borderBottom:'1px solid var(--border)' }}>
                  {['Keyword','Position','Monthly Searches','Difficulty'].map(h => (
                    <th key={h} style={{ textAlign:h==='Keyword'?'left':'center', padding:'0 10px 10px', color:'var(--ink-3)', fontWeight:600, fontSize:11.5, whiteSpace:'nowrap' }}>{h}</th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {quickWins.map((kw,i) => (
                  <tr key={i} style={{ borderBottom:'1px solid var(--surface-3)' }}>
                    <td style={{ padding:'10px', color:'var(--ink)', fontWeight:500 }}>{kw.keyword}</td>
                    <td style={{ padding:'10px', textAlign:'center' }}><PosBadge pos={kw.pos}/></td>
                    <td style={{ padding:'10px', textAlign:'center', color:'var(--ink-2)' }}>{(kw.vol||0).toLocaleString()}</td>
                    <td style={{ padding:'10px', minWidth:100 }}><KDBar diff={kw.diff}/></td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {/* All keywords */}
      <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 }}>All Tracked 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:'Searches', hint:'Monthly Google searches for this term.' },
                  { label:'Traffic',  hint:'Estimated monthly clicks coming to your site from this keyword.' },
                  { label:'KD',       hint:'Keyword Difficulty 0–100. Under 30 = attainable. 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>
              {kws.map((kw,i) => (
                <tr key={i} style={{ borderBottom:'1px solid var(--surface-3)' }}>
                  <td style={{ padding:'10px', color:'var(--ink)', fontWeight:500 }}>{kw.keyword}</td>
                  <td style={{ padding:'10px', textAlign:'center' }}><PosBadge pos={kw.pos}/></td>
                  <td style={{ padding:'10px', textAlign:'center', color:'var(--ink-2)' }}>{(kw.vol||0).toLocaleString()}</td>
                  <td style={{ padding:'10px', textAlign:'center', color:'var(--accent)', fontWeight:600 }}>{kw.traffic}</td>
                  <td style={{ padding:'10px', minWidth:100 }}><KDBar diff={kw.diff}/></td>
                  <td style={{ padding:'10px', textAlign:'center' }}><TrendBadge trend={kw.trend}/></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {/* Locked: Keyword Gap / Opportunities */}
      <LockedSection
        label="Keyword Gap Analysis — Unlock on Strategy Call"
        sub="6 high-value keywords your competitors rank for but you don't — each with monthly search volume and a content plan."
        ctaLabel="Get Keyword Research"
      >
        <div style={{ background:'var(--surface)', border:'1px solid var(--border)', borderRadius:'var(--r-3)', padding:'18px 20px' }}>
          <div style={{ display:'flex', alignItems:'center', gap:8, marginBottom:14 }}>
            <span className="hk-h4">Untapped Keyword Opportunities</span>
            <span style={{ fontSize:11, fontWeight:700, padding:'2px 8px', borderRadius:100, background:'var(--good-soft)', color:'var(--good)' }}>6 found</span>
          </div>
          {OPPORTUNITY_KWS.map((kw,i) => (
            <div key={i} style={{ display:'flex', alignItems:'center', gap:12, padding:'10px 0', borderBottom:i<OPPORTUNITY_KWS.length-1?'1px solid var(--surface-3)':'' }}>
              <span style={{ flex:1, fontSize:13, color:'var(--ink)', fontWeight:500 }}>{kw.keyword}</span>
              <span style={{ fontSize:12, color:'var(--ink-3)', flexShrink:0 }}>{kw.vol.toLocaleString()}/mo</span>
              <span style={{ fontSize:11.5, fontWeight:600, flexShrink:0, color:'var(--good)' }}>KD {kw.kd}</span>
              <span style={{ fontSize:11, fontWeight:700, padding:'2px 8px', borderRadius:4, background:'var(--bad-soft)', color:'var(--bad)', flexShrink:0 }}>Not ranking</span>
            </div>
          ))}
        </div>
      </LockedSection>
    </div>
  );
}

CP_PAGES.keywords = { title: 'Keywords', component: KeywordsPage };

})();
