import { useThemeVariations } from '@agent/hooks/useThemeVariations'; import { useVariationOverride } from '@agent/hooks/useVariationOverride'; import { useChatStore } from '@agent/state/chat'; import { useEffect, useMemo, useRef, useState } from '@wordpress/element'; import { __ } from '@wordpress/i18n'; export const SelectThemeVariation = ({ onConfirm, onCancel, onLoad }) => { const [css, setCss] = useState(''); const [selected, setSelected] = useState(null); const [duotoneTheme, setDuotoneTheme] = useState(null); const { undoChange } = useVariationOverride({ css, duotoneTheme }); const confirmed = useRef(false); useEffect(() => { return () => { if (!confirmed.current) undoChange(); }; }, []); const { variations, isLoading } = useThemeVariations(); const noVariations = !variations || variations.length === 0; const { addMessage, messages } = useChatStore(); const shuffled = useMemo( () => (variations ? variations.sort(() => Math.random() - 0.5) : []), [variations], ); const handleConfirm = () => { if (!selected) return; const variation = variations.find((v) => v.title === selected); if (!variation) { // translators: A chat message shown to the user when their selected color variation cannot be applied const content = __( 'We were unable to apply your selected colors. Please try again.', 'extendify-local', ); addMessage('message', { role: 'assistant', content, error: true }); onCancel(); return; } confirmed.current = true; onConfirm({ data: { variation }, shouldRefreshPage: true }); }; useEffect(() => { if (isLoading) return; onLoad(); }, [isLoading, onLoad]); useEffect(() => { if (isLoading || !noVariations) return; const timer = setTimeout(() => onCancel(), 100); // translators: A chat message shown to the user const content = __( 'We were unable to find any colors for your theme', 'extendify-local', ); const last = messages.at(-1)?.details?.content; if (content === last) return () => clearTimeout(timer); addMessage('message', { role: 'assistant', content, error: true }); return () => clearTimeout(timer); }, [addMessage, onCancel, noVariations, messages, isLoading]); if (isLoading) { return (