import React, { useCallback, useEffect, useRef, useState } from 'react';
import { __, _n, sprintf } from '@wordpress/i18n';
import { api } from '../api';
import { Card, Button, Badge, Notice, Bar, Switch, PageState, Panel, SectionTitle } from '../components/ui';
import rkSvg from '../icons/vendors/rk.svg?raw';
import aioSvg from '../icons/vendors/aio.svg?raw';
import tsfSvg from '../icons/vendors/seo-framework.svg?raw';
import suSvg from '../icons/vendors/seo-ultimate.svg?raw';
import slimSvg from '../icons/vendors/slim-seo.svg?raw';
import yoastSvg from '../icons/vendors/yoast.svg?raw';
import seopressSvg from '../icons/vendors/seopress.svg?raw';
/**
* The vendor mark for a migration card. Real artwork where we have it,
* bundled inline so the admin stays a single file; a tinted initial tile
* for the rest — never an empty square.
*/
export function VendorIcon({ id, label }) {
const art = { rankmath: rkSvg, aioseo: aioSvg, seoframework: tsfSvg, seoultimate: suSvg, slimseo: slimSvg, yoast: yoastSvg, seopress: seopressSvg }[id];
if (art) {
return (
);
}
const tint = { yoast: '#a4286a', seopress: '#5b43d6', smartcrawl: '#d63638', wpmetaseo: '#c150ba', squirrly: '#0e7c5a', jetpack: '#069e08', genesis: '#ff5000', woocommerce: '#7f54b3', redirection: '#2271b1' }[id] || 'var(--ars-brand)';
return (
{(label || '?').charAt(0)}
);
}
const num = (n) => Number(n || 0).toLocaleString();
const when = (ts) => (ts ? new Date(ts * 1000).toLocaleString() : '');
/** What a source holds, in one line the reader can check. */
function sourceSummary(s) {
const parts = [];
if (s.posts) parts.push(sprintf(_n('%s page', '%s pages', s.posts, 'ai-rank-suite'), num(s.posts)));
if (s.terms) parts.push(sprintf(_n('%s term', '%s terms', s.terms, 'ai-rank-suite'), num(s.terms)));
if (s.redirects) parts.push(sprintf(_n('%s redirect', '%s redirects', s.redirects, 'ai-rank-suite'), num(s.redirects)));
if (s.settings) parts.push(__('site-wide settings', 'ai-rank-suite'));
return parts.join(' · ');
}
/**
* The fields a run wrote, named rather than counted — and pluralised, because
* "1 titles" is the kind of detail that makes a report look machine-made.
*/
function fieldSummary(fields = {}) {
const label = (key, n) => {
switch (key) {
case 'title':
return sprintf(_n('%s title', '%s titles', n, 'ai-rank-suite'), num(n));
case 'desc':
return sprintf(_n('%s description', '%s descriptions', n, 'ai-rank-suite'), num(n));
case 'keywords':
return sprintf(_n('%s keyword set', '%s keyword sets', n, 'ai-rank-suite'), num(n));
case 'canonical':
return sprintf(_n('%s canonical', '%s canonicals', n, 'ai-rank-suite'), num(n));
case 'robots':
return sprintf(_n('%s robots directive', '%s robots directives', n, 'ai-rank-suite'), num(n));
case 'social':
return sprintf(_n('%s social card', '%s social cards', n, 'ai-rank-suite'), num(n));
case 'breadcrumb':
return sprintf(_n('%s breadcrumb title', '%s breadcrumb titles', n, 'ai-rank-suite'), num(n));
case 'schema':
return sprintf(_n('%s schema type', '%s schema types', n, 'ai-rank-suite'), num(n));
case 'sitemap':
return sprintf(_n('%s sitemap exclusion', '%s sitemap exclusions', n, 'ai-rank-suite'), num(n));
case 'term_title':
return sprintf(_n('%s term title', '%s term titles', n, 'ai-rank-suite'), num(n));
case 'term_desc':
return sprintf(_n('%s term description', '%s term descriptions', n, 'ai-rank-suite'), num(n));
case 'term_canonical':
return sprintf(_n('%s term canonical', '%s term canonicals', n, 'ai-rank-suite'), num(n));
case 'term_robots':
return sprintf(_n('%s term robots directive', '%s term robots directives', n, 'ai-rank-suite'), num(n));
case 'term_social':
return sprintf(_n('%s term social card', '%s term social cards', n, 'ai-rank-suite'), num(n));
case 'redirects':
return sprintf(_n('%s redirect', '%s redirects', n, 'ai-rank-suite'), num(n));
case 'settings':
return sprintf(_n('%s setting', '%s settings', n, 'ai-rank-suite'), num(n));
default:
return `${num(n)} ${key}`;
}
};
return Object.entries(fields)
.filter(([, v]) => v > 0)
.map(([k, v]) => label(k, v))
.join(' · ');
}
export default function Import() {
const [data, setData] = useState(null);
const [overwrite, setOverwrite] = useState(false);
const [parts, setParts] = useState({ settings: true, posts: true, terms: true, redirects: true });
const [job, setJob] = useState(null);
const [progress, setProgress] = useState(null);
const [error, setError] = useState(null);
const [backup, setBackup] = useState(null);
const [busy, setBusy] = useState(false);
const [file, setFile] = useState(null);
const running = useRef(false);
const fileRef = useRef(null);
const dataFileRef = useRef(null);
const load = useCallback(
() =>
api
.get('/import/detect')
.then((d) => {
setData(d);
setJob(d.job && d.job.state === 'running' ? d.job : null);
})
.catch((e) => setError(e.message)),
[]
);
useEffect(() => {
load();
api.get('/settings/backup').then(setBackup).catch(() => {});
}, [load]);
/**
* Start a run and tick it to the end. The server does the work in slices;
* this loop only keeps asking, so closing the tab pauses rather than
* breaks — cron picks the same run up from its cursor.
*/
const pump = async (body, label) => {
if (running.current) return;
running.current = true;
setError(null);
setProgress({ label, counts: {}, done: false });
try {
let s = await api.post('/import/start', body);
setJob(s);
const carry = (state, done) => ({
label,
source: body.source || state.source || '',
dryRun: !!body.dry_run,
total: state.total || 0,
counts: state.counts || {},
fields: state.fields || {},
importId: state.import_id,
errors: state.errors || [],
done,
});
while (s.state === 'running') {
s = await api.post('/import/tick', {});
setJob(s.state === 'running' ? s : null);
setProgress(carry(s, s.state !== 'running'));
if (s.busy || s.error) await new Promise((r) => setTimeout(r, 1500));
}
setProgress(carry(s, true));
} catch (e) {
setError(e.message);
} finally {
running.current = false;
setJob(null);
load();
}
};
const chosenParts = Object.entries(parts)
.filter(([, on]) => on)
.map(([k]) => k);
const runImport = (source, dryRun) =>
pump(
{ source, mode: overwrite ? 'overwrite' : 'fill', dry_run: dryRun, parts: chosenParts },
dryRun ? __('Preview', 'ai-rank-suite') : __('Import', 'ai-rank-suite')
);
const undo = (importId) => pump({ undo: importId }, __('Undo', 'ai-rank-suite'));
const cancel = async () => {
try {
await api.post('/import/cancel', {});
} catch (e) {
setError(e.message);
}
};
// --- CSV/JSON ---------------------------------------------------------
const readFile = async (f) => {
setError(null);
try {
const content = await f.text();
const format = /\.json$/i.test(f.name) ? 'json' : 'csv';
const parsed = await api.post('/import/preview-file', { content, format });
if (parsed.error) {
setError(parsed.error);
return;
}
// Guess the mapping from the column names: an export from this
// plugin, or a spreadsheet whose headers say what they hold, needs
// no mapping at all.
const guess = {};
(parsed.columns || []).forEach((c) => {
const k = c.toLowerCase();
if (/^(seo[_ ]?)?title$/.test(k)) guess[c] = 'title';
else if (/desc/.test(k)) guess[c] = 'desc';
else if (/keyword|keyphrase/.test(k)) guess[c] = 'keywords';
else if (/canonical/.test(k)) guess[c] = 'canonical';
else if (/robots|noindex/.test(k)) guess[c] = 'robots';
else if (/og[_ ]?image/.test(k)) guess[c] = 'og_image';
else if (/og[_ ]?title/.test(k)) guess[c] = 'og_title';
});
const match = (parsed.columns || []).includes('id') ? 'id' : (parsed.columns || []).includes('url') ? 'url' : 'slug';
setFile({ name: f.name, content, format, ...parsed, map: guess, match });
} catch (e) {
setError(e.message);
} finally {
if (dataFileRef.current) dataFileRef.current.value = '';
}
};
const runFileImport = (dryRun) =>
pump(
{
source: 'file',
mode: overwrite ? 'overwrite' : 'fill',
dry_run: dryRun,
file: { content: file.content, format: file.format, match: file.match, map: file.map },
},
dryRun ? __('Preview', 'ai-rank-suite') : __('File import', 'ai-rank-suite')
);
// --- export / backup (unchanged behaviour) ----------------------------
const download = (blob, name) => {
const a = document.createElement('a');
a.href = URL.createObjectURL(blob);
a.download = name;
a.click();
URL.revokeObjectURL(a.href);
};
const stamp = () => new Date().toISOString().slice(0, 10);
const exportSettings = async () => {
setBusy(true);
try {
const payload = await api.get('/settings/export');
download(new Blob([JSON.stringify(payload, null, 2)], { type: 'application/json' }), `ai-rank-suite-settings-${stamp()}.json`);
} catch (e) {
setError(e.message);
} finally {
setBusy(false);
}
};
const exportCsv = async () => {
setBusy(true);
try {
const cols = ['id', 'title', 'url', 'seo_title', 'seo_desc', 'keyword'];
const rows = [];
let after = 0;
let total = null;
for (let guard = 0; guard < 400; guard++) {
const r = await api.get(`/content/csv?after=${after}&per_page=500`);
rows.push(...(r.rows || []));
total = r.total ?? total;
setProgress({ exported: rows.length, of: total });
if (r.next === null || r.next === undefined) break;
after = r.next;
}
// Spreadsheets execute a cell that begins with = + - @ or a tab; a
// title typed as "=HYPERLINK(...)" must open as text.
const cell = (v) => {
let s = String(v ?? '').replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g, '');
if (/^[=+\-@\t]/.test(s)) s = "'" + s;
return `"${s.replace(/"/g, '""')}"`;
};
const lines = [cols.join(','), ...rows.map((row) => cols.map((c) => cell(row[c])).join(','))];
download(new Blob(['\ufeff' + lines.join('\r\n')], { type: 'text/csv;charset=utf-8' }), `ai-rank-suite-seo-data-${stamp()}.csv`);
setProgress({ exported: rows.length, of: total, done: true });
} catch (e) {
setError(e.message);
} finally {
setBusy(false);
}
};
const importSettings = async (f) => {
setBusy(true);
setError(null);
try {
const payload = JSON.parse(await f.text());
const r = await api.post('/settings/import', { payload });
setProgress({ settings: r.applied });
} catch (e) {
setError(e.message);
} finally {
setBusy(false);
if (fileRef.current) fileRef.current.value = '';
}
};
const restore = async () => {
setBusy(true);
try {
await api.post('/settings/backup');
setProgress({ restored: true });
} catch (e) {
setError(e.message);
} finally {
setBusy(false);
}
};
if (!data) return
{e.what} — {e.message}
{__('No other SEO plugin, and no data left behind by one, was found on this site. When one is installed its card appears here with what it holds.', 'ai-rank-suite')}
)}{__('Template variables such as %%title%% are translated into this plugin’s own. A variable nothing here can resolve is dropped rather than printed into your pages. Run the content analysis afterwards so the scores reflect the imported data.', 'ai-rank-suite')}
{e.what} — {e.message}
{__('API keys and license data are never included in an export.', 'ai-rank-suite')} {backup?.exists && ` ${sprintf(__('A backup from version %s was taken automatically before the last update.', 'ai-rank-suite'), backup.from)}`}