import DriftDecision from '@/features/interventions/detail/DriftDecision';
import CodeTag from '@/features/interventions/detail/CodeTag';
import { resolvePageRef } from '@/features/interventions/detail/pageRef';

/**
 * Detail for the `optimizetitlesingle` / `drift` intervention (type selection).
 *
 * The user changed the page title (and/or site name) after Flavio had set it;
 * the scanner noticed. We surface the conflicting field(s) and let the user pick
 * which version stands. Built on the shared DriftDecision.
 *
 * Contract metadata: `drift:{ title?:{current,expected}, site_name?:{current,expected} }`.
 * userResponse: { choice:"keep_current" | "revert_to_expected" }.
 *
 * Defensive on metadata: only fields actually present in `drift` are shown.
 */
const TitleDrift = ({ intervention = {}, interventionId, onBack, onResolved }) => {
	const m = intervention.metadata || {};
	const drift = m.drift || {};
	const { pageLabel, pageUrl } = resolvePageRef(m);

	const changes = [];
	if (drift.title) {
		changes.push({
			label: 'Page title',
			current: drift.title.current || '',
			expected: drift.title.expected || '',
			renderValue: (v) => <CodeTag tag="title" value={v} />,
		});
	}
	if (drift.site_name) {
		changes.push({
			label: 'Site name',
			current: drift.site_name.current || '',
			expected: drift.site_name.expected || '',
		});
	}

	const what = changes.length > 1 ? 'page title and site name' : 'page title';

	return (
		<DriftDecision
			interventionId={interventionId}
			onBack={onBack}
			onResolved={onResolved}
			heading="Your page title changed"
			subtitle={`You edited the ${what} after my last update. Tell me which version to keep going forward.`}
			pageLabel={pageLabel}
			pageUrl={pageUrl}
			changes={changes}
			keepDoneText="Got it. I'll keep your version and stop suggesting changes here."
			revertDoneText="Done. I'll restore my version shortly."
		/>
	);
};

export default TitleDrift;
