import React, { useEffect, useMemo, useState } from 'react'; import { __, _n, sprintf } from '@wordpress/i18n'; import { api, env } from '../api'; import { Button, Notice, Spinner } from '../components/ui'; import { VendorIcon } from './Import'; /** * First-run setup, structured the way SEOPress structures it: a numbered * step rail on the left that shows the whole journey at once, and one * working card on the right. Every step writes a real setting; "Save and * continue" is a save, not a page turn. */ /* ------------------------------------------------------------------ */ /* Shared chrome */ /* ------------------------------------------------------------------ */ const IconCheckSmall = () => ( ); const IconChevronLeft = () => ( ); const IconArrowRight = () => ( ); const IconUpload = () => ( ); const IconDone = () => ( ); /** One-colour marks for the social step — recognisable, not trademark art. */ const SOCIAL_MARKS = { facebook: ( ), x: ( ), pinterest: ( ), instagram: ( ), youtube: ( ), linkedin: ( ), }; /** `[post]`-style code chip inside running text. */ const Code = ({ children }) => {children}; /** SEOPress-style info callout: tinted panel with a solid left bar. */ function Callout({ tone = 'info', children }) { return
{children}
; } /** Small-caps field label, SEOPress-style. */ function FieldLabel({ children }) { return (
{children}
); } function FieldHint({ children }) { return (

{children}

); } /** One exclusion checkbox row: Exclude `[slug]` from search engine. */ function ExcludeRow({ checked, onChange, slug, label, sub, disabled = false, example }) { return (
{(sub || example) && (
{sub &&
{sub}
} {example && (
{__('Example:', 'ai-rank-suite')} {example}
)}
)}
); } /** * The card frame every sub-step renders in: title, lede, body, and the * Back / Skip / primary footer. */ function StepCard({ title, lede, children, footer }) { return (

{title}

{lede &&

{lede}

}
{children}
{footer &&
{footer}
}
); } /* ------------------------------------------------------------------ */ /* The site-title template editor: token chips plus free text */ /* ------------------------------------------------------------------ */ const TITLE_TOKENS = () => ({ '%sitename%': __('Site title', 'ai-rank-suite'), '%sep%': __('Separator', 'ai-rank-suite'), '%tagline%': __('Tagline', 'ai-rank-suite'), '%currentyear%': __('Current year', 'ai-rank-suite'), }); const partsFromTemplate = (template) => String(template || '') .split(/(%[a-z_]+%)/) .map((chunk) => chunk.trim()) .filter(Boolean) .map((chunk) => (/^%[a-z_]+%$/.test(chunk) ? { token: chunk } : { text: chunk })); const templateFromParts = (parts) => parts.map((p) => (p.token ? p.token : p.text)).join(' '); function TitleBuilder({ parts, onChange, resolve }) { const tokens = TITLE_TOKENS(); const [draft, setDraft] = useState(''); const commitDraft = () => { const text = draft.trim(); if (text) onChange([...parts, { text }]); setDraft(''); }; return (
{parts.map((p, i) => ( {p.token ? tokens[p.token] || p.token : p.text} ))} setDraft(e.target.value)} onBlur={commitDraft} onKeyDown={(e) => { if (e.key === 'Enter') { e.preventDefault(); commitDraft(); } }} placeholder={parts.length ? '' : __('Type text or add a variable below…', 'ai-rank-suite')} style={{ flex: '1 1 120px', minWidth: 100, border: 0, outline: 'none', background: 'none', font: 'inherit', fontSize: 13, boxShadow: 'none', padding: 4 }} /> {parts.length > 0 && ( )}
{__('Preview:', 'ai-rank-suite')}{' '} {resolve(templateFromParts(parts)) || __('(empty — the default template applies)', 'ai-rank-suite')}
{Object.entries(tokens).map(([token, label]) => { const used = parts.some((p) => p.token === token); return ( ); })}
); } /* ------------------------------------------------------------------ */ /* The wizard */ /* ------------------------------------------------------------------ */ export default function Wizard({ onDone }) { /** * The journey. Groups carry the rail number; subs carry the cards. * Order here is the order of "Save and continue". */ const GROUPS = useMemo( () => [ { id: 'welcome', label: __('Welcome', 'ai-rank-suite'), subs: [ { id: 'start', label: __('Get started', 'ai-rank-suite') }, { id: 'import-config', label: __('Import configuration', 'ai-rank-suite') }, { id: 'import-meta', label: __('Import metadata', 'ai-rank-suite') }, ], }, { id: 'site', label: __('Your site', 'ai-rank-suite'), subs: [ { id: 'general', label: __('General', 'ai-rank-suite') }, { id: 'social', label: __('Social accounts', 'ai-rank-suite') }, ], }, { id: 'indexing', label: __('Indexing', 'ai-rank-suite'), subs: [ { id: 'idx-types', label: __('Post Types', 'ai-rank-suite') }, { id: 'idx-archives', label: __('Archives', 'ai-rank-suite') }, { id: 'idx-taxonomies', label: __('Taxonomies', 'ai-rank-suite') }, ], }, { id: 'google', label: __('Google', 'ai-rank-suite'), subs: [{ id: 'google-connect', label: __('Search Console & Analytics', 'ai-rank-suite') }], }, { id: 'advanced', label: __('Advanced options', 'ai-rank-suite'), subs: [ { id: 'adv', label: __('Advanced', 'ai-rank-suite') }, { id: 'metabox', label: __('SEO Metabox', 'ai-rank-suite') }, ], }, { id: 'ready', label: __('Ready!', 'ai-rank-suite'), subs: [], }, ], [] ); // Flat list of positions, so next/back are one index step. const FLAT = useMemo(() => { const out = []; GROUPS.forEach((g, gi) => { if (!g.subs.length) { out.push({ gi, si: -1, group: g, sub: null }); return; } g.subs.forEach((s, si) => out.push({ gi, si, group: g, sub: s })); }); return out; }, [GROUPS]); const [pos, setPos] = useState(0); const [busy, setBusy] = useState(false); const [error, setError] = useState(null); const current = FLAT[pos]; // What this run actually configured — the Ready! card reads from this, // never from "the user clicked through". const [log, setLog] = useState({}); const note = (key, value) => setLog((l) => ({ ...l, [key]: value })); const goto = (i) => { setError(null); setPos(Math.max(0, Math.min(FLAT.length - 1, i))); }; const next = () => goto(pos + 1); const back = () => goto(pos - 1); const guard = async (fn) => { setBusy(true); setError(null); try { await fn(); } catch (e) { setError(e.message); } finally { setBusy(false); } }; /* -------------------------------------------------------------- */ /* Step state */ /* -------------------------------------------------------------- */ // Import configuration (settings JSON from another install). const [configFile, setConfigFile] = useState(null); // {name, payload} const [configDone, setConfigDone] = useState(null); // {applied, skipped} const [dragOver, setDragOver] = useState(false); // Import metadata (migrate from another SEO plugin). const [sources, setSources] = useState(null); const [sourceChoice, setSourceChoice] = useState(null); const [migrated, setMigrated] = useState(null); // {label, total, redirects} // Your site. const [seo, setSeo] = useState(null); // /settings/seo payload const [schema, setSchema] = useState(null); // /settings/schema payload const [socialCfg, setSocialCfg] = useState(null); // /settings/social payload const [titleParts, setTitleParts] = useState([]); const [altTitle, setAltTitle] = useState(''); const [orgType, setOrgType] = useState('Organization'); const [profiles, setProfiles] = useState({}); const [extraAccounts, setExtraAccounts] = useState(''); // Indexing. const [noindexTypes, setNoindexTypes] = useState([]); const [noindexTaxes, setNoindexTaxes] = useState([]); const [dateNoindex, setDateNoindex] = useState(true); const [authorNoindex, setAuthorNoindex] = useState(false); // Advanced. const [attachRedirect, setAttachRedirect] = useState(true); const [emptyTerms, setEmptyTerms] = useState(true); const [imageSeo, setImageSeo] = useState(null); const [autoAlt, setAutoAlt] = useState(true); const [editorCfg, setEditorCfg] = useState(null); const [mbEnabled, setMbEnabled] = useState(true); const [mbPosition, setMbPosition] = useState('normal'); const [mbTypes, setMbTypes] = useState(null); // null = all // Google: one click connects Search Console and Analytics, and the // matching accounts are picked automatically after the sign-in. const [gsc, setGsc] = useState(null); const [gscPicked, setGscPicked] = useState(null); const [gscBusy, setGscBusy] = useState(false); // Ready! const [status, setStatus] = useState(null); useEffect(() => { api.get('/import/sources') .then((r) => { const list = r.sources || []; setSources(list); const detected = list.find((s) => s.active || s.posts > 0 || s.terms > 0); if (detected) setSourceChoice(detected.id); }) .catch(() => setSources([])); api.get('/settings/seo') .then((r) => { setSeo(r); setTitleParts(partsFromTemplate(r.settings.home_title)); setNoindexTypes((r.settings.noindex_types || []).slice()); setNoindexTaxes((r.settings.noindex_taxonomies || []).slice()); setDateNoindex(!!r.settings.date_noindex); setAuthorNoindex(!!r.settings.author_noindex); setAttachRedirect(!!r.settings.attachment_redirect); setEmptyTerms(!!r.settings.noindex_empty_terms); }) .catch(() => setSeo({ settings: {}, post_types: [], taxonomies: [] })); api.get('/settings/schema') .then((r) => { setSchema(r); setOrgType(r.settings.org_type || 'Organization'); setAltTitle(r.settings.identity?.alt_name || ''); }) .catch(() => setSchema(null)); api.get('/settings/social') .then((r) => { setSocialCfg(r); setProfiles({ ...(r.settings.profiles || {}) }); }) .catch(() => setSocialCfg(null)); api.get('/settings/image-seo') .then((r) => { setImageSeo(r); setAutoAlt(!!r.settings.auto_alt); }) .catch(() => setImageSeo(null)); api.get('/settings/editor') .then((r) => { setEditorCfg(r); setMbEnabled(!!r.settings.metabox_enabled); setMbPosition(r.settings.metabox_position || 'normal'); setMbTypes((r.settings.metabox_types || []).length ? r.settings.metabox_types.slice() : null); }) .catch(() => setEditorCfg(null)); api.get('/setup/status') .then(setStatus) .catch(() => setStatus({})); api.get('/gsc/status') .then(setGsc) .catch(() => setGsc(null)); }, []); const connectGoogle = async () => { setGscBusy(true); try { // The one-click path first; a build without the connect service // falls back to the Search Console screen and its manual setup. const r = await api.get('/gsc/signin-url'); window.location.href = r.url; } catch (e) { window.location.hash = '/search-console'; } }; const autoPickGoogle = async () => { setGscBusy(true); try { const picked = await api.post('/gsc/auto-configure', {}); setGscPicked(picked); } catch (e) { setGscPicked({ property: '', ga4_property: '', ga4_measurement: '' }); } setGscBusy(false); }; const resolveTemplate = (template) => String(template || '') .replace(/%sitename%/g, env.siteName || '') .replace(/%sep%/g, seo?.settings?.separator || '–') .replace(/%tagline%/g, env.tagline || '') .replace(/%currentyear%/g, String(new Date().getFullYear())) .replace(/\s{2,}/g, ' ') .trim(); /* -------------------------------------------------------------- */ /* Actions */ /* -------------------------------------------------------------- */ const finish = (thenAi = false) => guard(async () => { await api.post('/core/onboarding', { done: true }); onDone(); if (thenAi) window.location.hash = '/ai-wizard'; }); const readConfigFile = (file) => { setError(null); setConfigDone(null); const reader = new FileReader(); reader.onload = () => { try { const payload = JSON.parse(String(reader.result)); if (payload?.format !== 'ai-rank-suite/1') { setConfigFile(null); setError(__('This file is not an AI Rank Suite settings export.', 'ai-rank-suite')); return; } setConfigFile({ name: file.name, payload }); } catch (e) { setConfigFile(null); setError(__('This file is not valid JSON.', 'ai-rank-suite')); } }; reader.readAsText(file); }; const runConfigImport = () => guard(async () => { const r = await api.post('/settings/import', { payload: configFile.payload }); setConfigDone(r); note('config', sprintf(_n('%d settings group applied from your export file', '%d settings groups applied from your export file', r.applied, 'ai-rank-suite'), r.applied)); }); const runMetaImport = () => guard(async () => { // The same job path the Import screen drives (start + tick until // done): keyset paging, kept-counts and the undo journal — the // wizard was the last caller of the legacy synchronous /import/run // loop (audit: legacy import path). The tick loop is bounded so a // server that stops making progress ends the wizard, not hangs it. let s = await api.post('/import/start', { source: sourceChoice, mode: 'fill', parts: ['posts', 'terms', 'redirects'], }); for (let i = 0; i < 600 && s && s.state === 'running'; i++) { s = await api.post('/import/tick', {}); } const c = (s && s.counts) || {}; const imported = (c.posts ?? 0) + (c.terms ?? 0); const redirects = c.redirects ?? 0; const label = (sources || []).find((s2) => s2.id === sourceChoice)?.label || sourceChoice; setMigrated({ label, total: imported, redirects }); if (imported > 0) { note('meta', sprintf(_n('%1$d page migrated from %2$s', '%1$d pages migrated from %2$s', imported, 'ai-rank-suite'), imported, label)); } }); const saveGeneral = () => guard(async () => { const template = templateFromParts(titleParts); await api.put('/settings/seo', { home_title: template || '%sitename% %sep% %tagline%' }); if (schema) { await api.put('/settings/schema', { org_type: orgType, identity: { ...(schema.settings.identity || {}), alt_name: altTitle.trim() }, }); } note('general', __('Home title and site identity are configured', 'ai-rank-suite')); next(); }); const saveSocial = () => guard(async () => { const clean = {}; Object.entries(profiles).forEach(([k, v]) => { const url = String(v || '').trim(); if (url) clean[k] = url; }); // The free-text lines: recognised hosts become profiles, everything // else lands in the Organization's sameAs — nothing typed is lost. const rest = []; extraAccounts .split('\n') .map((l) => l.trim()) .filter(Boolean) .forEach((url) => { if (/tiktok\.com/i.test(url) && !clean.tiktok) clean.tiktok = url; else if (/wikipedia\.org/i.test(url) && !clean.wikipedia) clean.wikipedia = url; else rest.push(url); }); const payload = { profiles: clean }; // The X handle feeds twitter:site; the Facebook page feeds // article:publisher — both derived, neither asked twice. const xMatch = String(clean.x || '').match(/(?:x|twitter)\.com\/@?([A-Za-z0-9_]{2,})/); if (xMatch) payload.tw_site = '@' + xMatch[1]; if (clean.facebook) payload.fb_page = clean.facebook; await api.put('/settings/social', payload); if (rest.length && schema) { const existing = (schema.settings.identity?.same_as || []).map(String); await api.put('/settings/schema', { identity: { ...(schema.settings.identity || {}), same_as: [...new Set([...existing, ...rest])] }, }); } const count = Object.keys(clean).length + rest.length; if (count > 0) { note('social', sprintf(_n('%d social profile linked for the Knowledge Graph', '%d social profiles linked for the Knowledge Graph', count, 'ai-rank-suite'), count)); } next(); }); const saveIndexTypes = () => guard(async () => { await api.put('/settings/seo', { noindex_types: noindexTypes }); next(); }); const saveIndexArchives = () => guard(async () => { await api.put('/settings/seo', { date_noindex: dateNoindex, author_noindex: authorNoindex }); next(); }); const saveIndexTaxonomies = () => guard(async () => { await api.put('/settings/seo', { noindex_taxonomies: noindexTaxes }); const parts = []; if (noindexTypes.length) parts.push(sprintf(_n('%d post type', '%d post types', noindexTypes.length, 'ai-rank-suite'), noindexTypes.length)); if (noindexTaxes.length) parts.push(sprintf(_n('%d taxonomy', '%d taxonomies', noindexTaxes.length, 'ai-rank-suite'), noindexTaxes.length)); note( 'indexing', parts.length ? sprintf(__('Indexing rules set — %s excluded from search results', 'ai-rank-suite'), parts.join(', ')) : __('Indexing rules reviewed for post types, archives and taxonomies', 'ai-rank-suite') ); next(); }); const saveAdvanced = () => guard(async () => { await api.put('/settings/seo', { attachment_redirect: attachRedirect, noindex_empty_terms: emptyTerms }); if (imageSeo) { await api.put('/settings/image-seo', { auto_alt: autoAlt }); } note('advanced', __('Advanced options set — attachments, image alt texts, empty terms', 'ai-rank-suite')); next(); }); const saveMetabox = () => guard(async () => { if (editorCfg) { await api.put('/settings/editor', { metabox_enabled: mbEnabled, metabox_position: mbPosition, metabox_types: mbTypes === null ? [] : mbTypes, }); note('metabox', mbEnabled ? __('The SEO metabox is active in the editor', 'ai-rank-suite') : __('The SEO metabox is switched off', 'ai-rank-suite')); } next(); }); /* -------------------------------------------------------------- */ /* Rail */ /* -------------------------------------------------------------- */ const rail = ( ); /* -------------------------------------------------------------- */ /* Cards */ /* -------------------------------------------------------------- */ const backBtn = ( ); const saveContinue = (onClick) => ( ); let card = null; const stepId = current.sub ? current.sub.id : current.group.id; const home = String(env.homeUrl || '').replace(/\/$/, ''); if (stepId === 'start') { card = ( } >

{__('AI assistants answer questions directly instead of showing links. The sites they quote are the sites they can read, understand and verify — that is exactly what this setup makes yours.', 'ai-rank-suite')}

{__('Why this wizard exists', 'ai-rank-suite')}
{__('Generative engine optimization, done once and done right', 'ai-rank-suite')}
{[ [ '77', __('structured data types, emitted automatically', 'ai-rank-suite'), , ], [ '31', __('AI crawlers under your control', 'ai-rank-suite'), , ], [ '6', __('AI engines tracked for mentions of you', 'ai-rank-suite'), , ], ].map(([n, label, icon]) => (
{icon}
{n}
{label}
))}
{__('Connect an AI engine after setup', 'ai-rank-suite')}
{__('Bring an OpenAI, Anthropic or Google key and the suite writes meta descriptions, answers FAQs and simulates AI answers about your site. The last step offers it.', 'ai-rank-suite')}
); } if (stepId === 'import-config') { card = ( {backBtn} } >
{ e.preventDefault(); setDragOver(true); }} onDragLeave={() => setDragOver(false)} onDrop={(e) => { e.preventDefault(); setDragOver(false); const f = e.dataTransfer.files?.[0]; if (f) readConfigFile(f); }} >
{__('Drag and drop your configuration file here', 'ai-rank-suite')}
{__('JSON file only — the one Settings → Export writes.', 'ai-rank-suite')}
{__('or select it from your computer:', 'ai-rank-suite')}
{ const f = e.target.files?.[0]; if (f) readConfigFile(f); }} /> {configFile && !configDone && (
{sprintf(__('Ready to import: %s', 'ai-rank-suite'), configFile.name)}
)}
{configDone ? ( {sprintf( _n('%d settings group applied. Continue to review the rest, or skip ahead — your configuration is live.', '%d settings groups applied. Continue to review the rest, or skip ahead — your configuration is live.', configDone.applied, 'ai-rank-suite'), configDone.applied )} ) : (

{__('Importing replaces your current settings (titles, llms.txt, sitemap, schema, advanced options…). Post and term metadata are not affected. API keys and licenses never travel in export files.', 'ai-rank-suite')}

)}
); } if (stepId === 'import-meta') { const detected = (s) => s.active || s.posts > 0 || s.terms > 0 || s.redirects > 0 || s.settings; card = ( {backBtn} } > {sources === null && (
)} {sources !== null && (
{sources.map((s) => ( ))}
)} {sources !== null && !sources.some(detected) && (

{__('No other SEO plugin left data on this site — nothing to migrate. Skip ahead.', 'ai-rank-suite')}

)} {migrated && ( 0 ? 'good' : 'info'}> {migrated.total > 0 ? (migrated.redirects > 0 ? sprintf(_n('Migrated %1$d page and %2$d redirects from %3$s.', 'Migrated %1$d pages and %2$d redirects from %3$s.', migrated.total, 'ai-rank-suite'), migrated.total, migrated.redirects, migrated.label) : sprintf(_n('Migrated %1$d page from %2$s.', 'Migrated %1$d pages from %2$s.', migrated.total, 'ai-rank-suite'), migrated.total, migrated.label)) : __('Nothing left to migrate — every page that had data already carries it here.', 'ai-rank-suite')} )} {migrated && migrated.total > 0 && (

{__('Once everything looks right, deactivate the old plugin so only one of them writes your SEO tags.', 'ai-rank-suite')}

)}
); } if (stepId === 'general') { const typeGroups = schema?.types && typeof schema.types === 'object' ? schema.types : null; card = ( {backBtn} {saveContinue(saveGeneral)} } > {__('Site title', 'ai-rank-suite')} {__('This template builds your home page title tag. Variables resolve live — the preview above is exactly what Google shows.', 'ai-rank-suite')} {__('Alternative site title', 'ai-rank-suite')} setAltTitle(e.target.value)} placeholder={__('e.g. a common acronym or short name', 'ai-rank-suite')} style={{ width: '100%', boxSizing: 'border-box' }} /> {__('The alternate name of the website — for example a commonly recognized acronym or shorter name. It becomes the alternateName in your structured data.', 'ai-rank-suite')} {__('Person or organization', 'ai-rank-suite')} {__('Choose "Person / sole trader" for a personal site, or the closest organization type for a company — it decides whether your Knowledge Graph entity is a Person or an Organization.', 'ai-rank-suite')} ); } if (stepId === 'social') { const FIELDS = [ ['facebook', 'Facebook', 'https://facebook.com/your-page'], ['x', 'X', 'https://x.com/your-handle'], ['pinterest', 'Pinterest', 'https://pinterest.com/your-profile'], ['instagram', 'Instagram', 'https://instagram.com/your-profile'], ['youtube', 'YouTube', 'https://youtube.com/@your-channel'], ['linkedin', 'LinkedIn', 'https://linkedin.com/company/your-page'], ]; card = ( {backBtn} {saveContinue(saveSocial)} } > {FIELDS.map(([id, label, placeholder]) => (
{label}
{SOCIAL_MARKS[id]} setProfiles({ ...profiles, [id]: e.target.value })} placeholder={placeholder} style={{ flex: 1 }} />
))} {__('Additional accounts', 'ai-rank-suite')}