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

/**
 * Detail for the `optimizedescsingle` / `propose` intervention (type selection).
 *
 * Flavio proposes a new meta description; the user edits it inline and Publishes,
 * or Skips for now. Sibling of OptimizeTitle on the same reusable TextProposal.
 * Contract userResponse: { choice:"apply", confirmed_description }.
 *
 * Options are [apply, dismiss], so Publish → `acknowledge` and Skip → `dismiss`.
 *
 * Length: recommended 120-155 (counter warns outside that range). Unlike titles,
 * there's no hard cap, since an over-long description is sub-optimal, not invalid.
 *
 * Defensive on metadata: every field is read with a fallback.
 */
const OptimizeDesc = ({
	intervention = {},
	interventionId,
	onBack,
	onResolved,
}) => {
	const m = intervention.metadata || {};
	const { pageLabel, pageUrl } = resolvePageRef(m);
	const rationale =
		m.rationale ||
		"This is what shows under your page title in Google's results.";

	return (
		<TextProposal
			interventionId={interventionId}
			onBack={onBack}
			onResolved={onResolved}
			heading="Approve your new meta description"
			subtitle={`${rationale} Edit it if you want, or publish as is.`}
			pageLabel={pageLabel}
			pageUrl={pageUrl}
			fieldLabel="Meta description"
			currentValue={m.current_description || ''}
			proposedValue={m.proposed_description || ''}
			multiline
			recommended={{ min: 120, max: 155 }}
			renderValue={(value) => (
				<CodeTag
					before={'<meta name="description" content="'}
					after={'">'}
					value={value}
				/>
			)}
			primaryLabel="Publish"
			secondaryLabel="Keep as is"
			primaryAction={(value) => ({
				status: 'acknowledge',
				userResponse: { choice: 'apply', confirmed_description: value },
			})}
			secondaryAction={() => ({
				status: 'dismiss',
				userResponse: { choice: 'dismiss' },
			})}
			footerNote="Google will pick up the change within a few days."
			primaryDoneText="Great. I'll publish your new description shortly."
			secondaryDoneText="No problem. I'll keep your current description."
		/>
	);
};

export default OptimizeDesc;
