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

/**
 * Detail for the `optimizetitlesingle` / `propose` intervention (type selection).
 *
 * Flavio proposes a new page title; the user can edit it inline and Publish, or
 * Skip for now. Built on the reusable TextProposal (shared with meta description
 * and tagline). Contract userResponse: { choice:"apply", confirmed_title }.
 *
 * Options are [apply, dismiss], so Publish → `acknowledge` and Skip → `dismiss`.
 *
 * Title length: recommended 30-60, hard-blocked over 60 (matches the executor's
 * own bound, so we never round-trip an invalid value).
 *
 * Defensive on metadata: every field is read with a fallback. The "no SEO plugin"
 * notice shows when the payload reports `seo_plugin_detected === false`.
 */
const OptimizeTitle = ({
	intervention = {},
	interventionId,
	onBack,
	onResolved,
}) => {
	const m = intervention.metadata || {};
	const { pageLabel, pageUrl } = resolvePageRef(m);
	const rationale = m.rationale || 'I rewrote your page title to help it rank.';
	const noSeoPlugin = m.seo_plugin_detected === false;

	return (
		<TextProposal
			interventionId={interventionId}
			onBack={onBack}
			onResolved={onResolved}
			heading="Approve your new page title"
			subtitle={`${rationale} Edit it if you want, or publish as is.`}
			pageLabel={pageLabel}
			pageUrl={pageUrl}
			fieldLabel="Title"
			currentValue={m.current_title || ''}
			proposedValue={m.proposed_title || ''}
			recommended={{ min: 30, max: 60 }}
			maxLength={60}
			renderValue={(value) => <CodeTag tag="title" value={value} />}
			notice={
				noSeoPlugin
					? 'No SEO plugin was detected on your site. This change will be applied to the native post title and will also affect the title shown in menus, breadcrumbs, and archive listings.'
					: ''
			}
			primaryLabel="Publish"
			secondaryLabel="Keep as is"
			primaryAction={(value) => ({
				status: 'acknowledge',
				userResponse: { choice: 'apply', confirmed_title: value },
			})}
			secondaryAction={() => ({
				status: 'dismiss',
				userResponse: { choice: 'dismiss' },
			})}
			footerNote="Nothing goes live until you publish."
			primaryDoneText="Great. I'll publish your new title shortly."
			secondaryDoneText="No problem. I'll keep your current title."
		/>
	);
};

export default OptimizeTitle;
