import React, { useEffect, useState } from 'react';
import { __, sprintf } from '@wordpress/i18n';
import { api } from '../api';
import KeywordSuggest from '../components/KeywordSuggest';
import { Card, Button, Badge, Notice, MetricGrid, LineChart, PosBadge, Sparkline, ColumnChart, Delta, PageState, Field } from '../components/ui';
import { IconRefresh, IconX } from '../components/icons';
/**
* The shared Delta, with the one thing it cannot know: absence.
*
* `change` is null until a keyword has two snapshots far enough apart, and
* ±0 would claim "measured, no movement" — an em-dash is the honest value.
* The number itself is already signed so that positive means climbed
* (position 12 → 9 is +3), so no invert.
*/
function Change({ value }) {
if (value === null || value === undefined) {
return —;
}
return ;
}
function KeywordPlanner({ tracked, onTrack }) {
const [status, setStatus] = useState(null);
const [form, setForm] = useState({ client_id: '', client_secret: '', developer_token: '', customer_id: '', login_customer_id: '', language_id: '1000', geo_target_ids: '2784' });
const [seeds, setSeeds] = useState('');
const [pageUrl, setPageUrl] = useState('');
const [ideas, setIdeas] = useState([]);
const [busy, setBusy] = useState(false);
const [error, setError] = useState(null);
const [serp, setSerp] = useState(null);
const [serpReport, setSerpReport] = useState(null);
useEffect(() => {
api.get('/rank/serp').then(setSerp).catch(() => setSerp(false));
api.get('/rank/planner/status').then((next) => {
setStatus(next);
setForm((old) => ({ ...old, ...next, client_secret: '', developer_token: '', geo_target_ids: (next.geo_target_ids || []).join(', ') }));
}).catch(() => setStatus(false));
}, []);
if (status === null || status === false) return null;
const set = (key) => (e) => setForm((old) => ({ ...old, [key]: e.target.value }));
const act = async (fn) => {
setBusy(true); setError(null);
try { await fn(); } catch (e) { setError(e.message); } finally { setBusy(false); }
};
/**
* Ask a search engine where the tracked keywords actually stand. Search
* Console answers a different question — the average position of pages it
* already shows — so a keyword the site does not rank for yet is simply
* absent from it.
*/
const checkPositions = (force) =>
act(async () => {
const r = await api.post('/rank/serp', { limit: 25, force });
setSerpReport(r);
setSerp(await api.get('/rank/serp'));
});
return (
<>
{serp && serp.provider ? (
{sprintf(
/* translators: %s: the provider being asked, e.g. Serper. */
__('Asking %s — each check spends one lookup from your quota.', 'ai-rank-suite'),
serp.provider
)}
{serpReport && (
{sprintf(
/* translators: 1: keywords checked, 2: how many were found in the results, 3: keywords skipped, 4: failures. */
__('%1$s checked, %2$s found in the results, %3$s already done today, %4$s failed.', 'ai-rank-suite'),
Number(serpReport.checked || 0).toLocaleString(),
Number(serpReport.found || 0).toLocaleString(),
Number(serpReport.skipped || 0).toLocaleString(),
Number(serpReport.failed || 0).toLocaleString()
)}
{(serpReport.errors || []).length > 0 && (
{serpReport.errors.slice(0, 5).map((e, i) => (
{e.keyword} — {e.message}
))}
)}
)}
) : (
{__('No SERP provider is set up yet. Add one under SEO data providers and this becomes a daily position check for every keyword you track — including the ones you do not rank for yet, which Search Console cannot show you at all.', 'ai-rank-suite')}
{flash.get('ads_connected') && {__('Google Ads is connected. Keyword Planner is ready.', 'ai-rank-suite')}}
{flash.get('ads_error') && {flash.get('ads_error')}}
{error && {error}}
{!data.connected && (
{__('This tracks your average position from your own Google Search Console data — not independent SERP rankings. Connect a property under “Search Console” to start collecting positions.', 'ai-rank-suite')}
)}
item.keyword)}
onTrack={(next) => run(() => api.post('/rank/keywords', { keyword: next }))}
/>
{/* The four headline numbers in one bordered grid — density is the
feature, and the explanation lives in the `?` hover. */}
{/* Where the site is going, not just where it stands: the average
position across every tracked keyword, one point per daily
snapshot. Inverted, because on this axis lower is better. */}
{trend && trend.length > 1 && (
}
>
`#${v}`}
/>
{[
['top3', __('In the top 3', 'ai-rank-suite')],
['top10', __('On page one', 'ai-rank-suite')],
['clicks', __('Clicks that day', 'ai-rank-suite')],
].map(([key, label]) => {
const now = trend[trend.length - 1]?.[key] ?? 0;
const was = trend[0]?.[key] ?? 0;
return (
{label}
{now.toLocaleString()}
);
})}
)}
{/*
* The distribution, stacked — screenshot 4's chart.
*
* Each column is one daily snapshot: every tracked keyword that had
* a position that day, bucketed. The column's height is the total,
* so a site gaining rankings grows taller and a site trading
* page-one spots for page-five spots changes colour without
* changing height — two different stories a grouped chart would
* make the reader assemble themselves.
*/}
{(data.distribution || []).filter((d) => d.top3 + d.mid + d.low > 0).length >= 2 && (
({
label: d.d.slice(5),
top3: d.top3,
mid: d.mid,
low: d.low,
}))}
series={[
{ key: 'top3', label: __('Top 3', 'ai-rank-suite'), color: 'var(--ars-c-green-ink)' },
{ key: 'mid', label: '4–10', color: 'var(--ars-brand)' },
{ key: 'low', label: '11–50', color: 'var(--ars-accent)' },
]}
/>
)}
}
>
{/* The empty box is where people stall. The engine already reads
this site for meta descriptions; it can propose what to track. */}
{__('No keywords yet. Add one above, or hit “Sync now” to import your top queries from Search Console.', 'ai-rank-suite')}
) : (
{__('Keyword', 'ai-rank-suite')}
{__('Position', 'ai-rank-suite')}
{__('7-day change', 'ai-rank-suite')}
{__('30 days', 'ai-rank-suite')}
{__('Clicks', 'ai-rank-suite')}
{__('Impressions', 'ai-rank-suite')}
{data.keywords.map((k) => (
setOpen(k)} style={{ cursor: 'pointer' }}>
{k.keyword}
{k.source === 'auto' && (
auto
)}
{/* Position negated so climbing towards #1 draws as a
rising line — the same flip the detail chart makes,
because a sparkline that falls as you improve would
be read wrong by everyone, every time. */}