import React, { useEffect, useState } from 'react';
import { __ } from '@wordpress/i18n';
import { api } from '../api';
import { Button, Badge, Notice, Segmented } from './ui';
import { IconSparkle } from './icons';
/**
* The per-page AI tools that used to be routing entries with no caller:
* passage rewrites, a schema proposal, alt text, internal links, translation.
*
* Same contract as the title/description card: every tool proposes, shows the
* receipt (model, tokens, cost), and only an explicit Apply writes — one item
* at a time, so a reviewer can take three of five rewrites and leave two.
* Content-changing applies keep a snapshot in the page's AI history for undo.
*/
const Receipt = ({ r }) =>
r && r.model ? (
{r.provider} · {r.model} · {(r.prompt_tokens || 0) + (r.completion_tokens || 0)} {__('tokens', 'ai-rank-suite')} · {r.cost} · {r.latency_ms} ms
) : null;
function useRun() {
const [busy, setBusy] = useState('');
const [error, setError] = useState(null);
const run = async (name, fn) => {
setBusy(name);
setError(null);
try {
return await fn();
} catch (e) {
setError(e.message);
return null;
} finally {
setBusy('');
}
};
return { busy, error, run, setError };
}
/* ---------- Rewrite ---------- */
function Rewrite({ postId, onServerEdit }) {
const { busy, error, run } = useRun();
const [data, setData] = useState(null);
const [focus, setFocus] = useState('');
const [drafts, setDrafts] = useState({});
const [applied, setApplied] = useState({});
const [canUndo, setCanUndo] = useState(false);
const propose = () =>
run('propose', async () => {
const r = await api.post(`/ai/rewrite/${postId}`, { focus });
setData(r);
setDrafts(Object.fromEntries((r.edits || []).map((e, i) => [i, e.rewritten])));
setApplied({});
});
const apply = (i) =>
run(`apply${i}`, async () => {
const e = data.edits[i];
await api.post(`/ai/rewrite/${postId}/apply`, { original: e.original, rewritten: drafts[i] });
setApplied((a) => ({ ...a, [i]: true }));
setCanUndo(true);
// The body of the page just changed, so the word count, the scores
// and every check are now about the previous version.
if (onServerEdit) onServerEdit();
});
const undo = () =>
run('undo', async () => {
await api.post(`/ai/rewrite/${postId}/undo`, {});
setCanUndo(false);
setApplied({});
if (onServerEdit) onServerEdit();
});
return (
{__('The AI picks the passages where a change most improves quotability or clarity and rewrites only those — no new facts, same language and register. Apply the ones you agree with; each apply is undoable.', 'ai-rank-suite')}
{__('The AI proposes the best-fitting schema type this plugin supports and fills only fields whose values appear on the page — never a price, rating or date it did not read. You review, then hand it to the schema editor.', 'ai-rank-suite')}
}
{Object.keys(fields).length === 0 ? (
{__('The page did not contain enough facts to fill any field. Add the details to the page, or fill the schema by hand.', 'ai-rank-suite')}
) : (
{__('One plain sentence per image that has none, from the page context and file name — written into the media library, so every page that uses the image gets it.', 'ai-rank-suite')}
{images.length === 0 && !data ? (
{done ? `${done} ${__('alt texts written.', 'ai-rank-suite')}` : __('Every media-library image on this page already has alt text.', 'ai-rank-suite')}
) : (
{images.length} {__('images without alt text', 'ai-rank-suite')}
);
}
/* ---------- Links ---------- */
function LinksTool({ postId, onServerEdit }) {
const { busy, error, run } = useRun();
const [data, setData] = useState(null);
const [applied, setApplied] = useState({});
const propose = () =>
run('propose', async () => {
setData(await api.post(`/ai/links/${postId}`, {}));
setApplied({});
});
const apply = (i) =>
run(`apply${i}`, async () => {
const l = data.links[i];
// The target travels as an id; the server builds the URL from it and
// checks it against the suggestion table.
await api.post(`/ai/links/${postId}/apply`, { anchor: l.anchor, target_id: l.target_id });
// A new internal link is a change to the body, same as a rewrite.
if (onServerEdit) onServerEdit();
setApplied((a) => ({ ...a, [i]: true }));
});
return (
{__('The link module finds candidates locally; the AI reads this page and picks which of them a reader would actually want, with natural anchor text from a sentence already on the page. Same language only.', 'ai-rank-suite')}
{error && {error}}
{data && data.links.length === 0 && {__('None of the candidates fit this page well enough.', 'ai-rank-suite')}}
{data &&
data.links.map((l, i) => (
{__('Translate this page’s SEO title and description for its counterpart in another language, keeping brand words and length limits. Copy the result into the translated page.', 'ai-rank-suite')}
{error && {error}}
{data && (
{data.from} → {data.to}
{data.title}
{data.description}
{onUse && (
)}
)}
);
}
/**
* `onServerEdit` — "this tool has already changed the page".
*
* Rewrite, Alt text and Links do not hand a draft back for the drawer to save;
* they POST an /apply that writes to the database there and then. Nothing told
* anybody, so the row in the list behind the drawer, its word count and its
* scores all went on describing the page as it was before the edit, and the
* drawer's own checks with them. The caller uses this to re-read the page.
*/
export default function AiTools({ postId, onSchema, onTranslate, onServerEdit }) {
const [tab, setTab] = useState('rewrite');
return (