import React, { useEffect, useMemo, useState } from 'react';
import { __, _n, sprintf } from '@wordpress/i18n';
import { api } from '../api';
import { readTheme, writeTheme } from '../theme.js';
import { Card, Switch, Badge, Button, Notice, MetricGrid, PageState, Field } from '../components/ui';
import Explain from '../components/Explain';
import { IconShield, IconLayers, IconGauge, IconExternal, IconSliders, IconDownload } from '../components/icons';
const MODULE_GROUPS = [
{ id: 'ai', label: __('AI search', 'ai-rank-suite'), hint: __('Everything that makes assistants find, read and recommend you', 'ai-rank-suite') },
{ id: 'search', label: __('Google search', 'ai-rank-suite'), hint: __('Classic SEO output, indexing and performance data', 'ai-rank-suite') },
{ id: 'content', label: __('Content', 'ai-rank-suite'), hint: __('Per-page analysis, bulk work, links and redirects', 'ai-rank-suite') },
{ id: 'system', label: __('System', 'ai-rank-suite'), hint: __('Housekeeping, integrations and developer tooling', 'ai-rank-suite') },
];
/**
* Module manager. The promise this screen makes is that switching something
* off is safe and reversible — so it says so, shows what is actually running,
* and never silently discards a setting.
*/
export function Modules() {
const [data, setData] = useState(null);
const [status, setStatus] = useState(null);
const [query, setQuery] = useState('');
const [saved, setSaved] = useState(false);
const [busy, setBusy] = useState(false);
const [error, setError] = useState(null);
const [dirty, setDirty] = useState(false);
// What the server last confirmed, and whether the person has read the
// warning for a module that must be switched on knowingly. The server
// refuses the transition off → on without the acknowledgement, so the
// screen has to know the saved state to tell a transition from a state.
const [savedOn, setSavedOn] = useState({});
const [acknowledged, setAcknowledged] = useState(false);
const remember = (payload) => {
setData(payload);
setSavedOn(Object.fromEntries((payload?.modules || []).map((m) => [m.id, !!m.enabled])));
setAcknowledged(false);
};
useEffect(() => {
api.get('/settings/general').then(remember).catch((e) => setError(e.message));
// Optional: the module manager is still fully usable without it.
api.get('/dev/status').then(setStatus).catch(() => {});
}, []);
const optional = useMemo(() => (data?.modules || []).filter((m) => m.optional), [data]);
const filtered = useMemo(() => {
const q = query.trim().toLowerCase();
if (!q) return optional;
return optional.filter((m) => m.label.toLowerCase().includes(q) || m.desc.toLowerCase().includes(q));
}, [optional, query]);
if (!data) return ;
const flash = () => {
setSaved(true);
setTimeout(() => setSaved(false), 2200);
};
const setModules = (fn) => {
setData({ ...data, modules: data.modules.map(fn) });
setDirty(true);
};
const toggleModule = (id, enabled) => setModules((m) => (m.id === id ? { ...m, enabled } : m));
const setAll = (enabled) => setModules((m) => (m.optional ? { ...m, enabled } : m));
// Modules that execute code and are about to go from off to on. Each one
// needs the acknowledgement flag in the request, or the server refuses.
const needsAck = (data?.modules || []).filter((m) => m.acknowledge && m.enabled && !savedOn[m.id]);
const ackMissing = needsAck.length > 0 && !acknowledged;
const save = async () => {
if (ackMissing) return;
setBusy(true);
setError(null);
try {
const disabled = data.modules.filter((m) => !m.enabled).map((m) => m.id);
const body = { disabled };
needsAck.forEach((m) => {
body[`acknowledge_${m.id}`] = true;
});
remember(await api.put('/settings/modules', body));
setDirty(false);
flash();
} catch (e) {
setError(e.message);
} finally {
setBusy(false);
}
};
const enabled = optional.filter((m) => m.enabled).length;
const quarantine = Object.keys(status?.modules?.quarantine || {});
return (
{error && {error}}
0 ? 'var(--ars-c-red-ink)' : undefined,
sub: quarantine.length > 0 ? quarantine.join(', ') : __('no module has failed', 'ai-rank-suite'),
},
{
id: 'version',
label: __('Plugin version', 'ai-rank-suite'),
hint: __('Settings survive every update — a snapshot is taken automatically before each one.', 'ai-rank-suite'),
value: status?.environment?.plugin ? `v${status.environment.plugin}` : '—',
sub: status?.environment?.db_schema ? sprintf(__('database schema %s', 'ai-rank-suite'), status.environment.db_schema) : undefined,
},
]}
/>
{quarantine.length > 0 && (
{quarantine.join(', ')} stopped with an error and was isolated so the rest of the plugin keeps working. Open{' '}
{' '}
to see the error and clear the quarantine.
)}
{/* Rank Math keeps its wizard permanently available as a tab, and it
is right: a setup wizard that can only ever run once is a wizard
nobody can use after the day they installed the plugin. */}
}
title={__('Setup wizard', 'ai-rank-suite')}
subtitle={__('Re-run the guided setup any time — it never overwrites a field you have already filled in', 'ai-rank-suite')}
action={
}
>
{__('Six questions — what the site is, which industry and market it serves, which AI engines matter to you — and it configures the schema type, business defaults, prompts and llms.txt accordingly. Useful after a rebrand, after adding a second market, or simply to see what it would suggest.', 'ai-rank-suite')}
} title={__('Modules', 'ai-rank-suite')}
subtitle={__('Switch off what you don’t use — a disabled module loads no code, registers no hooks and adds zero overhead', 'ai-rank-suite')}
action={
{dirty && {__('Nothing is switched until you press “Apply changes”.', 'ai-rank-suite')}}
{/* The one module that executes code is off on a new install
and comes on only through this step. The server refuses the
request without the flag, so this is not decoration: without
the box ticked, "Apply changes" does nothing. */}
{needsAck.length > 0 && (
{needsAck.map((m) => m.label).join(', ')}{' '}
{__('runs PHP that is typed into this admin. Anyone with the “edit plugins” capability can then execute code on this server. A snippet with a mistake is switched off automatically after one failed request; a snippet written to do harm is not.', 'ai-rank-suite')}
{modules.map((m) => (
// A card that is "on" should look solid and a card that is
// "off" should look switched off. Filling the enabled one
// with grey did the opposite: the active state was the
// duller of the two, and forty grey rectangles read as a
// wireframe rather than a product.
{__('Settings of a disabled module are kept untouched — switch it back on and everything is exactly as you left it. Essential modules (core, settings, licensing) are not listed here: turning them off would take this screen down with them.', 'ai-rank-suite')}
);
}
/**
* Everything about the customer's data: the snapshot taken before each update,
* portable configuration, and what happens on uninstall.
*/
export function DataPrivacy() {
const [data, setData] = useState(null);
const [backup, setBackup] = useState(null);
const [busy, setBusy] = useState(false);
const [saved, setSaved] = useState(false);
const [restored, setRestored] = useState(false);
const [importing, setImporting] = useState(false);
const [imported, setImported] = useState(null);
const [error, setError] = useState(null);
const load = () => {
api.get('/settings/general').then(setData).catch((e) => setError(e.message));
api.get('/settings/backup').then(setBackup).catch(() => {});
};
useEffect(load, []);
if (!data) return ;
const flash = () => {
setSaved(true);
setTimeout(() => setSaved(false), 2200);
};
const toggleKeepData = async (value) => {
setError(null);
try {
setData(await api.put('/settings/general', { keep_data_on_uninstall: value }));
flash();
} catch (e) {
setError(e.message);
}
};
const restore = async () => {
setBusy(true);
setError(null);
try {
await api.post('/settings/backup', {});
setRestored(true);
setTimeout(() => setRestored(false), 3000);
} catch (e) {
setError(e.message);
} finally {
setBusy(false);
}
};
const exportConfig = async () => {
setError(null);
try {
const payload = await api.get('/settings/export');
const blob = new Blob([JSON.stringify(payload, null, 2)], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `ai-rank-suite-config-${new Date().toISOString().slice(0, 10)}.json`;
document.body.appendChild(a);
a.click();
a.remove();
URL.revokeObjectURL(url);
} catch (e) {
setError(e.message);
}
};
const importConfig = async (file) => {
if (!file) return;
setImporting(true);
setError(null);
setImported(null);
try {
const text = await file.text();
const parsed = JSON.parse(text);
// The endpoint takes the whole export under `payload` and validates
// its format marker before touching a single option.
const r = await api.post('/settings/import', { payload: parsed });
setImported(r);
load();
} catch (e) {
setError(e instanceof SyntaxError ? __('That file is not valid JSON — pick a config exported from this plugin.', 'ai-rank-suite') : e.message);
} finally {
setImporting(false);
}
};
return (
{error && {error}}
{saved && {__('Saved.', 'ai-rank-suite')}}
} title={__('Updates & data safety', 'ai-rank-suite')} subtitle={__('Your configuration survives every update — that is a promise, not a hope', 'ai-rank-suite')}>
{__('Automatic snapshot', 'ai-rank-suite')}
{backup?.exists
? sprintf(__('Taken before the update to v%1$s, on %2$s. Every setting of every module is included.', 'ai-rank-suite'), backup.from, new Date(backup.time * 1000).toLocaleString())
: __('A snapshot of all settings is taken automatically before every update. None exists yet — the first one appears with your next update.', 'ai-rank-suite')}
{backup?.exists && (
)}
{restored && {__('Settings restored from the backup snapshot.', 'ai-rank-suite')}}
} title={__('Portable configuration', 'ai-rank-suite')}
subtitle={__('Move a finished setup to another site, or keep a copy outside the database', 'ai-rank-suite')}
>
{imported && (
0 ? 'good' : 'warning'}>
{imported.skipped > 0
? sprintf(__('Applied %1$d settings groups, skipped %2$d that this version does not recognise. Reload the page to see them everywhere.', 'ai-rank-suite'), imported.applied, imported.skipped)
: sprintf(_n('Applied %d settings group. Reload the page to see them everywhere.', 'Applied %d settings groups. Reload the page to see them everywhere.', imported.applied, 'ai-rank-suite'), imported.applied)}
)}
{__('The export contains settings only — never API keys, license keys or content. That is deliberate: a config file often ends up in a repository or a shared drive, and a secret in it would outlive the site it came from.', 'ai-rank-suite')}
{__('Recommended. Turn this off only if you want every setting, score, redirect and keyword removed from the database on uninstall — that cannot be undone.', 'ai-rank-suite')}
{!data.keep_data_on_uninstall && (
{__('Deletion on uninstall is enabled: removing the plugin will permanently erase all its data.', 'ai-rank-suite')}
)}
);
}
export default Modules;
/* -------------------------------------------------------------------------
Environment
Before anyone buys an SEO plugin they want three answers: will it fight the
plugin I already run, does it understand my page builder, and does it work
in my second language. Those answers lived in four different modules and in
no screen at all, which meant the honest answer was a support ticket. One
read-only page, everything it knows about this site.
------------------------------------------------------------------------- */
const HEALTH_TONE = { good: 'green', warn: 'yellow', bad: 'red' };
const HEALTH_MARK = { good: '✓', warn: '!', bad: '×' };
function Row({ active, label, children, note }) {
return (
{error && {error}}
p.label).join(', ') : __('running solo', 'ai-rank-suite'),
},
{
id: 'languages',
label: __('Languages', 'ai-rank-suite'),
hint: __('Translation plugins are read directly — no mapping to set up.', 'ai-rank-suite'),
value: ml.multilingual ? ml.languages.length : 1,
sub: ml.multilingual ? ml.label : __('single language', 'ai-rank-suite'),
},
{
id: 'integrations',
label: __('Integrations active', 'ai-rank-suite'),
hint: __('Plugins read automatically to make the structured data richer — nothing to configure.', 'ai-rank-suite'),
value: `${activeIntegrations.length} / ${integrations.length}`,
},
]}
/>
} title={__('Site health', 'ai-rank-suite')}
subtitle={__('What this server lets the plugin do — and what to change if something is holding it back', 'ai-rank-suite')}
>
{__('Check', 'ai-rank-suite')}
{__('Value', 'ai-rank-suite')}
{__('What it means', 'ai-rank-suite')}
{(data.health || []).map((h) => (
{HEALTH_MARK[h.status]}
{h.label}
{h.value}
{h.note}
))}
} title={__('Other SEO plugins', 'ai-rank-suite')}
subtitle={__('Detected on this site, with the tags each one normally writes', 'ai-rank-suite')}
>
{(data.importable || []).length > 0 && (
{data.importable
.map(
(i) =>
sprintf(_n('%1$s: %2$s page', '%1$s: %2$s pages', i.posts, 'ai-rank-suite'), i.label, i.posts.toLocaleString()) +
(i.redirects ? ' ' + sprintf(__('and %s redirects', 'ai-rank-suite'), i.redirects.toLocaleString()) : '')
)
.join(' · ')}{' '}
can be brought across without retyping anything.{' '}
)}
{(data.seo_plugins || []).length === 0 ? (
{__('None found — AI Rank Suite owns the whole head, which is the simplest setup there is. If you install one later, the Compatibility tab decides tag by tag who writes what, so the two never double up.', 'ai-rank-suite')}
{__('Running two SEO plugins is normally a broken head — two titles, two canonicals, a doubled schema graph. Here it is a supported configuration: every surface has exactly one owner, and you can see the decision on the Compatibility tab.', 'ai-rank-suite')}
)}
} title={__('Languages', 'ai-rank-suite')} subtitle={__('Translation plugins are read directly — no mapping to set up', 'ai-rank-suite')}>
} title={__('Page builders', 'ai-rank-suite')} subtitle={__('What the analyser reads when the content is not in the post body', 'ai-rank-suite')}>
{(data.builders || []).map((b) => (
))}
{__('A page built with Elementor or Divi stores almost nothing in the post body — the text a visitor reads lives in meta fields the builder renders later. An SEO plugin that reads the post body sees an empty page, scores it badly, and writes a meta description from nothing. Every check here runs against the rendered output instead, which is why the word count on a builder page matches what you actually see.', 'ai-rank-suite')}
} title={__('Connected services', 'ai-rank-suite')}
subtitle={__('Where real data comes from — all optional, most of them free', 'ai-rank-suite')}
>
} title={__('Content integrations', 'ai-rank-suite')}
subtitle={__('Plugins we read from automatically to make the structured data richer', 'ai-rank-suite')}
action={
}
>
{shown.length === 0 ? (
{__('None of the supported plugins is installed. Nothing is missing — this list only ever adds detail to schema that is already being emitted.', 'ai-rank-suite')}
) : (
{shown.map((i) => (
))}
)}
);
}
/**
* The agency's name on the menu and the header, and no vendor line in the
* footer. Presentation only: the Plugins screen still says what the plugin
* is, and every route and hook keeps its name.
*/
function WhiteLabel({ data, onSaved }) {
const [brand, setBrand] = useState(data.brand_name || '');
const [busy, setBusy] = useState(false);
const [error, setError] = useState(null);
const [saved, setSaved] = useState(false);
const dirty = brand !== (data.brand_name || '');
const put = async (patch) => {
setBusy(true);
setError(null);
try {
onSaved(await api.put('/settings/general', patch));
setSaved(true);
setTimeout(() => setSaved(false), 2200);
} catch (e) {
setError(e.message);
} finally {
setBusy(false);
}
};
const [theme, setTheme] = useState(readTheme);
return (
}
title={__('Appearance & white label', 'ai-rank-suite')}
subtitle={__('Put your agency\'s name on the plugin your clients see', 'ai-rank-suite')}
action={saved && ✓ {__('Saved', 'ai-rank-suite')}}
>
put({ hide_footer: v })}
label={__('Hide the vendor line at the foot of the sidebar', 'ai-rank-suite')}
/>
setTheme(writeTheme(v ? 'dark' : 'light'))}
label={__('Dark theme for this plugin\'s screens', 'ai-rank-suite')}
/>
{__('Stored in this browser only — it changes nothing for anyone else, and nothing outside these screens.', 'ai-rank-suite')}
{error && {error}}
{__('For an agency running the plugin on client sites: the client sees your name, your reports, your work. The toolbar menu can be hidden under Advanced → Ghost Mode, and client access is set per role under Advanced → Roles. The Plugins screen keeps the real plugin name — that is a WordPress rule, and the right one.', 'ai-rank-suite')}
);
}
/**
* How long the plugin keeps its own logs. Days; 0 keeps everything. A daily
* job prunes to these — on a busy site the AI ledger and the 404 monitor are
* the two tables that otherwise grow forever.
*/
function Retention({ data, onSaved }) {
const [values, setValues] = useState({
retention_ai_usage_days: data.retention_ai_usage_days ?? 365,
retention_404_days: data.retention_404_days ?? 90,
retention_crawler_days: data.retention_crawler_days ?? 90,
});
const [busy, setBusy] = useState(false);
const [error, setError] = useState(null);
const [saved, setSaved] = useState(false);
const dirty = Object.keys(values).some((k) => Number(values[k]) !== Number(data[k] ?? 0));
const save = async () => {
setBusy(true);
setError(null);
try {
onSaved(await api.put('/settings/general', values));
setSaved(true);
setTimeout(() => setSaved(false), 2200);
} catch (e) {
setError(e.message);
} finally {
setBusy(false);
}
};
const ROWS = [
['retention_ai_usage_days', __('AI usage ledger', 'ai-rank-suite'), __('One row per model call — cost, tokens, job. Budgets and the usage screen read the last 30 days; older rows are history.', 'ai-rank-suite')],
['retention_404_days', __('404 monitor', 'ai-rank-suite'), __('Missing paths and how often they were hit. A path nobody has hit in this many days is dropped.', 'ai-rank-suite')],
['retention_crawler_days', __('AI crawler visits', 'ai-rank-suite'), __('Per-bot daily counters from the crawler recorder.', 'ai-rank-suite')],
];
return (
{saved && ✓ {__('Saved', 'ai-rank-suite')}}
}
>
{__('Consent-log retention lives with the consent settings (Analytics → Consent), because it is a legal setting rather than a housekeeping one.', 'ai-rank-suite')}