import DriftDecision from '@/features/interventions/detail/DriftDecision';
import CodeTag from '@/features/interventions/detail/CodeTag';
import { resolvePageRef } from '@/features/interventions/detail/pageRef';
import {
	notReflectedSteps,
	seoPluginName,
} from '@/features/interventions/detail/seoPlugin';

const FIELDS = {
	title: {
		label: 'Page title',
		noun: 'title',
		render: (v) => <CodeTag tag="title" value={v} />,
	},
	description: {
		label: 'Meta description',
		noun: 'meta description',
		render: (v) => (
			<CodeTag
				before={'<meta name="description" content="'}
				after={'">'}
				value={v}
			/>
		),
	},
};

/**
 * Detail for the `not_reflected` variant of `optimizetitlesingle` and
 * `optimizedescsingle` (type selection).
 *
 * Flavio saved the value in Yoast SEO or All in One SEO, but the next scan saw
 * something else on the page. Unlike `drift`, we don't assume the user changed
 * it: they may have edited it in the SEO plugin, or something else (another
 * plugin, the theme) may override it. Same choice and same userResponse as
 * drift, on the shared DriftDecision, plus where to look.
 *
 * Contract metadata: `seo_plugin:"yoast"|"aioseo"`, and `drift.title` or
 * `drift.description` as `{current, expected}`.
 * userResponse: { choice:"keep_current" | "revert_to_expected" }.
 */
const NotReflected = ({
	field,
	intervention = {},
	interventionId,
	onBack,
	onResolved,
}) => {
	const m = intervention.metadata || {};
	const config = FIELDS[field] || FIELDS.title;
	const pair = (m.drift || {})[field] || {};
	const { pageLabel, pageUrl } = resolvePageRef(m);
	const plugin = seoPluginName(m.seo_plugin) || 'your SEO plugin';
	const steps = notReflectedSteps(m.seo_plugin, field);

	return (
		<DriftDecision
			interventionId={interventionId}
			onBack={onBack}
			onResolved={onResolved}
			heading={`Your page shows a different ${config.noun}`}
			subtitle={`I saved your ${config.noun} in ${plugin}, but your page shows another one. You may have changed it there, or something else is overriding it. Tell me which version to keep.`}
			pageLabel={pageLabel}
			pageUrl={pageUrl}
			changes={[
				{
					label: config.label,
					current: pair.current || '',
					expected: pair.expected || '',
					renderValue: config.render,
				},
			]}
			help={{ title: 'Where to check', steps }}
			keepDoneText="Got it. I'll keep what your page shows and stop suggesting changes here."
			revertDoneText={`Done. I'll save my version in ${plugin} again shortly.`}
		/>
	);
};

export const TitleNotReflected = (props) => (
	<NotReflected field="title" {...props} />
);

export const DescNotReflected = (props) => (
	<NotReflected field="description" {...props} />
);
