import React, { useState, useEffect, useRef } from 'react'; import { Send, Film, Upload, CheckCircle2, AlertCircle, RefreshCw, ExternalLink, Check, Heart, MessageCircle, Share2, Eye, X, Image as ImageIcon, MessageSquare, Palette, FileVideo, Plus, Hash, Layers, Video } from 'lucide-react'; import { SupportedLang, TRANSLATIONS } from '../data/translations'; import { OmniSDKConfig, PlatformType, PublishResult } from '../sdk/types'; import { PLATFORM_SPECS } from '../sdk/mediaValidator'; import { SocialAccountState } from './ConnectAccounts'; import { FacebookPageItem, INITIAL_FACEBOOK_PAGES } from '../types/facebookPages'; import { SocialAccountsBannerList } from './SocialAccountsBannerList'; import { AuthUser } from '../types/auth'; export type PublishFormatType = 'reel' | 'post' | 'status'; export type StatusBgTheme = 'emerald' | 'sunset' | 'cosmic' | 'ocean' | 'crimson' | 'clean'; const STATUS_THEMES: { id: StatusBgTheme; name: string; bgClass: string; textClass: string }[] = [ { id: 'emerald', name: 'Emerald', bgClass: 'bg-gradient-to-br from-emerald-600 via-teal-700 to-slate-900', textClass: 'text-white' }, { id: 'sunset', name: 'Sunset', bgClass: 'bg-gradient-to-br from-amber-500 via-rose-600 to-purple-800', textClass: 'text-white' }, { id: 'cosmic', name: 'Cosmic', bgClass: 'bg-gradient-to-br from-indigo-600 via-purple-700 to-pink-800', textClass: 'text-white' }, { id: 'ocean', name: 'Ocean', bgClass: 'bg-gradient-to-br from-cyan-600 via-blue-700 to-indigo-950', textClass: 'text-white' }, { id: 'crimson', name: 'Crimson', bgClass: 'bg-gradient-to-br from-rose-700 via-red-800 to-slate-950', textClass: 'text-white' }, { id: 'clean', name: 'Slate Post', bgClass: 'bg-slate-900 border border-slate-800', textClass: 'text-slate-100' } ]; interface PublishRecord { id: string; platform: PlatformType; postId: string; postUrl: string; title: string; timestamp: string; thumbnail: string; } interface PublishStudioProps { lang: SupportedLang; config: OmniSDKConfig; accounts: Record; onPublishSuccess: (records: PublishRecord[]) => void; onSyncRealData?: () => void; isSyncingRealData?: boolean; facebookPages?: FacebookPageItem[]; onUpdateFacebookPages?: (pages: FacebookPageItem[]) => void; onNavigateToConnect?: () => void; currentUser?: AuthUser | null; } export const PublishStudio: React.FC = ({ lang, config, accounts, onPublishSuccess, onSyncRealData, isSyncingRealData = false, facebookPages = INITIAL_FACEBOOK_PAGES, onUpdateFacebookPages, onNavigateToConnect, currentUser }) => { const t = TRANSLATIONS[lang]; // Publish Format: 'reel' | 'post' | 'status' const [publishFormat, setPublishFormat] = useState('reel'); const [statusTheme, setStatusTheme] = useState('emerald'); // Selected platforms - default to connected accounts const [selectedPlatforms, setSelectedPlatforms] = useState(() => { return accounts.facebook?.connected ? ['facebook'] : []; }); // Multi-page Facebook selection const [selectedPageIds, setSelectedPageIds] = useState(() => { if (accounts.facebook?.connected && facebookPages && facebookPages.length > 0) { return [facebookPages[0].id]; } return []; }); const [multiPagePublishResults, setMultiPagePublishResults] = useState([]); // Update selected pages if list changes useEffect(() => { if (facebookPages && facebookPages.length > 0) { setSelectedPageIds(prev => { const valid = prev.filter(id => facebookPages.some(p => p.id === id)); return valid.length > 0 ? valid : [facebookPages[0].id]; }); } }, [facebookPages]); // Uploaded real media state (supports BOTH photo and video) const [customFile, setCustomFile] = useState<{ name: string; size: number; url: string; file: File } | null>(null); const [customPhotoFile, setCustomPhotoFile] = useState<{ name: string; url: string; file: File } | null>(null); // Hidden input refs for dual media upload in feed posts const postPhotoInputRef = useRef(null); const postVideoInputRef = useRef(null); // Caption / Status Text const [caption, setCaption] = useState(''); const [inputError, setInputError] = useState(null); // Preview tab on the smartphone mockup const [previewPlatform, setPreviewPlatform] = useState('facebook'); // Publishing progress const [isPublishing, setIsPublishing] = useState(false); const [currentPublishPhase, setCurrentPublishPhase] = useState(''); const [publishProgress, setPublishProgress] = useState(0); const [latestResults, setLatestResults] = useState | null>(null); // User's custom hashtags (no default presets, user creates & sets them) const [userHashtags, setUserHashtags] = useState(() => { try { const saved = localStorage.getItem('ecohub_custom_hashtags'); return saved ? JSON.parse(saved) : []; } catch { return []; } }); const [newTagInput, setNewTagInput] = useState(''); const handleCreateTag = (e?: React.FormEvent) => { if (e) e.preventDefault(); let cleaned = newTagInput.trim().replace(/\s+/g, ''); if (!cleaned) return; if (!cleaned.startsWith('#')) { cleaned = `#${cleaned}`; } if (!userHashtags.includes(cleaned)) { const updated = [...userHashtags, cleaned]; setUserHashtags(updated); try { localStorage.setItem('ecohub_custom_hashtags', JSON.stringify(updated)); } catch (err) { console.warn(err); } } // Also append immediately to caption if not already present if (!caption.includes(cleaned)) { setCaption(prev => (prev.trim() ? `${prev.trim()} ${cleaned}` : cleaned)); } setNewTagInput(''); }; const handleRemoveTag = (tagToRemove: string, e: React.MouseEvent) => { e.stopPropagation(); const updated = userHashtags.filter(t => t !== tagToRemove); setUserHashtags(updated); try { localStorage.setItem('ecohub_custom_hashtags', JSON.stringify(updated)); } catch (err) { console.warn(err); } }; const handleToggleTagInCaption = (tag: string) => { if (caption.includes(tag)) { const regex = new RegExp(`\\s*${tag}`, 'g'); setCaption(prev => prev.replace(regex, '').trim()); } else { setCaption(prev => (prev.trim() ? `${prev.trim()} ${tag}` : tag)); } }; const togglePlatform = (p: PlatformType) => { setSelectedPlatforms(prev => prev.includes(p) ? prev.filter(item => item !== p) : [...prev, p] ); }; const handleCustomUpload = (e: React.ChangeEvent) => { setInputError(null); const file = e.target.files?.[0]; if (file) { const url = URL.createObjectURL(file); setCustomFile({ name: file.name, size: file.size, url, file }); } }; const handlePhotoUpload = (e: React.ChangeEvent) => { setInputError(null); const file = e.target.files?.[0]; if (file) { const url = URL.createObjectURL(file); setCustomPhotoFile({ name: file.name, url, file }); setCustomFile(null); } }; // Feed Post Dual Media Upload: Supports both photos and videos const handlePostMediaUpload = (e: React.ChangeEvent) => { setInputError(null); const file = e.target.files?.[0]; if (file) { const url = URL.createObjectURL(file); if (file.type.startsWith('video/')) { setCustomFile({ name: file.name, size: file.size, url, file }); setCustomPhotoFile(null); } else { setCustomPhotoFile({ name: file.name, url, file }); setCustomFile(null); } } }; const removeVideo = () => { if (customFile?.url) { URL.revokeObjectURL(customFile.url); } setCustomFile(null); }; const removePhoto = () => { if (customPhotoFile?.url) { URL.revokeObjectURL(customPhotoFile.url); } setCustomPhotoFile(null); }; // Execute Real Meta Publishing const handlePublish = async () => { setInputError(null); if (selectedPlatforms.length === 0) { setInputError(lang === 'bn' ? 'কমপক্ষে একটি সোশ্যাল প্ল্যাটফর্ম নির্বাচন করুন।' : 'Please select at least one platform.'); return; } if (publishFormat === 'reel' && !customFile) { setInputError(lang === 'bn' ? 'অনুগ্রহ করে প্রকাশের জন্য একটি MP4 ভিডিও ফাইল আপলোড করুন।' : 'Please upload an MP4 video file before publishing your Reel.'); return; } if (publishFormat === 'status' && !caption.trim()) { setInputError(lang === 'bn' ? 'অনুগ্রহ করে আপনার স্ট্যাটাস বার্তাটি লিখুন।' : 'Please write your status text before publishing.'); return; } if (selectedPlatforms.includes('youtube') && publishFormat === 'status') { setInputError( lang === 'bn' ? 'ইউটিউব শুধুমাত্র ভিডিও বা শর্টস (Shorts) সাপোর্ট করে। টেক্সট স্ট্যাটাস পোস্ট ইউটিউবে প্রকাশ করা সম্ভব নয়।' : 'YouTube only supports Video or Shorts. Text status updates cannot be published to YouTube.' ); return; } setIsPublishing(true); setLatestResults(null); setMultiPagePublishResults([]); setPublishProgress(25); setCurrentPublishPhase( lang === 'bn' ? `মেটা ও সোশ্যাল মিডিয়া সার্ভারে [${publishFormat.toUpperCase()}] প্রেরণের প্রস্তুতি চলছে...` : `Preparing [${publishFormat.toUpperCase()}] for remote dispatch...` ); try { setPublishProgress(55); setCurrentPublishPhase( lang === 'bn' ? 'সার্ভারে আসল এপিআই (Meta & YouTube API) এর মাধ্যমে ডেটা আপলোড হচ্ছে...' : 'Transmitting payload directly to live APIs...' ); const formData = new FormData(); formData.append('publishType', publishFormat); formData.append('platforms', JSON.stringify(selectedPlatforms)); formData.append('caption', caption); if (config.facebook?.pageId) formData.append('pageId', config.facebook.pageId); if (config.facebook?.accessToken) formData.append('fbAccessToken', config.facebook.accessToken); // YouTube support if (selectedPlatforms.includes('youtube')) { if (config.youtube?.accessToken) { formData.append('youtubeAccessToken', config.youtube.accessToken); } formData.append('youtubeTitle', caption.slice(0, 70) || 'Ecohub BD Video'); formData.append('youtubePrivacy', 'public'); } // Multiple Facebook Pages support const targetFbPages = (facebookPages || []).filter(p => selectedPageIds.includes(p.id)); if (targetFbPages.length > 0) { formData.append('targetPages', JSON.stringify(targetFbPages.map(p => ({ id: p.id, name: p.name, accessToken: p.accessToken })))); } if (publishFormat === 'reel' && customFile?.file) { formData.append('videoFile', customFile.file); } else if (publishFormat === 'post') { if (customPhotoFile?.file) { formData.append('mediaFile', customPhotoFile.file); } else if (customFile?.file) { formData.append('mediaFile', customFile.file); } } const resp = await fetch('/api/social/publish-real', { method: 'POST', body: formData }); setPublishProgress(85); setCurrentPublishPhase( lang === 'bn' ? 'পোস্ট কনফার্মেশন ও পারমালিঙ্ক সংগ্রহ করা হচ্ছে...' : 'Retrieving live confirmation permalinks...' ); const data = await resp.json(); const serverResults = data.results || {}; const mappedResults: Record = {} as any; const newRecords: PublishRecord[] = []; // Handle multi-page Facebook responses if (serverResults.facebookPages && Array.isArray(serverResults.facebookPages)) { setMultiPagePublishResults(serverResults.facebookPages); for (const pageRes of serverResults.facebookPages) { if (pageRes.success) { newRecords.push({ id: Math.random().toString(36).substring(2, 9), platform: 'facebook', postId: pageRes.postId, postUrl: pageRes.postUrl, title: `[${pageRes.pageName || 'Facebook'}] ${caption.substring(0, 50) || `${publishFormat.toUpperCase()} update`}`, timestamp: 'Just now', thumbnail: customPhotoFile ? customPhotoFile.url : (customFile ? customFile.url : (fbAccount.avatarUrl || '')) }); } } } for (const p of selectedPlatforms) { const sRes = serverResults[p]; if (sRes && sRes.success) { mappedResults[p] = { platform: p, success: true, postId: sRes.postId, postUrl: sRes.postUrl, executionTimeMs: sRes.executionTimeMs || 1200, logs: [{ timestamp: new Date().toISOString(), phase: 'COMPLETED', message: `Published [${publishFormat}] to ${p} via real API endpoint.`, level: 'success' }] }; newRecords.push({ id: Math.random().toString(36).substring(2, 9), platform: p, postId: sRes.postId, postUrl: sRes.postUrl, title: caption.substring(0, 60) || `${publishFormat.toUpperCase()} update`, timestamp: 'Just now', thumbnail: customPhotoFile ? customPhotoFile.url : (customFile ? customFile.url : (fbAccount.avatarUrl || '')) }); } else { mappedResults[p] = { platform: p, success: false, error: sRes?.error || 'Failed to publish to real account via API.', executionTimeMs: 0, logs: [{ timestamp: new Date().toISOString(), phase: 'ERROR', message: sRes?.error || 'Unknown error', level: 'error' }] }; } } setPublishProgress(100); setLatestResults(mappedResults); if (newRecords.length > 0) { onPublishSuccess(newRecords); } } catch (err: any) { console.error('Publishing failed:', err); const fallbackResults: Record = {} as any; for (const p of selectedPlatforms) { fallbackResults[p] = { platform: p, success: false, error: err.message || 'Connection error to backend publisher', executionTimeMs: 0, logs: [{ timestamp: new Date().toISOString(), phase: 'ERROR', message: err.message, level: 'error' }] }; } setLatestResults(fallbackResults); } finally { setIsPublishing(false); } }; const currentTheme = STATUS_THEMES.find(t => t.id === statusTheme) || STATUS_THEMES[0]; const fbAccount = accounts.facebook; return (
{/* All Social Media Live Connected Cards - Exact Uploaded Screenshot Style */} {/* Format Switcher: Reels, Feed Post, Status Update */}
{/* 1. Reels Option */} {/* 2. Feed Post Option */} {/* 3. Status Update Option */}
{/* Main Grid: Composer (Left) & Smartphone Mockup (Right) */}
{/* Left Column: 3-Step Composer (7 Cols) */}
{/* Step 1: Platforms */}
{selectedPlatforms.length} Selected
{(['facebook', 'youtube', 'instagram', 'tiktok', 'linkedin'] as PlatformType[]).map((p) => { const spec = PLATFORM_SPECS[p]; const acc = accounts[p]; const isSelected = selectedPlatforms.includes(p); return ( ); })}
{/* Multiple Facebook Pages Selection */} {selectedPlatforms.includes('facebook') && accounts.facebook?.connected && facebookPages && facebookPages.length > 0 && (
{lang === 'bn' ? 'টার্গেট ফেসবুক পেজ (Target Pages)' : 'Target Facebook Pages'} {selectedPageIds.length} {lang === 'bn' ? 'টি নির্বাচিত' : 'Selected'}
{onNavigateToConnect && currentUser?.role === 'admin' && ( )}
{facebookPages.map((pg) => { const isPageSelected = selectedPageIds.includes(pg.id); return (
{ setSelectedPageIds(prev => { if (prev.includes(pg.id)) { if (prev.length === 1) return prev; // Keep at least one selected return prev.filter(id => id !== pg.id); } else { return [...prev, pg.id]; } }); }} className={`p-2.5 rounded-xl border flex items-center justify-between cursor-pointer transition-all ${ isPageSelected ? 'bg-blue-950/40 border-blue-500/80 text-white shadow-sm ring-1 ring-blue-500/30' : 'bg-slate-950/50 border-slate-800/80 text-slate-400 hover:border-slate-700' }`} >
{pg.avatarUrl ? ( {pg.name} ) : (
{pg.name.charAt(0)}
)}
{pg.name} {pg.isVerified && ✓}
ID: {pg.id} • {pg.followersCount || pg.fanCount || 0} Followers
{isPageSelected && }
); })}
)}
{/* Step 2: Media Content & Format Setup (NO DEMO PRESETS) */}
{/* Format = REEL */} {publishFormat === 'reel' && (
{customFile && ( )}
{!customFile ? ( /* Video Upload Dropzone */ ) : ( /* Uploaded Video File Preview Card */

{customFile.name}

{(customFile.size / 1024 / 1024).toFixed(2)} MB • Ready for Meta Reels
Ready
)}
)} {/* Format = POST (PHOTO OR VIDEO - BOTH FULLY SUPPORTED) */} {publishFormat === 'post' && (
{(customPhotoFile || customFile) && ( )}
{/* Hidden input elements for specific pickers */} {!customPhotoFile && !customFile ? ( /* Dual Photo & Video Upload Dropzone */
+

{lang === 'bn' ? 'ফিড পোস্টের জন্য ছবি অথবা ভিডিও আপলোড করুন' : 'Upload photo or video for your feed post'}

{lang === 'bn' ? 'ছবি (JPG, PNG, WEBP) অথবা যেকোনো ভিডিও (MP4, MOV) আপলোড করা যাবে।' : 'Both photos (JPG, PNG, WEBP) and videos (MP4, MOV) are fully supported.'}

{/* Dual Action Buttons */}
{/* Fallback drag-and-drop input */}
) : customPhotoFile ? ( /* Attached Photo Card */

{customPhotoFile.name}

Photo Post Attached
Photo
Uploaded preview
) : ( /* Attached Video Card */

{customFile?.name}

Video Post • {customFile ? (customFile.size / (1024 * 1024)).toFixed(1) : 0} MB
Video
)}
)} {/* Format = STATUS (TEXT ONLY WITH THEMES) */} {publishFormat === 'status' && (
{lang === 'bn' ? 'ফেসবুক কালার স্ট্যাটাস' : 'Facebook Gradient Status'}
{STATUS_THEMES.map((theme) => ( ))}
)}
{/* Step 3: Caption, Text & Tags */}
{caption.length} / 2200