Files
filwordspl-frontend/src/components/FeedPostComposer.tsx
T

1010 lines
38 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { useState, useRef, useEffect } from 'react';
import { useLanguage } from '../i18n/LanguageContext';
import { radius } from '../styles/theme';
import {
createFeedPost,
updateFeedPost,
uploadFeedImage,
translateFeedPreview,
type FeedSection,
type FeedPostResponse,
} from '../api';
interface FeedPostComposerProps {
isOpen: boolean;
onClose: () => void;
onSuccess: () => void;
section: FeedSection;
/** Если передан — режим редактирования. Если null — создание. */
editingPost: FeedPostResponse | null;
}
type SourceLang = 'pl' | 'ru' | 'uk' | 'en';
interface TranslationPreview {
title_pl: string; title_ru: string; title_uk: string; title_en: string;
body_pl: string; body_ru: string; body_uk: string; body_en: string;
}
/**
* 🔧 ФИКС (18.09.2026, вечер): новая архитектура загрузки картинок.
*
* Было: один <input type="file" multiple> — Telegram WebView (особенно iOS)
* часто отдавал меньше файлов, чем выбрал юзер. Реально выбираешь 3,
* до бэка долетает 1.
*
* Стало: ТРИ отдельных слота, каждый со своим <input type="file"> БЕЗ multiple.
* За раз выбирается ровно 1 картинка — WebView не может ничего
* «потерять». Так же работает на Kufar, Instagram Stories, Telegram.
*
* Слот хранит Blob (in-memory объект), а не File. Это гарантирует, что
* к моменту публикации байты доступны — WebView их не «съест».
*/
interface ImageSlot {
blob: Blob;
name: string;
type: string;
previewUrl: string;
}
/**
* 🔧 СЖАТИЕ (19.09.2026): уменьшает картинку до maxDimension по длинной стороне
* и жмёт в JPEG с итеративным давлением до maxBytes.
*
* Зачем: юзер грузит фото как есть — 3 × 4 МБ = 12 МБ с телефона. После сжатия
* 3 × ~500 КБ = 1.5 МБ. Фид грузится быстрее, трафик меньше, nginx не напрягается.
*
* Логика:
* 1. Открываем картинку через createImageBitmap с fallback на Image() —
* для старых WebView и HEIC.
* 2. Ресайзим до maxDimension (1600px по длинной стороне).
* 3. Жмём в JPEG: quality 0.85 → 0.75 → 0.65 → 0.55, пока не уложимся
* в maxBytes (2 МБ).
* 4. Если даже на 0.55 не влезли — режем ещё сильнее по размеру.
*
* Если что-то пошло не так (HEIC в старом WebView, canvas недоступен) —
* кидает ошибку. Вызывающий код ловит и использует оригинал.
*/
async function compressImage(
blob: Blob,
maxDimension = 1600,
maxBytes = 2 * 1024 * 1024,
): Promise<{ blob: Blob; width: number; height: number }> {
// 1. Открываем картинку — createImageBitmap с fallback на Image()
let bitmap: ImageBitmap | HTMLImageElement;
try {
bitmap = await createImageBitmap(blob);
} catch {
bitmap = await new Promise<HTMLImageElement>((resolve, reject) => {
const img = new Image();
img.onload = () => resolve(img);
img.onerror = () => reject(new Error('image load failed'));
img.src = URL.createObjectURL(blob);
});
}
const w0 = 'width' in bitmap ? bitmap.width : (bitmap as HTMLImageElement).naturalWidth;
const h0 = 'height' in bitmap ? bitmap.height : (bitmap as HTMLImageElement).naturalHeight;
if (!w0 || !h0) throw new Error('invalid image dimensions');
// 2. Целевые размеры
const scale = Math.min(1, maxDimension / Math.max(w0, h0));
const w = Math.round(w0 * scale);
const h = Math.round(h0 * scale);
// 3. Рисуем в canvas
const canvas = document.createElement('canvas');
canvas.width = w;
canvas.height = h;
const ctx = canvas.getContext('2d');
if (!ctx) throw new Error('canvas 2d context unavailable');
ctx.drawImage(bitmap as any, 0, 0, w, h);
// 4. Итеративное сжатие: 0.85 → 0.75 → 0.65 → 0.55
const qualities = [0.85, 0.75, 0.65, 0.55];
let resultBlob: Blob | null = null;
for (const q of qualities) {
const b = await new Promise<Blob | null>((resolve) =>
canvas.toBlob((blob) => resolve(blob), 'image/jpeg', q),
);
if (!b) continue;
resultBlob = b;
if (b.size <= maxBytes) break;
}
if (!resultBlob) throw new Error('canvas.toBlob failed');
// 5. Если даже на 0.55 не влезли — режем ещё сильнее по размеру
if (resultBlob.size > maxBytes) {
const ratio = Math.sqrt(maxBytes / resultBlob.size) * 0.95;
const w2 = Math.round(w * ratio);
const h2 = Math.round(h * ratio);
const canvas2 = document.createElement('canvas');
canvas2.width = w2;
canvas2.height = h2;
const ctx2 = canvas2.getContext('2d');
if (!ctx2) throw new Error('canvas 2d context unavailable');
ctx2.drawImage(bitmap as any, 0, 0, w2, h2);
const b2 = await new Promise<Blob | null>((resolve) =>
canvas2.toBlob((b) => resolve(b), 'image/jpeg', 0.7),
);
if (b2) resultBlob = b2;
}
// Освобождаем ImageBitmap
if ('close' in bitmap && typeof (bitmap as ImageBitmap).close === 'function') {
(bitmap as ImageBitmap).close();
}
return { blob: resultBlob, width: w, height: h };
}
const FeedPostComposer: React.FC<FeedPostComposerProps> = ({
isOpen,
onClose,
onSuccess,
section,
editingPost,
}) => {
const { t, language } = useLanguage();
const isEditing = editingPost !== null;
// ============ Состояние формы ============
const [title, setTitle] = useState('');
const [body, setBody] = useState('');
const [linkUrl, setLinkUrl] = useState('');
const [telegramUrl, setTelegramUrl] = useState('');
const [isPinned, setIsPinned] = useState(false);
const [expiresAt, setExpiresAt] = useState('');
const [sourceLang, setSourceLang] = useState<SourceLang>('ru');
const [translateAgain, setTranslateAgain] = useState(false);
// ============ Картинки (новая схема: 3 слота) ============
// Ровно 3 слота, всегда. Пустой слот = null.
const [slots, setSlots] = useState<(ImageSlot | null)[]>([null, null, null]);
// Существующие картинки (режим редактирования) — занимают слоты в начале
const [existingImages, setExistingImages] = useState<string[]>([]);
// Три отдельных input[type=file] — по одному на слот. Без multiple.
const slotInputRef0 = useRef<HTMLInputElement>(null);
const slotInputRef1 = useRef<HTMLInputElement>(null);
const slotInputRef2 = useRef<HTMLInputElement>(null);
const slotInputRefs = [slotInputRef0, slotInputRef1, slotInputRef2];
// ============ Статусы ============
const [isTranslating, setIsTranslating] = useState(false);
const [isPublishing, setIsPublishing] = useState(false);
const [translationPreview, setTranslationPreview] = useState<TranslationPreview | null>(null);
const [error, setError] = useState<string | null>(null);
const [success, setSuccess] = useState(false);
// Синхронизируем состояние с editingPost при открытии
useEffect(() => {
if (isOpen && editingPost) {
setTitle(editingPost.title);
setBody(editingPost.body);
setLinkUrl(editingPost.linkUrl || '');
setTelegramUrl(editingPost.telegramUrl || '');
setIsPinned(editingPost.isPinned);
setExpiresAt(editingPost.expiresAt ? editingPost.expiresAt.slice(0, 16) : '');
setExistingImages(editingPost.images || []);
setSourceLang((language as SourceLang) || 'ru');
setTranslateAgain(false);
setSlots([null, null, null]);
} else if (isOpen) {
setTitle('');
setBody('');
setLinkUrl('');
setTelegramUrl('');
setIsPinned(false);
setExpiresAt('');
setSourceLang('ru');
setTranslateAgain(false);
setSlots([null, null, null]);
setExistingImages([]);
}
setTranslationPreview(null);
setError(null);
setSuccess(false);
}, [isOpen, editingPost, language]);
// 🔧 ФИКС (22.09.2026): утечка ObjectURL при размонтировании.
// Было: setSlots в cleanup — setState в unmounted компоненте НЕ выполняется,
// поэтому URL.revokeObjectURL никогда не вызывался.
// Стало: ref с актуальными слотами + чтение из ref в cleanup.
const slotsRef = useRef<(ImageSlot | null)[]>([null, null, null]);
useEffect(() => {
slotsRef.current = slots;
}, [slots]);
useEffect(() => {
return () => {
slotsRef.current.forEach(slot => {
if (slot?.previewUrl) {
try { URL.revokeObjectURL(slot.previewUrl); } catch { /* ignore */ }
}
});
};
}, []);
// ============ Работа с одним слотом ============
const handleSlotFile = async (slotIndex: number, e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) {
return;
}
// Сразу очищаем input, чтобы можно было выбрать тот же файл повторно
e.target.value = '';
// Валидация размера (страховка от совсем тяжёлых — например HEIC 15 МБ,
// который fallback не сжал)
if (file.size > 5 * 1024 * 1024) {
setError(t('feedAdminImageTooBig') || 'Фото слишком большое (макс. 5 МБ)');
return;
}
// Валидация типа
const okTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/webp', 'image/gif', 'image/heic', 'image/heif'];
if (!okTypes.includes(file.type)) {
setError(t('feedAdminImageBadType') || `Тип не разрешён: ${file.type}`);
return;
}
// 🔧 КЛЮЧЕВОЙ ФИКС: читаем байты СРАЗУ и создаём Blob.
// Никаких повторных file.arrayBuffer() позже — только blob.
try {
const buffer = await file.arrayBuffer();
let blob = new Blob([buffer], { type: file.type || 'image/jpeg' });
// 🔧 СЖАТИЕ: если больше 500 КБ — жмём до 1600px / 2 МБ
if (blob.size > 500 * 1024) {
try {
const { blob: compressed } = await compressImage(blob, 1600, 2 * 1024 * 1024);
blob = compressed;
} catch (e) {
console.error('[handleSlotFile] compress FAILED, using original:', e);
// оставляем оригинал — лучше отправить как есть, чем упасть
}
}
const previewUrl = URL.createObjectURL(blob);
setSlots(prev => {
const old = prev[slotIndex];
if (old?.previewUrl) {
try { URL.revokeObjectURL(old.previewUrl); } catch { /* ignore */ }
}
const next = [...prev];
next[slotIndex] = {
blob,
name: file.name,
// После сжатия всегда JPEG. Если сжатие упало — оставляем оригинальный тип.
type: blob.type || 'image/jpeg',
previewUrl,
};
return next;
});
setError(null);
} catch (err) {
console.error('[handleSlotFile] read FAIL:', err);
setError('Не удалось прочитать файл: ' + err);
}
};
const clearSlot = (slotIndex: number) => {
setSlots(prev => {
const old = prev[slotIndex];
if (old?.previewUrl) {
try { URL.revokeObjectURL(old.previewUrl); } catch { /* ignore */ }
}
const next = [...prev];
next[slotIndex] = null;
return next;
});
};
const handleRemoveExistingImage = (index: number) => {
setExistingImages((prev) => prev.filter((_, i) => i !== index));
};
// ============ Перевод (превью) ============
const handleTranslate = async () => {
if (!title.trim() || !body.trim()) {
setError(t('feedAdminTextRequired') || 'Введите текст поста');
return;
}
setIsTranslating(true);
setError(null);
try {
const data = await translateFeedPreview({
title: title.trim(),
body: body.trim(),
source_language: sourceLang,
});
setTranslationPreview(data);
} catch (e) {
console.error('[Translate] FAILED:', e);
setError(t('feedAdminErrorTranslate') || 'Не удалось перевести');
} finally {
setIsTranslating(false);
}
};
// ============ Публикация / обновление ============
const handlePublish = async () => {
const imagesToUpload = slots.filter((s): s is ImageSlot => s !== null);
if (!title.trim() || !body.trim()) {
setError(t('feedAdminTextRequired') || 'Введите текст поста');
return;
}
setIsPublishing(true);
setError(null);
try {
let postId: number;
if (isEditing && editingPost) {
const result = await updateFeedPost(editingPost.id, {
title: title.trim(),
body: body.trim(),
link_url: linkUrl.trim() || null,
telegram_url: telegramUrl.trim() || null,
is_pinned: isPinned,
expires_at: expiresAt ? new Date(expiresAt).toISOString() : null,
translate_again: translateAgain,
});
postId = result.post_id;
} else {
const result = await createFeedPost({
section,
source_language: sourceLang,
title: title.trim(),
body: body.trim(),
link_url: linkUrl.trim() || null,
telegram_url: telegramUrl.trim() || null,
is_pinned: isPinned,
is_published: true,
expires_at: expiresAt ? new Date(expiresAt).toISOString() : null,
});
postId = result.post_id;
}
if (!postId || typeof postId !== 'number') {
throw new Error(`Backend returned invalid postId: ${postId}`);
}
// 🔧 Отдельно обрабатываем каждый слот, чтобы не терять
const uploadResults: any[] = [];
const failedUploads: string[] = [];
for (let i = 0; i < imagesToUpload.length; i++) {
const slot = imagesToUpload[i];
try {
const res = await uploadFeedImage(postId, slot.blob, slot.name, slot.type);
uploadResults.push(res);
} catch (e: any) {
console.error(`[Publish] upload ${i + 1} FAILED:`, e?.message || e);
failedUploads.push(slot.name);
}
}
// 🔧 ФИКС: если хоть одна загрузка упала — не считаем публикацию успешной
if (failedUploads.length > 0) {
setError(
`Не удалось загрузить: ${failedUploads.join(', ')}. ` +
`Загружено ${uploadResults.length} из ${imagesToUpload.length} фото.`
);
return;
}
setSuccess(true);
setTimeout(() => {
onSuccess();
onClose();
}, 600);
} catch (e: any) {
console.error('[Publish] FAILED:', e);
setError(t('feedAdminErrorPublish') || 'Не удалось опубликовать');
} finally {
setIsPublishing(false);
}
};
if (!isOpen) return null;
const textColor = '#1A1A2E';
const subColor = '#6B7280';
const cardBg = 'rgba(255,255,255,0.55)';
const brandColor = '#8B5CF6';
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,
});
// Сколько слотов доступно под НОВЫЕ картинки (учитывая existing)
const newSlotsAvailable = Math.max(0, 3 - existingImages.length);
const totalImages = existingImages.length + slots.filter(Boolean).length;
return (
<div
style={{
position: 'fixed', top: 0, left: 0, right: 0, bottom: 0,
background: 'rgba(20,22,35,0.55)', zIndex: 2000,
display: 'flex', alignItems: 'center', justifyContent: 'center',
padding: '20px',
backdropFilter: 'blur(8px)', WebkitBackdropFilter: 'blur(8px)',
}}
onClick={(e) => { if (e.target === e.currentTarget && !isPublishing) onClose(); }}
>
<div
onClick={(e) => e.stopPropagation()}
style={{
...glass({
borderRadius: radius.lg,
padding: '20px',
width: '100%',
maxWidth: '480px',
maxHeight: '90vh',
display: 'flex',
flexDirection: 'column',
}),
}}
>
{/* ============ Шапка ============ */}
<div style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
marginBottom: '16px',
paddingBottom: '12px',
borderBottom: '1px solid rgba(0,0,0,0.06)',
flexShrink: 0,
}}>
<h3 style={{ margin: 0, fontSize: '17px', fontWeight: 800, color: textColor }}>
{isEditing ? `✏️ ${t('feedAdminEdit')}` : `➕ ${t('feedAdminSend')}`}
</h3>
<button
onClick={onClose}
disabled={isPublishing}
style={{
...glass({ padding: '8px 14px', borderRadius: radius.sm }),
color: textColor,
fontSize: '14px',
fontWeight: 600,
cursor: isPublishing ? 'default' : 'pointer',
opacity: isPublishing ? 0.5 : 1,
}}
>
✕
</button>
</div>
{/* ============ Скролл-контент ============ */}
<div style={{
flex: 1,
overflowY: 'auto',
display: 'flex',
flexDirection: 'column',
gap: '12px',
paddingBottom: '12px',
WebkitOverflowScrolling: 'touch',
minHeight: 0,
}}>
{/* Язык источника */}
<div>
<label style={{ fontSize: '12px', color: subColor, fontWeight: 600, marginBottom: '6px', display: 'block' }}>
{t('feedAdminSourceLang') || 'Язык источника'}
</label>
<div style={{ display: 'flex', gap: '6px', flexWrap: 'wrap' }}>
{(['pl', 'ru', 'uk', 'en'] as SourceLang[]).map((lang) => (
<button
key={lang}
onClick={() => setSourceLang(lang)}
disabled={isEditing && !translateAgain}
style={{
padding: '8px 14px',
borderRadius: radius.sm,
border: sourceLang === lang
? `2px solid ${brandColor}`
: '1px solid rgba(0,0,0,0.08)',
background: sourceLang === lang
? `${brandColor}15`
: 'rgba(255,255,255,0.6)',
color: sourceLang === lang ? brandColor : textColor,
fontSize: '13px',
fontWeight: 700,
cursor: (isEditing && !translateAgain) ? 'default' : 'pointer',
opacity: (isEditing && !translateAgain) ? 0.6 : 1,
textTransform: 'uppercase',
}}
>
{lang}
</button>
))}
</div>
</div>
{/* Заголовок */}
<div>
<label style={{ fontSize: '12px', color: subColor, fontWeight: 600, marginBottom: '6px', display: 'block' }}>
Title
</label>
<input
type="text"
value={title}
onChange={(e) => setTitle(e.target.value)}
placeholder="Заголовок поста"
disabled={isPublishing}
style={{
width: '100%',
padding: '12px 14px',
borderRadius: radius.md,
border: '1px solid rgba(0,0,0,0.08)',
background: 'rgba(255,255,255,0.8)',
color: textColor,
fontSize: '15px',
fontWeight: 600,
outline: 'none',
boxSizing: 'border-box',
}}
onFocus={(e) => {
e.currentTarget.style.borderColor = brandColor;
e.currentTarget.style.boxShadow = `0 0 0 3px ${brandColor}15`;
}}
onBlur={(e) => {
e.currentTarget.style.borderColor = 'rgba(0,0,0,0.08)';
e.currentTarget.style.boxShadow = 'none';
}}
/>
</div>
{/* Текст */}
<div>
<label style={{ fontSize: '12px', color: subColor, fontWeight: 600, marginBottom: '6px', display: 'block' }}>
Body
</label>
<textarea
value={body}
onChange={(e) => setBody(e.target.value)}
placeholder={t('feedAdminPlaceholder') || 'Написать пост...'}
disabled={isPublishing}
rows={5}
style={{
width: '100%',
padding: '12px 14px',
borderRadius: radius.md,
border: '1px solid rgba(0,0,0,0.08)',
background: 'rgba(255,255,255,0.8)',
color: textColor,
fontSize: '14px',
lineHeight: '1.5',
fontFamily: 'inherit',
outline: 'none',
resize: 'vertical',
minHeight: '100px',
boxSizing: 'border-box',
}}
onFocus={(e) => {
e.currentTarget.style.borderColor = brandColor;
e.currentTarget.style.boxShadow = `0 0 0 3px ${brandColor}15`;
}}
onBlur={(e) => {
e.currentTarget.style.borderColor = 'rgba(0,0,0,0.08)';
e.currentTarget.style.boxShadow = 'none';
}}
/>
</div>
{/* Опциональные поля */}
<details style={{
background: 'rgba(0,0,0,0.02)',
borderRadius: radius.md,
padding: '10px 12px',
}}>
<summary style={{
fontSize: '13px',
fontWeight: 600,
color: subColor,
cursor: 'pointer',
userSelect: 'none',
}}>
⚙️ Дополнительно
</summary>
<div style={{ marginTop: '12px', display: 'flex', flexDirection: 'column', gap: '10px' }}>
<input
type="text"
value={linkUrl}
onChange={(e) => setLinkUrl(e.target.value)}
placeholder={t('feedAdminLinkUrl') || 'Link (optional)'}
disabled={isPublishing}
style={{
width: '100%',
padding: '10px 12px',
borderRadius: radius.sm,
border: '1px solid rgba(0,0,0,0.08)',
background: 'rgba(255,255,255,0.8)',
color: textColor,
fontSize: '13px',
outline: 'none',
boxSizing: 'border-box',
}}
/>
<input
type="text"
value={telegramUrl}
onChange={(e) => setTelegramUrl(e.target.value)}
placeholder={t('feedAdminTelegramUrl') || 'Telegram URL (optional)'}
disabled={isPublishing}
style={{
width: '100%',
padding: '10px 12px',
borderRadius: radius.sm,
border: '1px solid rgba(0,0,0,0.08)',
background: 'rgba(255,255,255,0.8)',
color: textColor,
fontSize: '13px',
outline: 'none',
boxSizing: 'border-box',
}}
/>
<input
type="datetime-local"
value={expiresAt}
onChange={(e) => setExpiresAt(e.target.value)}
disabled={isPublishing}
style={{
width: '100%',
padding: '10px 12px',
borderRadius: radius.sm,
border: '1px solid rgba(0,0,0,0.08)',
background: 'rgba(255,255,255,0.8)',
color: textColor,
fontSize: '13px',
outline: 'none',
boxSizing: 'border-box',
}}
/>
<label style={{ display: 'flex', alignItems: 'center', gap: '8px', fontSize: '13px', color: textColor, cursor: 'pointer' }}>
<input
type="checkbox"
checked={isPinned}
onChange={(e) => setIsPinned(e.target.checked)}
disabled={isPublishing}
/>
📌 {t('feedAdminPinned') || 'Pin'}
</label>
{isEditing && (
<label style={{ display: 'flex', alignItems: 'center', gap: '8px', fontSize: '13px', color: textColor, cursor: 'pointer' }}>
<input
type="checkbox"
checked={translateAgain}
onChange={(e) => setTranslateAgain(e.target.checked)}
disabled={isPublishing}
/>
🌐 {t('feedAdminTranslateAgain') || 'Re-translate'}
</label>
)}
</div>
</details>
{/* Картинки — 3 слота */}
<div>
<label style={{ fontSize: '12px', color: subColor, fontWeight: 600, marginBottom: '8px', display: 'block' }}>
📷 {t('feedAdminImages') || 'Фото'} ({totalImages}/3)
</label>
<div style={{ display: 'flex', gap: '8px', flexWrap: 'wrap' }}>
{/* Существующие картинки (режим редактирования) */}
{existingImages.map((url, i) => (
<div key={`existing-${i}`} style={{ position: 'relative' }}>
<div style={{
width: '80px',
height: '80px',
borderRadius: radius.md,
background: `url(${url}) center/cover`,
border: '1px solid rgba(0,0,0,0.06)',
}} />
<button
onClick={() => handleRemoveExistingImage(i)}
disabled={isPublishing}
style={{
position: 'absolute',
top: '-6px',
right: '-6px',
width: '22px',
height: '22px',
borderRadius: '50%',
border: 'none',
background: '#E74C3C',
color: '#FFFFFF',
fontSize: '12px',
fontWeight: 800,
cursor: 'pointer',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
padding: 0,
boxShadow: '0 2px 6px rgba(231,76,60,0.4)',
}}
>
✕
</button>
</div>
))}
{/* Слоты для новых картинок — рендерим только доступное количество */}
{slots.slice(0, newSlotsAvailable).map((slot, slotIndex) => (
<div key={`slot-${slotIndex}`} style={{ position: 'relative' }}>
{/* Скрытый input для этого слота — БЕЗ multiple */}
<input
ref={slotInputRefs[slotIndex]}
type="file"
accept="image/*"
onChange={(e) => handleSlotFile(slotIndex, e)}
style={{ display: 'none' }}
disabled={isPublishing}
/>
{slot ? (
<>
{/* Превью с картинкой */}
<div style={{
width: '80px',
height: '80px',
borderRadius: radius.md,
background: `url(${slot.previewUrl}) center/cover`,
border: `2px solid ${brandColor}`,
opacity: isPublishing ? 0.5 : 1,
}} />
<button
onClick={() => clearSlot(slotIndex)}
disabled={isPublishing}
style={{
position: 'absolute',
top: '-6px',
right: '-6px',
width: '22px',
height: '22px',
borderRadius: '50%',
border: 'none',
background: '#E74C3C',
color: '#FFFFFF',
fontSize: '12px',
fontWeight: 800,
cursor: 'pointer',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
padding: 0,
boxShadow: '0 2px 6px rgba(231,76,60,0.4)',
}}
>
✕
</button>
</>
) : (
/* Пустой слот — плюсик */
<button
onClick={() => slotInputRefs[slotIndex].current?.click()}
disabled={isPublishing}
style={{
width: '80px',
height: '80px',
borderRadius: radius.md,
border: `2px dashed ${brandColor}60`,
background: `${brandColor}08`,
color: brandColor,
fontSize: '28px',
fontWeight: 300,
cursor: isPublishing ? 'default' : 'pointer',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
padding: 0,
transition: 'all 0.2s ease',
}}
onTouchStart={(e) => {
if (!isPublishing) e.currentTarget.style.transform = 'scale(0.95)';
}}
onTouchEnd={(e) => { e.currentTarget.style.transform = 'scale(1)'; }}
>
+
</button>
)}
</div>
))}
</div>
{/* Подсказка */}
<div style={{
fontSize: '11px',
color: subColor,
marginTop: '8px',
lineHeight: '1.4',
}}>
{t('feedAdminImagesHint') || 'Тапни на плюсик → выбери одну картинку. До 3 фото.'}
</div>
</div>
{/* Превью перевода */}
{translationPreview && (
<div style={{
padding: '12px',
background: `${brandColor}08`,
borderRadius: radius.md,
border: `1px solid ${brandColor}30`,
}}>
<div style={{
fontSize: '12px',
fontWeight: 700,
color: brandColor,
marginBottom: '8px',
textTransform: 'uppercase',
letterSpacing: '0.5px',
}}>
🌐 {t('feedAdminPreview') || 'Translation preview'}
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: '6px' }}>
{(['pl', 'ru', 'uk', 'en'] as const).map((lang) => (
<div key={lang} style={{
padding: '8px 10px',
background: 'rgba(255,255,255,0.6)',
borderRadius: radius.sm,
fontSize: '12px',
}}>
<div style={{ fontWeight: 800, color: brandColor, marginBottom: '2px', textTransform: 'uppercase' }}>
{lang}
</div>
<div style={{ fontWeight: 700, color: textColor, marginBottom: '2px' }}>
{translationPreview[`title_${lang}` as keyof TranslationPreview]}
</div>
<div style={{ color: textColor, lineHeight: '1.4', whiteSpace: 'pre-line' }}>
{translationPreview[`body_${lang}` as keyof TranslationPreview]}
</div>
</div>
))}
</div>
</div>
)}
{/* Ошибка */}
{error && (
<div style={{
padding: '10px 14px',
background: 'rgba(231,76,60,0.08)',
borderRadius: radius.md,
border: '1px solid rgba(231,76,60,0.2)',
color: '#E74C3C',
fontSize: '13px',
fontWeight: 600,
wordBreak: 'break-word',
}}>
⚠️ {error}
</div>
)}
{/* Успех */}
{success && (
<div style={{
padding: '10px 14px',
background: 'rgba(46,204,113,0.08)',
borderRadius: radius.md,
border: '1px solid rgba(46,204,113,0.3)',
color: '#2ECC71',
fontSize: '13px',
fontWeight: 600,
}}>
✅ {t('feedAdminSuccess') || 'Done!'}
</div>
)}
</div>
{/* ============ Кнопки внизу ============ */}
<div style={{
display: 'flex',
gap: '8px',
paddingTop: '12px',
borderTop: '1px solid rgba(0,0,0,0.06)',
flexShrink: 0,
flexWrap: 'wrap',
}}>
<button
onClick={onClose}
disabled={isPublishing}
style={{
flex: '1 1 auto',
padding: '12px 14px',
borderRadius: radius.md,
border: '1px solid rgba(0,0,0,0.08)',
background: 'rgba(255,255,255,0.8)',
color: textColor,
fontSize: '13px',
fontWeight: 700,
cursor: isPublishing ? 'default' : 'pointer',
opacity: isPublishing ? 0.5 : 1,
minWidth: '80px',
}}
>
{t('feedAdminCancel') || 'Cancel'}
</button>
<button
onClick={handleTranslate}
disabled={isTranslating || isPublishing || !title.trim() || !body.trim()}
style={{
flex: '1 1 auto',
padding: '12px 14px',
borderRadius: radius.md,
border: 'none',
background: (isTranslating || isPublishing || !title.trim() || !body.trim())
? 'rgba(255,154,60,0.35)'
: 'linear-gradient(135deg, #FF9A3C, #FF7A1F)',
color: '#1A1A2E',
fontSize: '13px',
fontWeight: 800,
cursor: (isTranslating || isPublishing || !title.trim() || !body.trim()) ? 'default' : 'pointer',
opacity: (isTranslating || isPublishing || !title.trim() || !body.trim()) ? 0.7 : 1,
minWidth: '110px',
boxShadow: (isTranslating || isPublishing || !title.trim() || !body.trim())
? 'none'
: '0 4px 15px rgba(255,154,60,0.45)',
transition: 'all 0.2s ease',
textShadow: '0 1px 0 rgba(255,255,255,0.4)',
}}
onTouchStart={(e) => {
if (!isTranslating && !isPublishing && title.trim() && body.trim()) {
e.currentTarget.style.transform = 'scale(0.96)';
}
}}
onTouchEnd={(e) => { e.currentTarget.style.transform = 'scale(1)'; }}
>
{isTranslating
? (t('feedAdminTranslating') || 'Translating...')
: `🌐 ${t('feedAdminTranslate') || 'Translate'}`}
</button>
<button
onClick={handlePublish}
disabled={isPublishing || !title.trim() || !body.trim()}
style={{
flex: '2 1 auto',
padding: '12px 14px',
borderRadius: radius.md,
border: 'none',
background: `linear-gradient(135deg, ${brandColor}, #6B46C1)`,
color: '#FFFFFF',
fontSize: '13px',
fontWeight: 700,
cursor: (isPublishing || !title.trim() || !body.trim()) ? 'default' : 'pointer',
opacity: (isPublishing || !title.trim() || !body.trim()) ? 0.5 : 1,
minWidth: '120px',
boxShadow: `0 4px 15px ${brandColor}40`,
}}
>
{isPublishing
? (t('feedAdminPublishing') || 'Publishing...')
: (isEditing
? `✓ ${t('feedAdminPublish') || 'Save'}`
: `📤 ${t('feedAdminPublish') || 'Publish'}`)}
</button>
</div>
</div>
</div>
);
};
export default FeedPostComposer;