import { __, _n, sprintf } from '@wordpress/i18n'; import React, { useEffect, useState } from 'react'; import { api } from '../api'; import { usableTabs } from '../App'; import ScreenVerdict from '../components/ScreenVerdict'; import Bing from './Bing'; import { Card, Button, Badge, Notice, LineChart, Tabs, SegmentBar, ChipBar, MetricGrid, Panel, PageState } from '../components/ui'; import Explain from '../components/Explain'; import RankTracker from './RankTracker'; function Setup({ status, onStatus }) { const [clientId, setClientId] = useState(''); const [clientSecret, setClientSecret] = useState(''); const [busy, setBusy] = useState(false); const [error, setError] = useState(null); const saveCreds = async () => { setBusy(true); setError(null); try { onStatus(await api.put('/gsc/credentials', { client_id: clientId, client_secret: clientSecret })); } catch (e) { setError(e.message); } finally { setBusy(false); } }; const connect = async () => { setBusy(true); setError(null); try { const { url } = await api.get('/gsc/connect-url'); window.location.href = url; } catch (e) { setError(e.message); setBusy(false); } }; const [advanced, setAdvanced] = useState(!status.signin_available); const signIn = async () => { setBusy(true); setError(null); try { const { url } = await api.get('/gsc/signin-url'); window.location.href = url; } catch (e) { setError(e.message); setBusy(false); } }; return ( {status.signin_available && (

{__('Google asks you to allow read access to Search Console and Analytics; nothing is written to your account. Tokens are stored encrypted on this site. Prefer your own Cloud project?', 'ai-rank-suite')}{' '}

{error &&

{error}

}
)} {advanced && ( <>
  1. {__('Open', 'ai-rank-suite')}{' '} {__('Google Cloud Console → Credentials', 'ai-rank-suite')}{' '} {__('and create an', 'ai-rank-suite')} {__('OAuth client ID', 'ai-rank-suite')} {__('(type: Web application).', 'ai-rank-suite')}
  2. {__('Enable the', 'ai-rank-suite')} {__('Search Console API', 'ai-rank-suite')} {__('for the project (APIs & Services → Library).', 'ai-rank-suite')}
  3. {__('Add this exact redirect URI:', 'ai-rank-suite')} {status.redirect_uri}
  4. {__('Paste the client credentials here:', 'ai-rank-suite')}
setClientId(e.target.value)} /> setClientSecret(e.target.value)} />
{status.has_credentials && ✓ {__('Credentials stored', 'ai-rank-suite')}}
{/* Two greyed-out buttons and no word about why. A disabled control that does not say what would enable it is a dead end. */} {!status.has_credentials && (

{!clientId || !clientSecret ? __('Paste both the client ID and the secret above to save them — connecting needs stored credentials.', 'ai-rank-suite') : __('Save the credentials first; the Google consent screen is opened with them.', 'ai-rank-suite')}

)} {error &&

{error}

}
)}
); } function PropertyPicker({ status, onStatus }) { const [sites, setSites] = useState(null); const [error, setError] = useState(null); useEffect(() => { api.get('/gsc/sites').then((r) => setSites(r.sites)).catch((e) => setError(e.message)); }, []); return ( {error && {error}} {!sites && !error &&

{__('Loading properties…', 'ai-rank-suite')}

} {sites && (
{sites.length === 0 &&

{__('No verified properties found for this account.', 'ai-rank-suite')}

} {sites.map((s) => ( ))}
)}
); } /** Which series each tile draws, and in which colour. */ const CHART = { clicks: { key: 'clicks', label: __('Clicks', 'ai-rank-suite'), color: 'var(--ars-series-1)' }, impressions: { key: 'impressions', label: __('Impressions', 'ai-rank-suite'), color: 'var(--ars-series-2)' }, ctr: { key: 'ctr', label: __('CTR', 'ai-rank-suite'), color: 'var(--ars-c-green-ink)' }, position: { key: 'position', label: __('Average position', 'ai-rank-suite'), color: 'var(--ars-accent)' }, queries: { key: 'clicks', label: __('Clicks', 'ai-rank-suite'), color: 'var(--ars-series-1)' }, topten: { key: 'clicks', label: __('Clicks', 'ai-rank-suite'), color: 'var(--ars-series-1)' }, }; function Report({ status, onStatus }) { const [metric, setMetric] = useState('clicks'); const [days, setDays] = useState(28); const [data, setData] = useState(null); const [error, setError] = useState(null); useEffect(() => { setData(null); api.get(`/gsc/performance?days=${days}`).then(setData).catch((e) => setError(e.message)); }, [days]); const fmt = (n) => (n >= 10000 ? `${(n / 1000).toFixed(1)}k` : String(n)); return (
{/* The period, and nothing else. Which property is connected and how to disconnect it are settings — they were sitting where the report should start, and Disconnect is not a control that belongs one stray click away from the numbers it would delete. */}
{error && {error}} {!data && !error && (

{__('Fetching Search Console data…', 'ai-rank-suite')}

)} {data && ( <> {/* * Six numbers, one chart. * * Four tiles and then two charts plotting two of those same * four series meant you saw clicks twice before reaching * anything new, and position — the number that actually says * whether the work is landing — was the one metric with no * chart of its own. The tiles select what the chart draws now, * and the two that were missing are here: how many queries you * appear for at all, and how many of them sit on page one. */} Number(q.position) <= 10).length), sub: __('position 10 or better', 'ai-rank-suite'), }, ]} /> {/* Six pixels of gutter, not sixteen: the drawing carries its own axis inset, so the card's padding was a second margin around a picture that already had one. */}
({ date: d.date, value: d[CHART[metric]?.key || 'clicks'], }))} height={220} invert={metric === 'position'} formatValue={metric === 'ctr' ? (v) => `${v}%` : undefined} bleed />
)}
); } export default function SearchConsole({ tab = 'performance', onTab }) { const [status, setStatus] = useState(null); const [error, setError] = useState(null); const flash = new URLSearchParams((window.location.hash.split('?')[1] || '')); // #/search-console?connected=1 useEffect(() => { api.get('/gsc/status').then(setStatus).catch((e) => setError(e.message)); }, []); if (!status) return ; // Three states, one sentence each: no credentials, credentials but not // connected, connected to a property. Each names the one next step. const verdict = !status.connected && status.signin_available && !status.has_credentials ? { tone: 'neutral', text: __('Search Console and Analytics are not connected yet.', 'ai-rank-suite'), why: __('One sign-in with Google connects both — read-only, revocable in your Google account at any time. Rank snapshots cannot be backfilled; the trend starts the day you connect.', 'ai-rank-suite'), } : !status.has_credentials && !status.connected ? { tone: 'neutral', text: __('Search Console is not set up — no Google credentials yet.', 'ai-rank-suite'), why: __('Clicks, impressions and positions come from your own Search Console property. It takes a client id and secret from Google Cloud once; after that the connection renews itself.', 'ai-rank-suite'), } : !status.connected ? { tone: 'warning', text: __('Credentials are saved but Google has not been authorised yet.', 'ai-rank-suite'), why: __('One click on Connect opens Google, you pick the account, and the data starts flowing. Rank snapshots cannot be backfilled — the trend starts the day you connect.', 'ai-rank-suite'), } : { tone: 'good', text: sprintf(__('Connected to %s.', 'ai-rank-suite'), status.property || __('your Search Console property', 'ai-rank-suite')), why: __('Reports below are read live from Google. Positions are recorded daily so the rank trend can exist later.', 'ai-rank-suite'), }; return (
{flash.get('error') && {decodeURIComponent(flash.get('error'))}} {/* Both tabs read the same Search Console connection, so they belong behind one nav item rather than two that each ask you to connect. */} {/* Keywords is the rank tracker, which the free edition does not ship — an unfiltered tab answered "no route matched". */} {(() => { const { tabs: scTabs, active: scActive } = usableTabs( [ { id: 'performance', label: __('Google', 'ai-rank-suite') }, { id: 'keywords', label: __('Keywords', 'ai-rank-suite'), needs: 'rank_tracker' }, { id: 'bing', label: __('Bing', 'ai-rank-suite') }, ], tab ); if (scActive !== tab) { // The hash asked for a tab this build does not have. setTimeout(() => onTab(scActive), 0); } return ; })()} {tab === 'bing' ? ( ) : tab === 'keywords' ? ( ) : ( <> {!status.connected && } {status.connected && !status.property && } {status.connected && status.property && } {/* * The connection, and the way out of it, at page level. * * This panel used to sit inside , after the charts. * A report that fails or never finishes loading takes the * whole component with it — including the only control that * disconnects the property. So the one screen you would open * *because* the connection is misbehaving was the one screen * that hid the fix. It renders from `status` alone now, * which is what it always described. */} {status.connected && status.property && (
✓ {__('Connected', 'ai-rank-suite')} {status.property}

{__('Disconnecting stops the daily snapshots. The history already recorded stays — it cannot be rebuilt from Google, so nothing here deletes it.', 'ai-rank-suite')}

)} )}
); } /** Percentage change, or null when there is nothing to compare against. */ function pct(now, before) { if (!before || before === 0) return null; return Math.round(((now - before) / before) * 1000) / 10; } /** * The part of Search Console that is worth paying for. * * The four totals and a top-ten list are the numbers Google hands you. These * are the four questions those numbers cannot answer on their own. */ function GscInsights({ data, fmt }) { const [view, setView] = useState('questions'); const q = data.questions || { totals: {}, rows: [] }; return (
{view === 'questions' && ( <> {q.totals?.question?.ctr > 0 && q.totals?.other?.ctr > 0 && (
)}

{__('A question query is the shape an AI answer eats. When an overview or an assistant answers it above your result, the impression still counts and the click does not — so the signature of AI cannibalisation is this segment\'s click-through falling while its impressions hold or rise. Comparing it against your non-question queries is the closest thing to measuring that from inside Search Console, which does not report it directly.', 'ai-rank-suite')}

{__('If it is happening, the response is not to fight for the click. It is to be the source the answer quotes: an answer-first opening, question-shaped sub-headings, and FAQ markup. All three are on the page editor\'s Full report tab.', 'ai-rank-suite')}

)} {view === 'striking' && ( <>
{(data.striking || []).map((r) => ( ))}
{__('Query', 'ai-rank-suite')} {__('Position', 'ai-rank-suite')} {__('Impr.', 'ai-rank-suite')} {__('Clicks', 'ai-rank-suite')} {__('Upside', 'ai-rank-suite')}
{r.key} {r.position} {fmt(r.impressions)} {r.clicks} +{r.upside}

{__('Upside is roughly the clicks three positions of improvement would add, from published click-through curves — not a measurement of your site. It is here to rank these against each other, not as a forecast.', 'ai-rank-suite')}

)} {view === 'ignored' && ( <>
{(data.ignored || []).map((r) => ( ))}
{__('Page', 'ai-rank-suite')} {__('Position', 'ai-rank-suite')} {__('Impr.', 'ai-rank-suite')} {__('CTR', 'ai-rank-suite')} {__('Usual', 'ai-rank-suite')} {__('Clicks lost', 'ai-rank-suite')}
{r.key.replace(/^https?:\/\/[^/]+/, '') || r.key} {r.position} {fmt(r.impressions)} {r.actual_ctr}% {r.expected_ctr}% {r.lost}

{__('Every one of these is a title and description problem, which is the cheapest thing on this list to fix. Note that an AI overview sitting above your result depresses click-through at every position, so a page answering a question may appear here without anything being wrong with its snippet.', 'ai-rank-suite')}

)} {view === 'movement' && (
)} {view === 'all' && (
)}
); } function Rows({ title, rows, keyLabel, fmt, strip = false }) { return (
{(rows || []).map((r) => ( ))}
{keyLabel} {__('Clicks', 'ai-rank-suite')} {__('Impr.', 'ai-rank-suite')} {__('CTR', 'ai-rank-suite')} {__('Pos.', 'ai-rank-suite')}
{strip ? r.key.replace(/^https?:\/\/[^/]+/, '') || r.key : r.key} {r.clicks} {fmt(r.impressions)} {r.ctr}% {r.position}
); } function MoveTable({ title, rows, fmt, tone }) { return (
{rows.map((r) => ( ))} {rows.length === 0 && ( )}
{__('Page', 'ai-rank-suite')} {__('Before', 'ai-rank-suite')} {__('Now', 'ai-rank-suite')} {__('Change', 'ai-rank-suite')}
{r.key.replace(/^https?:\/\/[^/]+/, '') || r.key} {r.gone && {__('gone', 'ai-rank-suite')}} {r.new && {__('new', 'ai-rank-suite')}} {r.before} {r.clicks} 0 ? '#1a7f45' : 'var(--ars-serious)' }}> {r.change > 0 ? '+' : ''} {r.change}
{__('Nothing moved enough to report.', 'ai-rank-suite')}
); }