/* Page: Keyword rankings + page mapping (SERanking-style centerpiece) */
const { useState: useStateR } = React;

function RankingsView({ client }) {
  const { data, loading, error } = useApi(
    `/api/clients/${client.id}/rankings`,
    [client.id]
  );
  const [selectedKw, setSelectedKw] = useStateR(null);
  const [tab, setTab] = useStateR('keywords');
  const [groupBy, setGroupBy] = useStateR('flat');

  if (loading) return <div className="loading-state">Loading rankings...</div>;
  if (error) return <div className="error-state">Failed to load rankings: {error}</div>;

  const KEYWORDS = data?.keywords || [];
  const PAGES = data?.pages || [];

  if (!selectedKw && KEYWORDS.length) {
    // Can't call setSelectedKw here (would be a side effect in render)
    // The table will render and first-row click sets the selection
  }

  const activeKw = selectedKw || KEYWORDS[0] || null;

  const visibility = 38.4;
  const tracked = KEYWORDS.length * 12; // pretend total is bigger

  return (
    <>
      <div className="page-head">
        <div>
          <div className="eyebrow gold"><span className="dot"/>Rankings · 142 keywords across 38 pages</div>
          <h1>Keyword rankings</h1>
          <div className="sub">Tracked keywords mapped to landing pages. Position history, SERP features, intent. Drill into any keyword for daily detail.</div>
        </div>
        <div className="actions">
          <button className="btn btn-secondary"><Icon name="plus" size={13}/> Add keywords</button>
          <button className="btn btn-secondary"><Icon name="ext" size={13}/> Bulk import</button>
        </div>
      </div>

      <div className="kpi-grid">
        <div className="kpi">
          <span className="label">Visibility score</span>
          <span className="value">{visibility}%</span>
          <span className="delta up"><Icon name="arrowUp" size={10}/> +4.6pp</span>
          <span className="source">Semrush · weighted</span>
        </div>
        <div className="kpi">
          <span className="label">Top-3</span>
          <span className="value">38</span>
          <span className="delta up"><Icon name="arrowUp" size={10}/> +11</span>
          <span className="source">142 tracked · PH desktop</span>
        </div>
        <div className="kpi">
          <span className="label">Top-10</span>
          <span className="value">76</span>
          <span className="delta up"><Icon name="arrowUp" size={10}/> +18</span>
          <span className="source">vs prev 30d</span>
        </div>
        <div className="kpi">
          <span className="label">Avg position</span>
          <span className="value">11.4</span>
          <span className="delta up"><Icon name="arrowDown" size={10}/> −2.7</span>
          <span className="source">Lower is better</span>
        </div>
        <div className="kpi">
          <span className="label">SERP features</span>
          <span className="value">28</span>
          <span className="delta flat">Map pack · 14 · Snippet · 6</span>
          <span className="source">Semrush · daily</span>
        </div>
      </div>

      <div className="section-head">
        <span className="label">Tracked keywords</span>
        <span className="rule"/>
        <div className="actions">
          <div className="tabs">
            <span className={`tab ${tab === 'keywords' ? 'active' : ''}`} onClick={() => setTab('keywords')}>By keyword</span>
            <span className={`tab ${tab === 'pages' ? 'active' : ''}`} onClick={() => setTab('pages')}>By page</span>
            <span className={`tab ${tab === 'intent' ? 'active' : ''}`} onClick={() => setTab('intent')}>By intent</span>
          </div>
        </div>
      </div>

      <div className="filter-row">
        <div className="search">
          <Icon name="search" size={14}/>
          <input placeholder="Search 142 keywords..."/>
          <kbd>⌘K</kbd>
        </div>
        <button className="filter-pill active">All <span className="v">142</span></button>
        <button className="filter-pill">Top 3 <span className="v">38</span></button>
        <button className="filter-pill">Top 10 <span className="v">76</span></button>
        <button className="filter-pill">Striking distance <span className="v">22</span></button>
        <button className="filter-pill">Lost <span className="v">4</span></button>
        <span style={{flex: 1}}/>
        <button className="filter-pill">Tag · <span className="v">All</span> <Icon name="chev" size={10}/></button>
        <button className="filter-pill">Intent · <span className="v">All</span> <Icon name="chev" size={10}/></button>
        <button className="filter-pill">Device · <span className="v">Desktop</span> <Icon name="chev" size={10}/></button>
      </div>

      <div style={{display: 'grid', gridTemplateColumns: '1.6fr 1fr', gap: 16}}>
        {/* Left: keyword table */}
        <div className="panel" style={{minHeight: 520}}>
          <table className="table">
            <thead>
              <tr>
                <th>Keyword</th>
                <th>Mapped page</th>
                <th className="num">Pos</th>
                <th className="num">Δ</th>
                <th className="num">Target</th>
                <th>History · 90d</th>
                <th className="num">Vol</th>
                <th className="num">KD</th>
                <th>SERP features</th>
              </tr>
            </thead>
            <tbody>
              {KEYWORDS.map((k, i) => {
                const sel = activeKw?.kw === k.kw;
                const posClass = k.pos <= 3 ? 'top3' : k.pos <= 10 ? 'top10' : k.pos <= 30 ? 'top30' : 'beyond';
                const delta = k.posPrev - k.pos; // positive = improved
                return (
                  <tr key={i}
                      onClick={() => setSelectedKw(k)}
                      style={{cursor:'pointer', background: sel ? 'var(--gold-dim)' : undefined}}>
                    <td>
                      <div className="cell-stack">
                        <span className="lead">{k.kw}</span>
                        <span className="meta">{k.intent} · {k.tags.join(' · ')}</span>
                      </div>
                    </td>
                    <td><span className="mono" style={{color: 'var(--text-muted)', fontSize: 11}}>{k.page}</span></td>
                    <td className="num"><span className={`pos-chip ${posClass}`}>{k.pos}</span></td>
                    <td className="num">
                      {delta !== 0 ? (
                        <span className={`delta-chip ${delta > 0 ? 'up' : 'down'}`}>
                          <Icon name={delta > 0 ? 'arrowUp' : 'arrowDown'} size={10}/>
                          {Math.abs(delta)}
                        </span>
                      ) : <span className="delta-chip flat">—</span>}
                    </td>
                    <td className="num"><span style={{fontFamily:'var(--font-mono)', fontSize: 11, color: 'var(--text-dim)'}}>≤{k.target}</span></td>
                    <td><PosSpark values={k.history} w={120} h={28}/></td>
                    <td className="num mono">{k.vol.toLocaleString()}</td>
                    <td className="num mono" style={{color: 'var(--text-muted)'}}>{k.kd}</td>
                    <td>
                      <div style={{display:'flex', gap: 4, flexWrap:'wrap'}}>
                        {k.serp.length === 0 ? <span className="dim mono" style={{fontSize: 10}}>—</span> :
                          k.serp.map((s, j) => (
                            <span key={j} className={`serp-badge ${s.toLowerCase().includes('snippet') ? 'gold' : ''}`}>{s}</span>
                          ))}
                      </div>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>

        {/* Right: keyword detail panel */}
        <div className="panel" style={{position: 'sticky', top: 0, alignSelf: 'flex-start'}}>
          <div className="panel-head">
            <h3 style={{fontSize: 15}}>{activeKw?.kw || ''}</h3>
            <div className="right">
              <button className="icon-btn" style={{width: 28, height: 28}}><Icon name="ext" size={13}/></button>
            </div>
          </div>
          <div className="panel-body" style={{padding: 0}}>
            <div style={{padding: '14px 18px', display:'grid', gridTemplateColumns:'1fr 1fr', gap: 12, borderBottom:'1px solid var(--border-light)'}}>
              <div>
                <div className="mono-label">Position · today</div>
                <div style={{fontFamily:'var(--font-display)', fontWeight: 900, fontSize: 36, lineHeight: 1, color: 'var(--text)', marginTop: 4}}>{activeKw?.pos || 0}</div>
                <div className={`delta-chip ${(activeKw?.posPrev || 0) - (activeKw?.pos || 0) > 0 ? 'up' : (activeKw?.posPrev || 0) - (activeKw?.pos || 0) < 0 ? 'down' : 'flat'}`} style={{marginTop: 6}}>
                  {(activeKw?.posPrev || 0) - (activeKw?.pos || 0) > 0 ? <Icon name="arrowUp" size={10}/> : (activeKw?.posPrev || 0) - (activeKw?.pos || 0) < 0 ? <Icon name="arrowDown" size={10}/> : null}
                  {(activeKw?.posPrev || 0) - (activeKw?.pos || 0) === 0 ? 'No change' : `${Math.abs((activeKw?.posPrev || 0) - (activeKw?.pos || 0))} from prev week`}
                </div>
              </div>
              <div>
                <div className="mono-label">Best · 90d</div>
                <div style={{fontFamily:'var(--font-display)', fontWeight: 900, fontSize: 36, lineHeight: 1, color: 'var(--gold)', marginTop: 4}}>{(activeKw?.history?.length ? Math.min(...activeKw.history) : 0)}</div>
                <div className="mono-label" style={{marginTop: 6, fontSize: 9}}>Target · ≤{activeKw?.target || 0}</div>
              </div>
            </div>

            <div style={{padding: '14px 18px', borderBottom:'1px solid var(--border-light)'}}>
              <div className="mono-label" style={{marginBottom: 8}}>Position history · 90d</div>
              <PosHistoryChart values={activeKw?.history || []}/>
            </div>

            <div style={{padding: '14px 18px', borderBottom:'1px solid var(--border-light)'}}>
              <div className="mono-label" style={{marginBottom: 8}}>Mapped page</div>
              <div style={{display:'flex', gap: 12, alignItems:'flex-start'}}>
                <span className="serp-badge gold">SERVICE</span>
                <div style={{flex: 1, minWidth: 0}}>
                  <div className="mono" style={{fontSize: 12, color: 'var(--text)', wordBreak:'break-all'}}>karatenation.ph{activeKw?.page || ''}</div>
                  <div className="mono-label" style={{fontSize: 9, marginTop: 4}}>38 keywords · 4 820 sessions/mo</div>
                </div>
                <button className="icon-btn" style={{width: 28, height: 28, flexShrink: 0}}><Icon name="ext" size={12}/></button>
              </div>
            </div>

            <div style={{padding: '14px 18px', borderBottom:'1px solid var(--border-light)'}}>
              <div className="mono-label" style={{marginBottom: 8}}>SERP composition</div>
              <div style={{display:'flex', flexWrap:'wrap', gap: 4}}>
                {(activeKw?.serp || []).length === 0 && <span className="dim" style={{fontSize: 12}}>No SERP features detected.</span>}
                {(activeKw?.serp || []).map((s, i) => (
                  <span key={i} className={`serp-badge ${s.toLowerCase().includes('snippet') ? 'gold' : ''}`}>{s}</span>
                ))}
                <span className="serp-badge">10 organic</span>
                <span className="serp-badge">3 ads</span>
              </div>
            </div>

            <div style={{padding: '14px 18px'}}>
              <div className="mono-label" style={{marginBottom: 8}}>Top-10 competitors</div>
              <div style={{display:'flex', flexDirection:'column', gap: 6}}>
                {[
                  { d: 'karatenation.ph', p: activeKw?.pos || 0, you: true },
                  { d: 'manilamartialarts.com', p: 1 },
                  { d: 'philippinekarate.org', p: 2 },
                  { d: 'fitnessfirst.com.ph', p: 4 },
                  { d: 'rappler.com', p: 6 },
                ].sort((a,b) => a.p - b.p).map((c, i) => (
                  <div key={i} style={{display:'flex', alignItems:'center', gap: 10, fontSize: 12, padding: '4px 0'}}>
                    <span className={`pos-chip ${c.p <= 3 ? 'top3' : 'top10'}`} style={{minWidth: 28}}>{c.p}</span>
                    <span className="mono" style={{flex: 1, color: c.you ? 'var(--gold)' : 'var(--text)', fontWeight: c.you ? 500 : 300}}>
                      {c.d} {c.you && <span className="mono-label" style={{fontSize: 8, marginLeft: 4}}>YOU</span>}
                    </span>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>
      </div>
    </>
  );
}

/* Position history line — for the detail panel */
function PosHistoryChart({ values }) {
  const w = 420, h = 140;
  const padL = 28, padR = 8, padT = 8, padB = 22;
  const innerW = w - padL - padR;
  const innerH = h - padT - padB;
  const max = Math.max(20, Math.max(...values));
  const min = 1;
  const stepX = innerW / (values.length - 1);
  // Top of chart = best position (1)
  const yFor = (v) => padT + ((v - min) / (max - min)) * innerH;
  const pts = values.map((v, i) => [padL + i * stepX, yFor(v)]);
  const d = pts.map((p, i) => (i === 0 ? `M${p[0]},${p[1]}` : `L${p[0]},${p[1]}`)).join(' ');
  const last = values[values.length - 1];
  const lastColor = last <= 3 ? 'var(--gold)' : last <= 10 ? 'var(--accent)' : 'var(--text-muted)';

  const yTicks = [1, 3, 10, 20].filter(t => t <= max);
  return (
    <svg viewBox={`0 0 ${w} ${h}`} style={{width: '100%', height: 140, display:'block'}}>
      {yTicks.map((t, i) => {
        const y = yFor(t);
        return (
          <g key={i}>
            <line x1={padL} x2={w - padR} y1={y} y2={y} className="chart-grid"
                  strokeDasharray={t === 3 || t === 10 ? '2 4' : null}/>
            <text x={padL - 6} y={y + 3} textAnchor="end" className="chart-y-label">{t}</text>
          </g>
        );
      })}
      <path d={d} fill="none" stroke="var(--gold)" strokeWidth="1.75"/>
      {pts.map((p, i) => (
        <circle key={i} cx={p[0]} cy={p[1]} r={i === pts.length - 1 ? 3 : 1.5} fill={i === pts.length - 1 ? lastColor : 'var(--gold)'}/>
      ))}
      <text x={padL} y={h - 6} className="chart-x-label">90d ago</text>
      <text x={w - padR} y={h - 6} textAnchor="end" className="chart-x-label">today</text>
    </svg>
  );
}

window.RankingsView = RankingsView;
