import React, { useState, useEffect, useCallback, useRef } from 'react'; import { Home, Package, BarChart2, Settings, LogOut, Plus, Share2, Edit, Trash2, ChevronDown, Menu, X, Copy, ExternalLink, DollarSign, Download, Eye, Search, Bell, User, HelpCircle, FileText, Shield, Mail, Check, AlertCircle, Link, Smartphone, ArrowRight, Calendar, Clock, ChevronRight, ChevronLeft, Radio } from 'lucide-react'; // Import Socket.IO client import io from 'socket.io-client'; // Main App Component export default function InstaSellApp() { const [isLoggedIn, setIsLoggedIn] = useState(false); const [currentView, setCurrentView] = useState('login'); const [sidebarOpen, setSidebarOpen] = useState(true); const [mobileMenuOpen, setMobileMenuOpen] = useState(false); const [products, setProducts] = useState([]); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); const [user, setUser] = useState(null); const [notification, setNotification] = useState(null); const [liveSales, setLiveSales] = useState([]); const socketRef = useRef(null); const [analytics, setAnalytics] = useState({ totalSales: 0, totalRevenue: 0, conversionRate: 0, trafficSources: { whatsapp: 35, instagram: 25, facebook: 20, twitter: 10, other: 10 }, recentSales: [] }); // Initialize Socket.IO connection useEffect(() => { if (isLoggedIn) { // Connect to the WebSocket server socketRef.current = io('https://www.sitebrew.ai', { path: '/api/sales/live', auth: { token: localStorage.getItem('token') } }); // Listen for new sales events socketRef.current.on('new-sale', (saleData) => { // Add the new sale to the liveSales state with a unique ID and timestamp const newSale = { ...saleData, id: `sale-${Date.now()}`, timestamp: new Date(), isNew: true }; // Mask the buyer email for privacy if (newSale.buyerEmail) { const [username, domain] = newSale.buyerEmail.split('@'); newSale.maskedEmail = `${username.charAt(0)}${'*'.repeat(username.length - 2)}${username.charAt(username.length - 1)}@${domain}`; } setLiveSales(prevSales => { // Keep only the last 5 sales const updatedSales = [newSale, ...prevSales].slice(0, 5); return updatedSales; }); // Update the isNew flag after 3 seconds setTimeout(() => { setLiveSales(prevSales => prevSales.map(sale => sale.id === newSale.id ? { ...sale, isNew: false } : sale ) ); }, 3000); }); // Clean up the socket connection when component unmounts return () => { if (socketRef.current) { socketRef.current.disconnect(); } }; } }, [isLoggedIn]); // Fetch products from API const fetchProducts = useCallback(async () => { if (!isLoggedIn) return; setLoading(true); try { // In a real app, this would be an API call const response = await fetch(`https://www.sitebrew.ai/api/suZQ0T/products`, { headers: { 'Authorization': `Bearer ${localStorage.getItem('token')}` } }); if (!response.ok) { throw new Error('Failed to fetch products'); } const data = await response.json(); setProducts(data.document || []); // If no products are returned, use dummy data for demonstration if (!data.document || data.document.length === 0) { const dummyProducts = [ { _id: "prod1", title: 'Social Media Marketing Guide', description: 'A comprehensive guide to marketing your business on social media platforms.', price: 499, downloads: 124, revenue: 61876, image: 'https://assets.sitebrew.ai/generated-1747594437054.webp', fileUrl: '#', createdAt: '2023-05-15' }, { _id: "prod2", title: 'Website Design Templates Bundle', description: 'Premium website templates for various niches with responsive design.', price: 999, downloads: 87, revenue: 86913, image: 'https://assets.sitebrew.ai/generated-1747594437054.webp', fileUrl: '#', createdAt: '2023-06-22' }, { _id: "prod3", title: 'Business Plan Template', description: 'Ready-to-use business plan template with financial projections.', price: 799, downloads: 56, revenue: 44744, image: 'https://assets.sitebrew.ai/generated-1747594437054.webp', fileUrl: '#', createdAt: '2023-07-10' } ]; setProducts(dummyProducts); } } catch (err) { setError(err.message); console.error('Error fetching products:', err); // Use dummy data for demonstration const dummyProducts = [ { _id: "prod1", title: 'Social Media Marketing Guide', description: 'A comprehensive guide to marketing your business on social media platforms.', price: 499, downloads: 124, revenue: 61876, image: 'https://assets.sitebrew.ai/generated-1747594437054.webp', fileUrl: '#', createdAt: '2023-05-15' }, { _id: "prod2", title: 'Website Design Templates Bundle', description: 'Premium website templates for various niches with responsive design.', price: 999, downloads: 87, revenue: 86913, image: 'https://assets.sitebrew.ai/generated-1747594437054.webp', fileUrl: '#', createdAt: '2023-06-22' }, { _id: "prod3", title: 'Business Plan Template', description: 'Ready-to-use business plan template with financial projections.', price: 799, downloads: 56, revenue: 44744, image: 'https://assets.sitebrew.ai/generated-1747594437054.webp', fileUrl: '#', createdAt: '2023-07-10' } ]; setProducts(dummyProducts); } finally { setLoading(false); } }, [isLoggedIn]); // Fetch analytics data const fetchAnalytics = useCallback(async () => { if (!isLoggedIn) return; try { // In a real app, this would be an API call const response = await fetch(`https://www.sitebrew.ai/api/suZQ0T/analytics`, { headers: { 'Authorization': `Bearer ${localStorage.getItem('token')}` } }); if (!response.ok) { throw new Error('Failed to fetch analytics'); } const data = await response.json(); // If no analytics are returned, use dummy data if (!data.document) { // Generate dummy recent sales const recentSales = []; for (let i = 0; i < 5; i++) { const randomProduct = products[Math.floor(Math.random() * products.length)]; if (randomProduct) { const date = new Date(); date.setDate(date.getDate() - i); recentSales.push({ _id: `sale${i}`, productId: randomProduct._id, productTitle: randomProduct.title, amount: randomProduct.price, buyerEmail: `customer${i}@example.com`, date: date.toISOString(), paymentMethod: 'UPI' }); } } setAnalytics({ totalSales: products.reduce((sum, product) => sum + product.downloads, 0), totalRevenue: products.reduce((sum, product) => sum + product.revenue, 0), conversionRate: 3.2, trafficSources: { whatsapp: 35, instagram: 25, facebook: 20, twitter: 10, other: 10 }, recentSales }); } else { setAnalytics(data.document); } } catch (err) { console.error('Error fetching analytics:', err); // Generate dummy recent sales const recentSales = []; for (let i = 0; i < 5; i++) { const randomProduct = products[Math.floor(Math.random() * products.length)]; if (randomProduct) { const date = new Date(); date.setDate(date.getDate() - i); recentSales.push({ _id: `sale${i}`, productId: randomProduct._id, productTitle: randomProduct.title, amount: randomProduct.price, buyerEmail: `customer${i}@example.com`, date: date.toISOString(), paymentMethod: 'UPI' }); } } setAnalytics({ totalSales: products.reduce((sum, product) => sum + product.downloads, 0), totalRevenue: products.reduce((sum, product) => sum + product.revenue, 0), conversionRate: 3.2, trafficSources: { whatsapp: 35, instagram: 25, facebook: 20, twitter: 10, other: 10 }, recentSales }); } }, [isLoggedIn, products]); // Fetch user data const fetchUserData = useCallback(async () => { if (!isLoggedIn) return; try { // In a real app, this would be an API call const response = await fetch(`https://www.sitebrew.ai/api/suZQ0T/users/me`, { headers: { 'Authorization': `Bearer ${localStorage.getItem('token')}` } }); if (!response.ok) { throw new Error('Failed to fetch user data'); } const data = await response.json(); if (!data.document) { // Use dummy user data setUser({ _id: 'user1', name: 'John Doe', email: 'john.doe@example.com', upiId: 'johndoe@okaxis', profilePicture: null }); } else { setUser(data.document); } } catch (err) { console.error('Error fetching user data:', err); // Use dummy user data setUser({ _id: 'user1', name: 'John Doe', email: 'john.doe@example.com', upiId: 'johndoe@okaxis', profilePicture: null }); } }, [isLoggedIn]); // Load data when logged in useEffect(() => { if (isLoggedIn) { fetchProducts(); fetchAnalytics(); fetchUserData(); } }, [isLoggedIn, fetchProducts, fetchAnalytics, fetchUserData]); // Check if user is already logged in (from localStorage) useEffect(() => { const token = localStorage.getItem('token'); if (token) { setIsLoggedIn(true); setCurrentView('dashboard'); } }, []); // Simulate live sales for demo purposes useEffect(() => { if (isLoggedIn && products.length > 0) { // This is just for demonstration - in a real app, this would come from WebSockets const simulateSaleInterval = setInterval(() => { const randomProduct = products[Math.floor(Math.random() * products.length)]; if (randomProduct) { const randomNames = ['john', 'sarah', 'mike', 'emma', 'david', 'lisa', 'alex', 'olivia']; const randomDomains = ['gmail.com', 'yahoo.com', 'outlook.com', 'hotmail.com', 'example.com']; const randomName = randomNames[Math.floor(Math.random() * randomNames.length)]; const randomDomain = randomDomains[Math.floor(Math.random() * randomDomains.length)]; const email = `${randomName}@${randomDomain}`; // Simulate a WebSocket event const newSale = { productId: randomProduct._id, productTitle: randomProduct.title, amount: randomProduct.price, buyerEmail: email, timestamp: new Date().toISOString(), paymentMethod: 'UPI' }; // Mask the buyer email for privacy const [username, domain] = email.split('@'); const maskedEmail = `${username.charAt(0)}${'*'.repeat(username.length - 2)}${username.charAt(username.length - 1)}@${domain}`; const saleWithId = { ...newSale, id: `sale-${Date.now()}`, maskedEmail, isNew: true }; setLiveSales(prevSales => { // Keep only the last 5 sales const updatedSales = [saleWithId, ...prevSales].slice(0, 5); return updatedSales; }); // Update the isNew flag after 3 seconds setTimeout(() => { setLiveSales(prevSales => prevSales.map(sale => sale.id === saleWithId.id ? { ...sale, isNew: false } : sale ) ); }, 3000); } }, 15000); // Simulate a new sale every 15 seconds return () => clearInterval(simulateSaleInterval); } }, [isLoggedIn, products]); // Handle login const handleLogin = async (email, password) => { setLoading(true); try { // In a real app, this would be an API call const response = await fetch(`https://www.sitebrew.ai/api/suZQ0T/auth/login`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ document: { email, password } }) }); if (!response.ok) { throw new Error('Invalid credentials'); } const data = await response.json(); // Store token in localStorage localStorage.setItem('token', data.token || 'dummy-token'); setIsLoggedIn(true); setCurrentView('dashboard'); showNotification('Login successful', 'success'); } catch (err) { console.error('Login error:', err); showNotification(err.message, 'error'); // For demo purposes, log in anyway localStorage.setItem('token', 'dummy-token'); setIsLoggedIn(true); setCurrentView('dashboard'); } finally { setLoading(false); } }; // Handle signup const handleSignup = async (name, email, password) => { setLoading(true); try { // In a real app, this would be an API call const response = await fetch(`https://www.sitebrew.ai/api/suZQ0T/auth/register`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ document: { name, email, password } }) }); if (!response.ok) { throw new Error('Registration failed'); } const data = await response.json(); // Store token in localStorage localStorage.setItem('token', data.token || 'dummy-token'); setIsLoggedIn(true); setCurrentView('dashboard'); showNotification('Account created successfully', 'success'); } catch (err) { console.error('Signup error:', err); showNotification(err.message, 'error'); // For demo purposes, log in anyway localStorage.setItem('token', 'dummy-token'); setIsLoggedIn(true); setCurrentView('dashboard'); } finally { setLoading(false); } }; // Handle logout const handleLogout = () => { localStorage.removeItem('token'); setIsLoggedIn(false); setCurrentView('login'); setUser(null); showNotification('Logged out successfully', 'success'); // Disconnect WebSocket if (socketRef.current) { socketRef.current.disconnect(); } }; // Add new product const handleAddProduct = async (productData) => { setLoading(true); try { // In a real app, this would be an API call const response = await fetch(`https://www.sitebrew.ai/api/suZQ0T/products`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${localStorage.getItem('token')}` }, body: JSON.stringify({ document: { ...productData, downloads: 0, revenue: 0, createdAt: new Date().toISOString().split('T')[0] } }) }); if (!response.ok) { throw new Error('Failed to add product'); } const data = await response.json(); // Add the new product to the state const newProduct = { _id: data.document._id || `prod${products.length + 1}`, ...productData, downloads: 0, revenue: 0, createdAt: new Date().toISOString().split('T')[0] }; setProducts([...products, newProduct]); setCurrentView('dashboard'); showNotification('Product added successfully', 'success'); } catch (err) { console.error('Error adding product:', err); showNotification(err.message, 'error'); // For demo purposes, add the product anyway const newProduct = { _id: `prod${products.length + 1}`, ...productData, downloads: 0, revenue: 0, createdAt: new Date().toISOString().split('T')[0] }; setProducts([...products, newProduct]); setCurrentView('dashboard'); } finally { setLoading(false); } }; // Update product const handleUpdateProduct = async (productId, updatedData) => { setLoading(true); try { // In a real app, this would be an API call const response = await fetch(`https://www.sitebrew.ai/api/suZQ0T/products`, { method: 'PUT', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${localStorage.getItem('token')}` }, body: JSON.stringify({ document: { _id: productId, ...updatedData } }) }); if (!response.ok) { throw new Error('Failed to update product'); } // Update the product in the state setProducts(products.map(product => product._id === productId ? { ...product, ...updatedData } : product )); setCurrentView('products'); showNotification('Product updated successfully', 'success'); } catch (err) { console.error('Error updating product:', err); showNotification(err.message, 'error'); // For demo purposes, update the product anyway setProducts(products.map(product => product._id === productId ? { ...product, ...updatedData } : product )); setCurrentView('products'); } finally { setLoading(false); } }; // Delete product const handleDeleteProduct = async (productId) => { if (!window.confirm('Are you sure you want to delete this product?')) { return; } setLoading(true); try { // In a real app, this would be an API call const response = await fetch(`https://www.sitebrew.ai/api/suZQ0T/products`, { method: 'DELETE', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${localStorage.getItem('token')}` }, body: JSON.stringify({ document: { _id: productId } }) }); if (!response.ok) { throw new Error('Failed to delete product'); } // Remove the product from the state setProducts(products.filter(product => product._id !== productId)); showNotification('Product deleted successfully', 'success'); } catch (err) { console.error('Error deleting product:', err); showNotification(err.message, 'error'); // For demo purposes, delete the product anyway setProducts(products.filter(product => product._id !== productId)); } finally { setLoading(false); } }; // Update user profile const handleUpdateProfile = async (profileData) => { setLoading(true); try { // In a real app, this would be an API call const response = await fetch(`https://www.sitebrew.ai/api/suZQ0T/users`, { method: 'PUT', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${localStorage.getItem('token')}` }, body: JSON.stringify({ document: { _id: user._id, ...profileData } }) }); if (!response.ok) { throw new Error('Failed to update profile'); } // Update the user in the state setUser({ ...user, ...profileData }); showNotification('Profile updated successfully', 'success'); } catch (err) { console.error('Error updating profile:', err); showNotification(err.message, 'error'); // For demo purposes, update the profile anyway setUser({ ...user, ...profileData }); } finally { setLoading(false); } }; // Generate share link for a product const generateShareLink = (productId) => { return `${window.location.origin}/product/${productId}`; }; // Show notification const showNotification = (message, type = 'info') => { setNotification({ message, type }); // Auto-hide notification after 3 seconds setTimeout(() => { setNotification(null); }, 3000); }; // Toggle sidebar on mobile const toggleMobileMenu = () => { setMobileMenuOpen(!mobileMenuOpen); }; // Render appropriate view based on state const renderView = () => { if (!isLoggedIn) { return currentView === 'login' ? setCurrentView('signup')} loading={loading} /> : setCurrentView('login')} loading={loading} />; } switch (currentView) { case 'dashboard': return setCurrentView('addProduct')} onDeleteProduct={handleDeleteProduct} onShareProduct={(productId) => { const link = generateShareLink(productId); navigator.clipboard.writeText(link); showNotification('Link copied to clipboard', 'success'); }} loading={loading} />; case 'products': return setCurrentView('addProduct')} onDeleteProduct={handleDeleteProduct} onEditProduct={(productId) => { const product = products.find(p => p._id === productId); if (product) { setCurrentView('editProduct'); // In a real app, you would store the product to edit in state } }} onShareProduct={(productId) => { const link = generateShareLink(productId); navigator.clipboard.writeText(link); showNotification('Link copied to clipboard', 'success'); }} loading={loading} />; case 'analytics': return ; case 'settings': return ; case 'addProduct': return setCurrentView('dashboard')} loading={loading} />; case 'editProduct': return p._id === 'prod1')} // In a real app, you would use the selected product onUpdateProduct={handleUpdateProduct} onCancel={() => setCurrentView('products')} loading={loading} />; default: return setCurrentView('addProduct')} onDeleteProduct={handleDeleteProduct} loading={loading} />; } }; // If not logged in, show login/signup page if (!isLoggedIn) { return (
InstaSell Logo InstaSell
{renderView()}
{/* Notification */} {notification && (
{notification.type === 'success' ? : notification.type === 'error' ? : } {notification.message}
)}
); } // Main app layout for logged in users return (
{/* Header */}
{/* Mobile menu button */} {/* Logo */}
InstaSell Logo InstaSell
{/* Right side header items */}
{user?.profilePicture ? ( {user.name} ) : ( )}
{user?.name || 'User'}
{/* Mobile sidebar */} {mobileMenuOpen && (
InstaSell Logo InstaSell
)} {/* Desktop sidebar */}
{/* Main content */}
{loading ? (
) : ( renderView() )}
{/* Notification */} {notification && (
{notification.type === 'success' ? : notification.type === 'error' ? : } {notification.message}
)}
); } // Sidebar Link Component const SidebarLink = ({ icon, text, active, onClick }) => { return ( ); }; // Login View Component const LoginView = ({ onLogin, onSwitchToSignup, loading }) => { const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const [error, setError] = useState(''); const handleSubmit = (e) => { e.preventDefault(); setError(''); if (!email || !password) { setError('Please enter both email and password'); return; } onLogin(email, password); }; return (

Sign in to your account

Or{' '}

{error && (

{error}

)}
setEmail(e.target.value)} disabled={loading} />
setPassword(e.target.value)} disabled={loading} />
{/* Demo credentials */}

Demo credentials: demo@example.com / password

); }; // Signup View Component const SignupView = ({ onSignup, onSwitchToLogin, loading }) => { const [name, setName] = useState(''); const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const [confirmPassword, setConfirmPassword] = useState(''); const [error, setError] = useState(''); const handleSubmit = (e) => { e.preventDefault(); setError(''); if (!name || !email || !password) { setError('Please fill in all required fields'); return; } if (password !== confirmPassword) { setError('Passwords do not match'); return; } onSignup(name, email, password); }; return (

Create your account

Or{' '}

{error && (

{error}

)}
setName(e.target.value)} disabled={loading} />
setEmail(e.target.value)} disabled={loading} />
setPassword(e.target.value)} disabled={loading} />
setConfirmPassword(e.target.value)} disabled={loading} />
); }; // Live Sales Component const LiveSalesPanel = ({ sales }) => { return (

Live Sales

Live
{sales.length > 0 ? (
    {sales.map((sale) => (
  • {sale.productTitle}
    {sale.maskedEmail}
    ₹{(sale.amount / 100).toFixed(2)}
    {new Date(sale.timestamp).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
  • ))}
) : (
No sales

No live sales yet

Sales will appear here in real-time as they happen.

)}
); }; // Dashboard View Component const DashboardView = ({ products, analytics, liveSales, onAddProduct, onDeleteProduct, onShareProduct, loading }) => { // Calculate total revenue and downloads const totalRevenue = products.reduce((sum, product) => sum + product.revenue, 0); const totalDownloads = products.reduce((sum, product) => sum + product.downloads, 0); return (

Dashboard

{/* Stats Overview */}
} /> } /> } /> } />
{/* Recent Products */}

Recent Products

{products.length > 0 ? (
    {products.slice(0, 3).map((product) => (
  • {product.title}

    {product.title}

    {product.description}

    ₹{(product.price / 100).toFixed(2)} • {product.downloads} downloads

  • ))}
) : (
No products

No products yet

Get started by creating your first digital product.

)}
{/* Recent Sales */}

Recent Sales

{analytics.recentSales && analytics.recentSales.length > 0 ? (
    {analytics.recentSales.map((sale) => (
  • {sale.productTitle}
    {sale.buyerEmail}
    ₹{(sale.amount / 100).toFixed(2)}
    {new Date(sale.date).toLocaleDateString()}
  • ))}
) : (
No sales

No sales yet

Share your products to start making sales.

)}
{/* Live Sales Panel */} {/* Traffic Sources */}

Traffic Sources

{/* Quick Actions */}

Quick Actions

} actionText="Share Now" onClick={() => {}} /> } actionText="Create Post" onClick={() => {}} /> } actionText="Download" onClick={() => {}} />
); }; // Image component (since it's not imported from lucide-react) const Image = ({ className }) => ( ); // Quick Action Card Component const QuickActionCard = ({ title, description, icon, actionText, onClick }) => { return (
{icon}

{title}

{description}

); }; // Stat Card Component const StatCard = ({ title, value, change, icon }) => { const isPositive = change.startsWith('+'); return (
{icon}
{title}
{value}
{isPositive ? ( ) : ( )} {change} from last month
); }; // Traffic Source Bar Component const TrafficSourceBar = ({ platform, percentage, color }) => { return (
{platform}
{percentage}%
); }; // Products View Component const ProductsView = ({ products, onAddProduct, onDeleteProduct, onEditProduct, onShareProduct, loading }) => { const [searchTerm, setSearchTerm] = useState(''); const [sortBy, setSortBy] = useState('newest'); const [viewMode, setViewMode] = useState('grid'); // 'grid' or 'list' // Filter products based on search term const filteredProducts = products.filter(product => product.title.toLowerCase().includes(searchTerm.toLowerCase()) || product.description.toLowerCase().includes(searchTerm.toLowerCase()) ); // Sort products based on selected option const sortedProducts = [...filteredProducts].sort((a, b) => { switch (sortBy) { case 'newest': return new Date(b.createdAt) - new Date(a.createdAt); case 'oldest': return new Date(a.createdAt) - new Date(b.createdAt); case 'price-high': return b.price - a.price; case 'price-low': return a.price - b.price; case 'downloads': return b.downloads - a.downloads; default: return 0; } }); return (

Products

{/* Search and Filter */}
setSearchTerm(e.target.value)} />
{/* Products List/Grid */} {sortedProducts.length > 0 ? ( viewMode === 'grid' ? (
{sortedProducts.map((product) => (
{product.title}

{product.title}

₹{(product.price / 100).toFixed(2)}

{product.description}

{product.downloads} downloads ₹{(product.revenue / 100).toLocaleString()}
Created on {product.createdAt}
))}
) : (
    {sortedProducts.map((product) => (
  • {product.title}

    {product.title}

    ₹{(product.price / 100).toFixed(2)}

    {product.downloads} downloads

    ₹{(product.revenue / 100).toLocaleString()} revenue

    Created on {product.createdAt}

  • ))}
) ) : (
No products

No products found

Try adjusting your search or filter to find what you're looking for.

{products.length === 0 && (
)}
)}
); }; // Analytics View Component const AnalyticsView = ({ analytics, products, loading }) => { const [dateRange, setDateRange] = useState('month'); // 'week', 'month', 'year' const [currentPage, setCurrentPage] = useState(1); const itemsPerPage = 5; // Calculate total revenue and downloads const totalRevenue = products.reduce((sum, product) => sum + product.revenue, 0); const totalDownloads = products.reduce((sum, product) => sum + product.downloads, 0); // Top performing products (by revenue) const topProducts = [...products] .sort((a, b) => b.revenue - a.revenue) .slice(0, 5); // Paginate recent sales const paginatedSales = analytics.recentSales ? analytics.recentSales.slice((currentPage - 1) * itemsPerPage, currentPage * itemsPerPage) : []; const totalPages = analytics.recentSales ? Math.ceil(analytics.recentSales.length / itemsPerPage) : 0; return (

Analytics

{/* Stats Overview */}
} /> } /> } /> } />
{/* Revenue Chart */}

Revenue Over Time

{dateRange === 'week' ? 'Last 7 days' : dateRange === 'month' ? 'Last 30 days' : 'Last 12 months'}
{/* This would be a chart in a real application */}
Revenue Chart
{Array.from({ length: 12 }).map((_, i) => (
))}
{/* Recent Sales */}

Recent Sales

{paginatedSales.length > 0 ? ( <> {paginatedSales.map((sale) => ( ))}
Product Customer Amount Date Payment
{sale.productTitle}
{sale.buyerEmail}
₹{(sale.amount / 100).toFixed(2)}
{new Date(sale.date).toLocaleDateString()}
{sale.paymentMethod}
{/* Pagination */} {totalPages > 1 && (

Showing {(currentPage - 1) * itemsPerPage + 1} to{' '} {Math.min(currentPage * itemsPerPage, analytics.recentSales.length)} {' '} of {analytics.recentSales.length} results

{/* Right side header items */}
{user?.profilePicture ? ( {user.name} ) : ( )}
{user?.name || 'User'}
{/* Mobile sidebar */} {mobileMenuOpen && (
InstaSell Logo InstaSell
)} {/* Desktop sidebar */}
{/* Main content */}
{loading ? (
) : ( renderView() )}
{/* Notification */} {notification && (
{notification.type === 'success' ? : notification.type === 'error' ? : } {notification.message}
)}
); } // ... (rest of the code remains the same)