import { useState, useRef, useEffect } from "react"; import { useTranslation } from "react-i18next"; import { useCityOptions } from "../hooks/useCityOptions"; /** * CityFilter — мультиселект городов с поиском и свободным вводом. * * @param {string[]} cities — доступные города (из /posts/cities) * @param {string[]} value — выбранные города * @param {(next: string[]) => void} onChange — изменение выбора */ export default function CityFilter({ cities, value, onChange }) { const { t } = useTranslation(); const [query, setQuery] = useState(""); const [open, setOpen] = useState(false); const rootRef = useRef(null); const inputRef = useRef(null); // Закрываем дропдаун при клике вне компонента useEffect(() => { if (!open) return; const onDocMouseDown = (e) => { if (rootRef.current && !rootRef.current.contains(e.target)) { setOpen(false); } }; document.addEventListener("mousedown", onDocMouseDown); return () => document.removeEventListener("mousedown", onDocMouseDown); }, [open]); const { options, typedCity } = useCityOptions(cities, value, query); const toggle = (city) => { if (value.includes(city)) { onChange(value.filter(c => c !== city)); } else { onChange([...value, city]); } setQuery(""); inputRef.current?.focus(); }; // Города нет в списке — объявлений там нет, но фильтр всё равно применяем: // лента покажет «В этом городе нет объявлений» const applyTyped = () => { onChange([...value, typedCity]); setQuery(""); setOpen(false); }; const handleKeyDown = (e) => { if (e.key === "Enter") { e.preventDefault(); if (typedCity) { applyTyped(); } else if (options.length) { toggle(options[0]); } } else if (e.key === "Backspace" && query === "" && value.length) { onChange(value.slice(0, -1)); } else if (e.key === "Escape") { setOpen(false); } }; return (