"use client"; import { useMemo } from "react"; import { AgeSelector } from "../AgeSelector"; import { ZodiacSelector } from "../ZodiacSelector"; import { EmailDomainSelector } from "../EmailDomainSelector"; import { ConditionTypeSelector } from "../ConditionTypeSelector"; import { UnleashConditionEditor } from "../UnleashConditionEditor"; import type { VariantConditionEditorProps } from "./types"; import type { BuilderScreen } from "@/lib/admin/builder/types"; import type { ListOptionDefinition } from "@/lib/funnel/types"; /** * Редактор условия для варианта экрана */ export function VariantConditionEditor({ condition, allScreens, onChange, }: VariantConditionEditorProps) { // Находим выбранный экран (может быть ID экрана или storageKey для zodiac) const selectedScreen = useMemo(() => { // Сначала ищем по ID экрана let screen = allScreens.find((s) => s.id === condition.screenId); if (screen) return screen; // Если не нашли, ищем date экран где storageKey === condition.screenId screen = allScreens.find((s) => { if (s.template === "date") { const dateScreen = s as BuilderScreen & { template: "date"; dateInput?: { zodiac?: { enabled?: boolean; storageKey?: string } } }; const zodiacSettings = dateScreen.dateInput?.zodiac; return zodiacSettings?.enabled && zodiacSettings.storageKey?.trim() === condition.screenId; } return false; }); return screen; }, [allScreens, condition.screenId]); // Определяем опции для условия (если это list экран) // Собираем опции из базового экрана + из всех вариантов const conditionOptions = useMemo(() => { if (!selectedScreen || selectedScreen.template !== "list") { return []; } const listScreen = selectedScreen as BuilderScreen & { template: "list"; list: { options: ListOptionDefinition[] }; variants?: Array<{ overrides?: { list?: { options?: ListOptionDefinition[] } } }>; }; // Начинаем с базовых опций const optionsMap = new Map(); listScreen.list.options.forEach(opt => { optionsMap.set(opt.id, opt); }); // Добавляем опции из всех вариантов if (listScreen.variants) { listScreen.variants.forEach(variant => { const variantOptions = variant.overrides?.list?.options; if (variantOptions) { variantOptions.forEach(opt => { // Проверяем что опция валидна (имеет id) if (opt && opt.id) { // Добавляем или переопределяем опцию optionsMap.set(opt.id, opt as ListOptionDefinition); } }); } }); } // Возвращаем все уникальные опции return Array.from(optionsMap.values()); }, [selectedScreen]); // Определяем, нужен ли специальный селектор const showZodiacSelector = useMemo(() => { if (!selectedScreen) return false; // Проверяем специальный zodiac экран if (selectedScreen.id === "zodiac-sign" || selectedScreen.id === "zodiac") { return true; } // Проверяем date экран с zodiac.enabled и storageKey === condition.screenId if (selectedScreen.template === "date") { const dateScreen = selectedScreen as BuilderScreen & { template: "date"; dateInput?: { zodiac?: { enabled?: boolean; storageKey?: string } } }; const zodiacSettings = dateScreen.dateInput?.zodiac; const storageKey = zodiacSettings?.storageKey?.trim(); // Показываем zodiac селектор если: // 1. zodiac включен // 2. storageKey совпадает с condition.screenId (т.е. пользователь выбрал этот storageKey) return zodiacSettings?.enabled === true && storageKey === condition.screenId; } return false; }, [selectedScreen, condition.screenId]); const showEmailSelector = selectedScreen?.id === "email"; const showAgeSelector = selectedScreen?.id === "age" || selectedScreen?.id === "crush-age" || selectedScreen?.id === "current-partner-age"; const conditionType = condition.conditionType ?? "options"; const isUnleashCondition = conditionType === "unleash"; // Обработчики для селекторов const handleToggleOption = (optionId: string) => { const currentIds = condition.optionIds || []; const nextIds = currentIds.includes(optionId) ? currentIds.filter((id) => id !== optionId) : [...currentIds, optionId]; onChange({ ...condition, optionIds: nextIds }); }; const handleAddCustomOption = (optionId: string) => { const currentIds = condition.optionIds || []; if (!currentIds.includes(optionId)) { onChange({ ...condition, optionIds: [...currentIds, optionId] }); } }; const handleConditionTypeChange = (newType: "options" | "values" | "unleash") => { onChange({ ...condition, conditionType: newType, // Очищаем поля при смене типа optionIds: newType === "unleash" ? undefined : condition.optionIds, values: newType === "unleash" ? undefined : condition.values, unleashFlag: newType === "unleash" ? condition.unleashFlag : undefined, unleashVariants: newType === "unleash" ? condition.unleashVariants : undefined, }); }; return (
{/* Тип условия */} {/* Unleash AB Test */} {isUnleashCondition ? ( ) : ( <> {/* Выбор экрана */}
{/* Оператор (только для list экранов с несколькими опциями) */} {conditionOptions.length > 1 && (
)} {/* Zodiac Selector */} {showZodiacSelector && (
)} {/* Email Domain Selector */} {showEmailSelector && (
)} {/* Age Selector */} {showAgeSelector && (
)} {/* Опции для обычных list экранов */} {!showZodiacSelector && !showEmailSelector && !showAgeSelector && conditionOptions.length > 0 && (
{conditionOptions.map((opt) => ( ))}
)} )}
); }