import React, { useState, useEffect, useRef } from 'react'; import { initializeApp } from 'firebase/app'; import { getAuth, onAuthStateChanged, createUserWithEmailAndPassword, signInWithEmailAndPassword, sendPasswordResetEmail, updateProfile, signOut, signInAnonymously, signInWithCustomToken } from 'firebase/auth'; import { getFirestore, collection, doc, setDoc, addDoc, onSnapshot, query, updateDoc, getDoc, arrayUnion, arrayRemove, orderBy } from 'firebase/firestore'; import { Heart, MessageCircle, Send, Search, Home, PlusSquare, X, Camera, User, Settings, BadgeCheck, LogOut, MoreHorizontal, Compass, Film, Bookmark, ChevronLeft } from 'lucide-react'; // --- FIREBASE INITIALIZATION --- const firebaseConfig = JSON.parse(__firebase_config); const app = initializeApp(firebaseConfig); const auth = getAuth(app); const db = getFirestore(app); const appId = typeof __app_id !== 'undefined' ? __app_id : 'kadraj-pro-desktop'; export default function App() { const [user, setUser] = useState(null); const [userData, setUserData] = useState(null); const [authMode, setAuthMode] = useState('login'); const [activeTab, setActiveTab] = useState('home'); const [targetUserId, setTargetUserId] = useState(null); const [posts, setPosts] = useState([]); const [users, setUsers] = useState([]); const [searchQuery, setSearchQuery] = useState(''); const [isCreating, setIsCreating] = useState(false); const [previewUrl, setPreviewUrl] = useState(null); const [loading, setLoading] = useState(true); const [isTransitioning, setIsTransitioning] = useState(false); const [activeChat, setActiveChat] = useState(null); const [messages, setMessages] = useState([]); // --- AUTHENTICATION FLOW (RULE 3) --- useEffect(() => { const initAuth = async () => { try { if (typeof __initial_auth_token !== 'undefined' && __initial_auth_token) { await signInWithCustomToken(auth, __initial_auth_token); } else { // Normal user flow handled by UI, but we ensure a base state } } catch (err) { console.error("Auth error:", err); } }; initAuth(); const unsubscribe = onAuthStateChanged(auth, async (u) => { if (u) { const userRef = doc(db, 'artifacts', appId, 'public', 'data', 'users', u.uid); const userDoc = await getDoc(userRef); if (userDoc.exists()) { setUserData(userDoc.data()); } else { const defaultData = { uid: u.uid, username: u.displayName?.toLowerCase().replace(/\s/g, '') || `kullanici_${u.uid.slice(0, 5)}`, fullName: u.displayName || 'Kadraj Kullanıcısı', avatar: `https://api.dicebear.com/7.x/avataaars/svg?seed=${u.uid}`, bio: 'Kadraj Sosyal dünyasına yeni katıldım.', followers: [], following: [], isVerified: false, createdAt: Date.now() }; await setDoc(userRef, defaultData); setUserData(defaultData); } setUser(u); } else { setUser(null); setUserData(null); } setLoading(false); }); return () => unsubscribe(); }, []); // --- DATA SYNC (RULE 1 & 2) --- useEffect(() => { if (!user) return; // Posts listener const postsQuery = query( collection(db, 'artifacts', appId, 'public', 'data', 'posts') ); const unsubPosts = onSnapshot(postsQuery, (snap) => { const p = snap.docs.map(d => ({ id: d.id, ...d.data() })); setPosts(p.sort((a, b) => b.createdAt - a.createdAt)); }, (err) => console.error("Posts error:", err)); // Users listener const usersQuery = collection(db, 'artifacts', appId, 'public', 'data', 'users'); const unsubUsers = onSnapshot(usersQuery, (snap) => { setUsers(snap.docs.map(d => ({ id: d.id, ...d.data() }))); }, (err) => console.error("Users error:", err)); return () => { unsubPosts(); unsubUsers(); }; }, [user]); // --- MESSAGES SYNC --- useEffect(() => { if (!activeChat || !user) return; const chatId = [user.uid, activeChat.uid].sort().join('_'); const msgQuery = collection(db, 'artifacts', appId, 'public', 'data', 'chats', chatId, 'messages'); const unsubMsgs = onSnapshot(msgQuery, (snap) => { const m = snap.docs.map(d => d.data()); setMessages(m.sort((a, b) => a.createdAt - b.createdAt)); }, (err) => console.error("Messages error:", err)); return () => unsubMsgs(); }, [activeChat, user]); // --- NAVIGATION & ACTIONS --- const navigateTo = (tab, targetId = null) => { setIsTransitioning(true); setTimeout(() => { setActiveTab(tab); if (targetId) setTargetUserId(targetId); setIsTransitioning(false); }, 400); }; const handleLogin = async (e) => { e.preventDefault(); const fd = new FormData(e.target); try { if (authMode === 'signup') { const res = await createUserWithEmailAndPassword(auth, fd.get('email'), fd.get('password')); await updateProfile(res.user, { displayName: fd.get('username') }); } else if (authMode === 'login') { await signInWithEmailAndPassword(auth, fd.get('email'), fd.get('password')); } else { await sendPasswordResetEmail(auth, fd.get('email')); setAuthMode('login'); } } catch (err) { console.error(err); } }; const handlePost = async (e) => { e.preventDefault(); if (!previewUrl || !user) return; const caption = e.target.caption.value; await addDoc(collection(db, 'artifacts', appId, 'public', 'data', 'posts'), { userId: user.uid, username: userData.username, avatar: userData.avatar, content: previewUrl, caption: caption, likes: [], isVerified: userData.isVerified, createdAt: Date.now() }); setIsCreating(false); setPreviewUrl(null); }; const handleSendMessage = async (e) => { e.preventDefault(); const text = e.target.msg.value; if (!text || !activeChat) return; const chatId = [user.uid, activeChat.uid].sort().join('_'); await addDoc(collection(db, 'artifacts', appId, 'public', 'data', 'chats', chatId, 'messages'), { senderId: user.uid, text, createdAt: Date.now() }); e.target.reset(); }; const toggleFollow = async (tUid) => { const isFollowing = userData.following.includes(tUid); const myRef = doc(db, 'artifacts', appId, 'public', 'data', 'users', user.uid); const tRef = doc(db, 'artifacts', appId, 'public', 'data', 'users', tUid); await updateDoc(myRef, { following: isFollowing ? arrayRemove(tUid) : arrayUnion(tUid) }); await updateDoc(tRef, { followers: isFollowing ? arrayRemove(user.uid) : arrayUnion(user.uid) }); }; if (loading) return
; if (!user) { return (

Kadraj

{authMode === 'signup' && ( )} {authMode !== 'reset' && ( )}
setAuthMode('reset')}>Şifreni mi unuttun?

{authMode === 'login' ? "Hesabın yok mu?" : "Zaten hesabın var mı?"}

); } return (
{/* Geçiş Perdesi */}
{/* Sol Kenar Çubuğu */} {/* Ana İçerik */}
{/* Akış Sayfası */} {activeTab === 'home' && (
{/* Hikayeler */}
{users.map(u => (
@{u.username}
))}
{/* Gönderiler */}
{posts.map(post => (
navigateTo('otherProfile', post.userId)}>
@{post.username} {post.isVerified && } • 2s

428 beğenme

@{post.username} {post.caption}

))}
)} {/* Mesajlaşma Sayfası */} {activeTab === 'chat' && (
@{userData.username}
{users.filter(u => u.uid !== user.uid).map(u => (
setActiveChat(u)} className={`p-4 flex items-center gap-3 cursor-pointer hover:bg-zinc-900 ${activeChat?.uid === u.uid ? 'bg-zinc-900' : ''}`} >
@{u.username} {u.fullName}
))}
{activeChat ? ( <>
@{activeChat.username}
{messages.map((m, i) => (
{m.text}
))}
) : (

Mesajların

Arkadaşlarına özel fotoğraflar ve mesajlar gönder.

)}
)} {/* Profil Sayfası */} {(activeTab === 'profile' || activeTab === 'otherProfile') && (
{(() => { const p = activeTab === 'profile' ? userData : users.find(u => u.uid === targetUserId); if (!p) return null; const isMe = p.uid === user.uid; return ( <>
{isMe &&
}

@{p.username}

{isMe ? ( ) : ( )}
{posts.filter(x => x.userId === p.uid).length} gönderi
{p.followers.length} takipçi
{p.following.length} takip

{p.fullName}

{p.bio}

{posts.filter(x => x.userId === p.uid).map(post => (
12 3
))}
); })()}
)} {/* Keşfet Sayfası */} {activeTab === 'explore' && (
{posts.map(post => (
navigateTo('otherProfile', post.userId)} className="aspect-square relative group bg-zinc-900 cursor-pointer overflow-hidden">
))}
)} {/* Sağ Kenar Çubuğu (Öneriler) */} {activeTab === 'home' && ( )}
{/* Gönderi Oluştur Modal */} {isCreating && (
Yeni Gönderi Oluştur
{!previewUrl ? (

Fotoğrafları buraya sürükle

{ const reader = new FileReader(); reader.onload = () => setPreviewUrl(reader.result); reader.readAsDataURL(e.target.files[0]); }} />
) : (
@{userData.username}
)}
)}
); }