import { __, _n, sprintf } from '@wordpress/i18n';
import React, { useCallback, useEffect, useState } from 'react';
import { api } from '../api';
import ScreenVerdict from '../components/ScreenVerdict';
import { Card, Button, Badge, Notice, MetricGrid, FilterBar, ChipBar, Field, RankBar, Segmented, PageState, LineChart, Delta } from '../components/ui';
import Explain from '../components/Explain';
import { IconLink, IconRefresh, IconSearch, IconExternal, IconX } from '../components/icons';
/**
* Backlinks.
*
* The honest version. No plugin can produce an Ahrefs-style index from inside
* a WordPress install, so this is built around the two things a site really
* knows — who sends it visitors, and what a source page says when you read it
* — plus Bing's free index for anyone who wants breadth. Every row says where
* it came from.
*/
const STATUS = {
live: { tone: 'good', label: __('Live', 'ai-rank-suite'), why: __('Read the page; the link is there and followed.', 'ai-rank-suite') },
nofollow: { tone: 'neutral', label: __('Nofollow', 'ai-rank-suite'), why: __('The link is there but carries rel=nofollow, ugc or sponsored.', 'ai-rank-suite') },
lost: { tone: 'serious', label: __('Lost', 'ai-rank-suite'), why: __('We read the page and the link is no longer on it.', 'ai-rank-suite') },
unreachable: { tone: 'warning', label: __('Unreachable', 'ai-rank-suite'), why: __('The source did not answer. Not the same as removed.', 'ai-rank-suite') },
unverified: { tone: 'brand', label: __('Unverified', 'ai-rank-suite'), why: __('Known from a visit or an import; not read yet.', 'ai-rank-suite') },
};
const VIA = {
referrer: __('A real visitor arrived through it', 'ai-rank-suite'),
bing: 'Bing Webmaster Tools',
import: __('Imported by you', 'ai-rank-suite'),
};
export default function Backlinks() {
const [data, setData] = useState(null);
const [error, setError] = useState(null);
const [busy, setBusy] = useState(false);
const [status, setStatus] = useState('');
const [growth, setGrowth] = useState(null);
const [via, setVia] = useState('');
const [search, setSearch] = useState('');
const [page, setPage] = useState(1);
const [view, setView] = useState('links');
const [bingKey, setBingKey] = useState('');
const [note, setNote] = useState(null);
const load = useCallback(
async (p = page, st = status, v = via, q = search) => {
try {
const params = new URLSearchParams({
page: String(p),
per_page: '25',
status: st,
via: v,
search: q,
});
setData(await api.get(`/backlinks?${params}`));
setError(null);
} catch (e) {
setError(e.message);
}
},
[page, status, via, search]
);
useEffect(() => {
load(page, status, via, search);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [page, status, via]);
useEffect(() => {
api.get('/backlinks/growth?weeks=26').then((r) => setGrowth(r.weeks || [])).catch(() => setGrowth([]));
}, []);
if (!data) return ;
const s = data.summary || {};
const pages = Math.max(1, Math.ceil((data.total || 0) / 25));
const verify = async (ids) => {
setBusy(true);
setNote(null);
try {
const r = await api.post('/backlinks/verify', { ids: ids || [] });
setNote(
r.checked === 0
? __('Nothing was waiting to be checked — every link has been read in the last week.', 'ai-rank-suite')
: sprintf(_n('Read %1$d source page. %2$d still queued.', 'Read %1$d source pages. %2$d still queued.', r.checked, 'ai-rank-suite'), r.checked, r.pending)
);
await load();
} catch (e) {
setError(e.message);
} finally {
setBusy(false);
}
};
const importBing = async () => {
setBusy(true);
setNote(null);
try {
const r = await api.post('/backlinks/bing');
setNote(sprintf(__('Bing returned %1$s links across %2$s of your pages.', 'ai-rank-suite'), r.imported, r.pages));
await load();
} catch (e) {
setError(e.message);
} finally {
setBusy(false);
}
};
const saveBing = async () => {
setBusy(true);
try {
await api.put('/backlinks/bing', { key: bingKey });
setBingKey('');
await load();
} catch (e) {
setError(e.message);
} finally {
setBusy(false);
}
};
const forget = async (id) => {
await api.del(`/backlinks/${id}`);
load();
};
return (
{error && {error}}
{note && {note}}
{/*
* Zero backlinks and zero connected sources look identical in a row
* of zeroes, and they mean opposite things: one is a site nobody
* links to, the other is a screen that has never been given anything
* to read. Say which.
*/}
{
const sum = data?.summary || {};
const links = sum.total || 0;
// The API reports the one source it can read: Bing.
const connected = !!data?.bing?.connected;
if (!connected) {
return {
tone: 'neutral',
text: __('No backlink source is connected, so this screen has nothing to read.', 'ai-rank-suite'),
why: __('Bing Webmaster Tools is free and is the one backlink index a site can read for its own domain. Connect it under Sources and the numbers below fill in.', 'ai-rank-suite'),
action: __('Open Sources', 'ai-rank-suite'),
onAction: () => setView('sources'),
};
}
if (links === 0) {
return {
tone: 'warning',
text: __('Connected, but no backlinks have come back yet.', 'ai-rank-suite'),
why: __('Either the index genuinely has none for this domain, or the site is not verified in that account — Bing only returns links for a site you own there.', 'ai-rank-suite'),
};
}
return {
tone: sum.lost > 0 ? 'warning' : 'good',
text: sprintf(
/* translators: 1: links, 2: domains. */
_n('%1$s link from %2$s domains.', '%1$s links from %2$s domains.', links, 'ai-rank-suite'),
links.toLocaleString(),
(sum.domains || 0).toLocaleString()
),
why:
sum.lost > 0
? sprintf(__('%s were there before and are not now — a lost link is worth chasing while the editor still remembers the page.', 'ai-rank-suite'), sum.lost.toLocaleString())
: __('Nothing has been lost since the last check. The anchors below show what those links say you are about.', 'ai-rank-suite'),
};
})()}
/>
{/*
* Four toned tiles became one bordered grid. The sentence under each
* tile is a `?` hover now; what remains under a number is a data fact.
* Colour is reserved for the one genuine alert — links that are gone.
*/}
0 ? 'var(--ars-c-red-ink)' : undefined,
},
{
id: 'clicks',
label: __('Clicks through', 'ai-rank-suite'),
hint: __('Visits that arrived by a link — the links that actually send you people.', 'ai-rank-suite'),
value: s.clicks ?? '—',
},
]}
/>
{/* Cumulative, from first_seen — "are we earning links" is a line
that climbs, not a bar chart of weekly noise. Two points minimum,
or there is no trend to claim. */}
{growth && growth.length > 1 && (
}
>
`${v}`}
/>
)}
{view === 'links' && (
}
title={__('Every link we know about', 'ai-rank-suite')}
subtitle={__('Where it came from, whether the page still carries it, and what the anchor says', 'ai-rank-suite')}
action={
{__('The list fills itself: every visitor who arrives from another site proves a link exists and gets recorded here. Connect Bing Webmaster Tools under Sources for the links nobody has clicked yet.', 'ai-rank-suite')}
{__('A healthy profile is mostly your brand name and natural phrases. A single commercial keyword dominating the list is the pattern link schemes produce, and the pattern penalties look for.', 'ai-rank-suite')}
{__('No plugin can produce an Ahrefs-style backlink index from inside a WordPress install — those are built by crawling the web for years. So this is built around three sources, and every row says which one it came from.', 'ai-rank-suite')}
{__('Visitors.', 'ai-rank-suite')}{' '}
{__('Someone arriving from another domain proves a link exists and that it is being clicked. That is a smaller set than a commercial index and a more useful one: these are the links that send you people. Note that a full-page cache serves most visits without PHP running, so a site behind one records fewer referrals than it receives.', 'ai-rank-suite')}
{__('Verification.', 'ai-rank-suite')}{' '}
{__('For any link here, the source page is fetched and read: is the link still on it, what does the anchor say, is it nofollow. A commercial index tells you a link existed when it last crawled. This tells you what the page says now — which is why “Lost” is a claim worth trusting, and why “Unreachable” is kept separate from it rather than counted as a removal.', 'ai-rank-suite')}
{__('Bing.', 'ai-rank-suite')}{' '}
{__('Free, real crawl data, limited to sites verified in your Webmaster Tools account and to Bing\'s own index, which is smaller than Google\'s. Useful for breadth; not a total.', 'ai-rank-suite')}