'use client'; import { useState, useEffect, useRef } from 'react'; import { useRouter } from 'next/navigation'; import api from '@/services/api'; import { postService } from '@/services/postService'; import { useAuthStore } from '@/store/authStore'; import { locationService } from '@/services/locationService'; interface Account { id: string; type: string; username: string; } interface LocationData { name: string; latitude: number; longitude: number; } export default function CreatePost({ onPostCreated }: { onPostCreated?: () => void }) { const router = useRouter(); const { user } = useAuthStore(); const [accounts, setAccounts] = useState([]); const [selectedAccount, setSelectedAccount] = useState(null); const [content, setContent] = useState(''); const [posting, setPosting] = useState(false); const [showLocationPicker, setShowLocationPicker] = useState(false); const [selectedLocation, setSelectedLocation] = useState(null); const [locationSearch, setLocationSearch] = useState(''); const [searchingLocation, setSearchingLocation] = useState(false); const [locationResults, setLocationResults] = useState([]); const [gettingCurrentLocation, setGettingCurrentLocation] = useState(false); const [mediaFiles, setMediaFiles] = useState([]); const [mediaPreviews, setMediaPreviews] = useState([]); const [isDragging, setIsDragging] = useState(false); const dragCounter = useRef(0); const fileInputRef = useRef(null); useEffect(() => { fetchAccounts(); }, []); const fetchAccounts = async () => { try { const res = await api.get('/v1/switch/accounts'); setAccounts(res.data.accounts || []); if (res.data.accounts?.length > 0) { setSelectedAccount(res.data.accounts[0]); } } catch (error) { console.error('Failed to fetch accounts:', error); } }; const searchLocation = async (query: string) => { if (!query.trim()) { setLocationResults([]); return; } setSearchingLocation(true); try { const response = await locationService.geocodeAddress(query); if (response.location) { setLocationResults([{ name: response.location.name || query, latitude: response.location.latitude, longitude: response.location.longitude, }]); } } catch (error) { console.error('Location search error:', error); setLocationResults([]); } finally { setSearchingLocation(false); } }; const getCurrentLocation = () => { if (!navigator.geolocation) { alert('Geolocation is not supported by your browser'); return; } setGettingCurrentLocation(true); navigator.geolocation.getCurrentPosition( async (position) => { const { latitude, longitude } = position.coords; try { setSelectedLocation({ name: 'Current Location', latitude, longitude, }); setShowLocationPicker(false); } catch (error) { console.error('Failed to get location name:', error); } finally { setGettingCurrentLocation(false); } }, (error) => { console.error('Geolocation error:', error); alert('Unable to get your location. Please check your permissions.'); setGettingCurrentLocation(false); } ); }; const selectLocation = (location: LocationData) => { setSelectedLocation(location); setShowLocationPicker(false); setLocationSearch(''); setLocationResults([]); }; const removeLocation = () => { setSelectedLocation(null); }; // Media handling const handleFilesSelected = (files: File[]) => { const maxFiles = 10; const maxSize = 10 * 1024 * 1024; // 10MB const validFiles = files.filter(f => { if (!f.type.startsWith('image/') && !f.type.startsWith('video/')) return false; if (f.size > maxSize) return false; return true; }); const total = [...mediaFiles, ...validFiles].slice(0, maxFiles); const previews = total.map(f => URL.createObjectURL(f)); // Clean up old previews mediaPreviews.forEach(p => URL.revokeObjectURL(p)); setMediaFiles(total); setMediaPreviews(previews); }; const removeMedia = (index: number) => { URL.revokeObjectURL(mediaPreviews[index]); setMediaFiles(prev => prev.filter((_, i) => i !== index)); setMediaPreviews(prev => prev.filter((_, i) => i !== index)); }; // Drag and drop const handleDragEnter = (e: React.DragEvent) => { e.preventDefault(); e.stopPropagation(); dragCounter.current += 1; setIsDragging(true); }; const handleDragLeave = (e: React.DragEvent) => { e.preventDefault(); e.stopPropagation(); dragCounter.current -= 1; if (dragCounter.current === 0) setIsDragging(false); }; const handleDragOver = (e: React.DragEvent) => { e.preventDefault(); e.stopPropagation(); }; const handleDrop = (e: React.DragEvent) => { e.preventDefault(); e.stopPropagation(); setIsDragging(false); dragCounter.current = 0; const files = Array.from(e.dataTransfer.files); handleFilesSelected(files); }; const createPost = async () => { if (!content.trim() && mediaFiles.length === 0) return; setPosting(true); try { const formData = new FormData(); formData.append('content', content); if (selectedAccount) formData.append('accountId', selectedAccount.id); mediaFiles.forEach(file => { formData.append('media', file); }); if (mediaFiles.length > 0) { formData.append('mediaType', mediaFiles[0].type.startsWith('video/') ? 'video' : 'image'); } if (selectedLocation) { formData.append('location', JSON.stringify({ name: selectedLocation.name, latitude: selectedLocation.latitude, longitude: selectedLocation.longitude, })); } await postService.createPost(formData); setContent(''); setSelectedLocation(null); setMediaFiles([]); setMediaPreviews([]); onPostCreated?.(); } catch (error) { console.error('Failed to create post:', error); } finally { setPosting(false); } }; const navigateToFullComposer = () => { router.push('/create'); }; const displayName = user?.username || selectedAccount?.username || '?'; return (
{/* Drag overlay */} {isDragging && (

Drop files here

)}
{user?.avatar ? ( {displayName} ) : ( displayName[0]?.toUpperCase() )}
{accounts.length > 1 && (
)}