import { useState, useEffect, useRef, useCallback } from 'react'; import { useLanguage } from '../i18n/LanguageContext'; import { radius } from '../styles/theme'; import { getFeedSection, deleteFeedPost, type FeedPostResponse } from '../api'; import FeedPostComposer from './FeedPostComposer'; import ImageLightbox from './ImageLightbox'; export type FeedSection = 'news' | 'partners' | 'contacts' | 'apps'; interface FeedModalProps { isOpen: boolean; onClose: () => void; section: FeedSection; /** Флаг админа — для админ-строки ввода */ isAdmin?: boolean; } type FeedPost = FeedPostResponse; const SECTION_CONFIG: Record = { news: { icon: '📢', titleKey: 'carouselNews', accent: '#E8B93F' }, partners: { icon: '💼', titleKey: 'carouselPartners', accent: '#2ECC71' }, contacts: { icon: '📇', titleKey: 'carouselContacts', accent: '#8B5CF6' }, apps: { icon: '📲', titleKey: 'carouselApps', accent: '#4FA9E8' }, }; // 🔧 URL поддержки (единый аккаунт для заявок) const SUPPORT_URL = 'https://t.me/fwpl_support'; // 🔧 API base для склейки относительных URL картинок (fallback для старых постов) const API_BASE = 'https://api.filwordspl.com'; // 🔧 Внутренний отступ карточки поста (текстовый блок под картинкой) const POST_PADDING = '16px'; const FeedModal: React.FC = ({ isOpen, onClose, section, isAdmin = false }) => { const { t, language } = useLanguage(); const [posts, setPosts] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); const scrollRef = useRef(null); const isMountedRef = useRef(true); // 🔧 ФИКС (23.09.2026): feed_modal_race_on_section_change — счётчик запросов, // чтобы старый ответ не перезаписал новый при быстрой смене секции. const requestIdRef = useRef(0); // 🔧 Шаг 6: состояния админ-режима const [showComposer, setShowComposer] = useState(false); const [editingPost, setEditingPost] = useState(null); const [deletingPost, setDeletingPost] = useState(null); const [isDeleting, setIsDeleting] = useState(false); const [deleteError, setDeleteError] = useState(null); // 🔧 Лайтбокс: какие картинки открыть + с какого индекса const [lightboxOpen, setLightboxOpen] = useState(false); const [lightboxImages, setLightboxImages] = useState([]); const [lightboxIndex, setLightboxIndex] = useState(0); const config = SECTION_CONFIG[section]; const textColor = '#1A1A2E'; const subColor = '#6B7280'; const cardBg = 'rgba(255,255,255,0.55)'; const glass = (extra: React.CSSProperties = {}): React.CSSProperties => ({ background: cardBg, backdropFilter: 'blur(24px) saturate(180%)', WebkitBackdropFilter: 'blur(24px) saturate(180%)', border: '1px solid rgba(255,255,255,0.7)', boxShadow: '0 8px 32px rgba(31,38,73,0.10), inset 0 1px 0 rgba(255,255,255,0.85)', ...extra, }); // 🔧 Утилита: превращает относительный путь в полный URL const fullImageUrl = (path: string): string => path.startsWith('http') ? path : `${API_BASE}${path}`; // 🔧 ФИКС (24.09.2026): feed_modal_javascript_url_xss — // валидация URL. Разрешаем только http(s) и tg://, отсекаем javascript: и data:. const safeUrl = (url: string | null | undefined): string | null => { if (!url) return null; const trimmed = url.trim(); const lower = trimmed.toLowerCase(); // Разрешаем http, https, tg, mailto, tel if ( lower.startsWith('http://') || lower.startsWith('https://') || lower.startsWith('tg://') || lower.startsWith('mailto:') || lower.startsWith('tel:') ) { return trimmed; } // Блокируем всё остальное (javascript:, data:, vbscript: и т.д.) return null; }; const loadFeed = useCallback(() => { setLoading(true); setError(null); // 🔧 ФИКС (23.09.2026): feed_modal_race_on_section_change const currentRequestId = ++requestIdRef.current; getFeedSection(section, language) .then((data) => { // 🔧 Игнорируем устаревшие ответы if (!isMountedRef.current || currentRequestId !== requestIdRef.current) return; setPosts(data.posts || []); }) .catch((e) => { if (!isMountedRef.current || currentRequestId !== requestIdRef.current) return; console.error('Failed to load feed:', e); setError('Failed to load feed'); setPosts([]); }) .finally(() => { if (!isMountedRef.current || currentRequestId !== requestIdRef.current) return; setLoading(false); }); }, [section, language]); useEffect(() => { if (!isOpen) return; isMountedRef.current = true; loadFeed(); return () => { isMountedRef.current = false; }; }, [isOpen, loadFeed]); // Скролл вверх при открытии useEffect(() => { if (isOpen && scrollRef.current) { scrollRef.current.scrollTop = 0; } }, [isOpen, section]); // Escape для закрытия (только если не открыт composer/lightbox/delete) useEffect(() => { if (!isOpen) return; const handleKey = (e: KeyboardEvent) => { if (e.key === 'Escape' && !showComposer && !deletingPost && !lightboxOpen) onClose(); }; window.addEventListener('keydown', handleKey); return () => window.removeEventListener('keydown', handleKey); }, [isOpen, onClose, showComposer, deletingPost, lightboxOpen]); // ============ Обработчики админа ============ const handleCreate = () => { setEditingPost(null); setShowComposer(true); }; const handleEdit = (post: FeedPost) => { setEditingPost(post); setShowComposer(true); }; const handleDeleteConfirm = async () => { if (!deletingPost) return; setIsDeleting(true); setDeleteError(null); try { await deleteFeedPost(deletingPost.id); setDeletingPost(null); loadFeed(); } catch (e: any) { const realMessage = e?.message || String(e); setDeleteError(realMessage); console.error('[handleDeleteConfirm] FAILED', realMessage); } finally { setIsDeleting(false); } }; const handleComposerSuccess = () => { loadFeed(); }; // ============ Открытие лайтбокса ============ const openLightbox = (images: string[], startIndex: number = 0) => { setLightboxImages(images.map(fullImageUrl)); setLightboxIndex(startIndex); setLightboxOpen(true); }; // ============ Автолинк ============ const renderTextWithLinks = (text: string) => { const linkRegex = /(https?:\/\/[^\s]+)/g; const phoneRegex = /(\+[\d\s\-()]{7,})/g; type Match = { start: number; end: number; text: string; href: string; type: 'link' | 'phone' }; const matches: Match[] = []; let m: RegExpExecArray | null; const linkRegexGlobal = new RegExp(linkRegex.source, 'g'); while ((m = linkRegexGlobal.exec(text)) !== null) { matches.push({ start: m.index, end: m.index + m[0].length, text: m[0], href: m[0], type: 'link', }); } const phoneRegexGlobal = new RegExp(phoneRegex.source, 'g'); while ((m = phoneRegexGlobal.exec(text)) !== null) { const overlaps = matches.some( (existing) => m!.index < existing.end && m!.index + m![0].length > existing.start ); if (!overlaps) { matches.push({ start: m.index, end: m.index + m[0].length, text: m[0], href: `tel:${m[0].replace(/[\s\-()]/g, '')}`, type: 'phone', }); } } matches.sort((a, b) => a.start - b.start); const result: React.ReactNode[] = []; let lastIndex = 0; matches.forEach((match, i) => { if (match.start > lastIndex) { result.push(text.slice(lastIndex, match.start)); } result.push( e.stopPropagation()} > {match.text} ); lastIndex = match.end; }); if (lastIndex < text.length) { result.push(text.slice(lastIndex)); } return result; }; const formatDate = (iso: string | null): string => { if (!iso) return ''; try { const date = new Date(iso); const locales: Record = { pl: 'pl-PL', ru: 'ru-RU', uk: 'uk-UA', en: 'en-US', }; return date.toLocaleDateString(locales[language] || 'en-US', { day: 'numeric', month: 'short', year: 'numeric', }); } catch { return iso; } }; const formatExpires = (iso: string | null | undefined): string | null => { if (!iso) return null; try { const date = new Date(iso); const locales: Record = { pl: 'pl-PL', ru: 'ru-RU', uk: 'uk-UA', en: 'en-US', }; return date.toLocaleDateString(locales[language] || 'en-US', { day: 'numeric', month: 'short', }); } catch { return null; } }; if (!isOpen) return null; const showPartnersBanner = section === 'partners'; return ( <>
{ if (e.target === e.currentTarget) onClose(); }} >
e.stopPropagation()} style={{ ...glass({ borderRadius: radius.lg, padding: '20px', width: '100%', maxWidth: '440px', height: '85vh', maxHeight: '720px', display: 'flex', flexDirection: 'column', boxShadow: '0 24px 60px rgba(31,38,73,0.25), inset 0 1px 0 rgba(255,255,255,0.85)', }), animation: 'feedModalSlideUp 0.3s ease', }} > {/* ============ Шапка ============ */}

{config.icon} {t(config.titleKey)}

{/* ============ Баннер «По вопросам рекламы» (только Партнёры) ============ */} {showPartnersBanner && (
window.open(SUPPORT_URL, '_blank')} style={{ ...glass({ padding: '14px 16px', borderRadius: radius.md, marginBottom: '12px', }), border: `1px solid ${config.accent}40`, background: `${config.accent}10`, cursor: 'pointer', display: 'flex', alignItems: 'center', gap: '12px', flexShrink: 0, transition: 'all 0.2s ease', }} onTouchStart={(e) => { e.currentTarget.style.transform = 'scale(0.98)'; }} onTouchEnd={(e) => { e.currentTarget.style.transform = 'scale(1)'; }} > 📩
{t('feedPartnersBannerTitle') || 'По вопросам рекламы'}
{t('feedPartnersBannerSubtitle') || 'Написать нам →'}
)} {/* ============ Лента постов ============ */}
{loading ? (
{t('loading')}
) : error ? (
⚠️
{t('feedError') || 'Не удалось загрузить. Попробуйте ещё раз.'}
) : posts.length === 0 ? (
{config.icon}
{t('feedEmpty') || 'Пока нет постов'}
) : ( posts.map((post, index) => { const expiresLabel = formatExpires(post.expiresAt); const hasImages = post.images.length > 0; return (
{/* ============ КАРТИНКА (всегда одна на превью, edge-to-edge) ============ */} {/* 🔧 ФИКС (18.09.2026): на посте видна ТОЛЬКО первая картинка. По клику открывается лайтбокс со ВСЕМИ картинками поста — там можно свайпать влево/вправо (ImageLightbox). */} {hasImages && (
{ e.stopPropagation(); openLightbox(post.images, 0); }} style={{ position: 'relative', width: '100%', aspectRatio: '16 / 9', background: '#f0f0f5', cursor: 'pointer', borderTopLeftRadius: radius.md, borderTopRightRadius: radius.md, overflow: 'hidden', transition: 'transform 0.15s ease', }} onTouchStart={(e) => { e.currentTarget.style.transform = 'scale(0.99)'; }} onTouchEnd={(e) => { e.currentTarget.style.transform = 'scale(1)'; }} > {/* Всегда рендерим ТОЛЬКО первую картинку как превью */} { (e.currentTarget as HTMLImageElement).style.display = 'none'; }} style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block', userSelect: 'none', WebkitUserSelect: 'none', }} /> {/* 🔧 Бейдж «📷 N» — если картинок больше 1. Показывает юзеру, что внутри ещё есть фото. */} {post.images.length > 1 && (
📷 {post.images.length}
)}
)} {/* ============ ТЕКСТОВЫЙ БЛОК (с padding) ============ */}
{/* Бейдж «Закреплено» */} {post.isPinned && (
📌
)} {/* 🔧 Шаг 6: админ-иконки ✏️ / 🗑️ */} {isAdmin && (
)} {/* Заголовок */}
{post.title}
{/* Текст поста */}
{renderTextWithLinks(post.body)}
{/* Ссылка */} {post.linkUrl && safeUrl(post.linkUrl) && ( e.stopPropagation()} style={{ display: 'inline-flex', alignItems: 'center', gap: '6px', padding: '8px 14px', borderRadius: radius.sm, background: `${config.accent}15`, border: `1px solid ${config.accent}40`, color: config.accent, fontSize: '13px', fontWeight: 700, textDecoration: 'none', marginBottom: '8px', transition: 'all 0.2s ease', }} onTouchStart={(e) => { e.currentTarget.style.transform = 'scale(0.96)'; }} onTouchEnd={(e) => { e.currentTarget.style.transform = 'scale(1)'; }} > 🔗 {t('feedOpenLink') || 'Открыть ссылку'} )} {/* Telegram-ссылка */} {post.telegramUrl && safeUrl(post.telegramUrl) && ( e.stopPropagation()} style={{ display: 'inline-flex', alignItems: 'center', gap: '6px', padding: '8px 14px', borderRadius: radius.sm, background: `#0088cc15`, border: `1px solid #0088cc40`, color: '#0088cc', fontSize: '13px', fontWeight: 700, textDecoration: 'none', marginBottom: '8px', marginLeft: post.linkUrl ? '8px' : '0', transition: 'all 0.2s ease', }} onTouchStart={(e) => { e.currentTarget.style.transform = 'scale(0.96)'; }} onTouchEnd={(e) => { e.currentTarget.style.transform = 'scale(1)'; }} > ✈️ Telegram )} {/* Футер: дата + таймер */}
🕐 {formatDate(post.createdAt)} {expiresLabel && ( ⏰ до {expiresLabel} )}
); }) )}
{/* ============ Админ-кнопка «Написать пост» ============ */} {isAdmin && (
)}
{/* ============ Composer (создание / редактирование) ============ */} { setShowComposer(false); setEditingPost(null); }} onSuccess={handleComposerSuccess} section={section} editingPost={editingPost} /> {/* ============ 🔧 Лайтбокс для просмотра картинок ============ */} setLightboxOpen(false)} /> {/* ============ Модалка подтверждения удаления ============ */} {deletingPost && (
{ if (e.target === e.currentTarget && !isDeleting) setDeletingPost(null); }} >
e.stopPropagation()} style={{ ...glass({ borderRadius: radius.lg, padding: '24px', width: '100%', maxWidth: '360px', textAlign: 'center', }), }} >
🗑️

{t('feedAdminDeleteConfirm') || 'Удалить этот пост?'}

{deletingPost.title}
{deleteError && (
⚠️ {deleteError}
)}
)} ); }; export default FeedModal;