"use client"; import React, { useState, useEffect } from 'react'; import Link from 'next/link'; import { LayoutDashboard, Edit3, ShoppingBag, CreditCard, LogOut, Eye, MessageSquare, User as UserIcon, Rocket } from 'lucide-react'; import { useRouter, useSearchParams } from 'next/navigation'; import { User } from '../../types'; import { MOCK_BUSINESSES } from '../../lib/mockData'; import DashboardOverview from '../../components/dashboard/DashboardOverview'; import DashboardProfile from '../../components/dashboard/DashboardProfile'; import DashboardProfileClient from '../../components/dashboard/DashboardProfileClient'; import DashboardMessages from '../../components/dashboard/DashboardMessages'; import DashboardOffers from '../../components/dashboard/DashboardOffers'; import PricingSection from '../../components/PricingSection'; import { useUser } from '../../components/UserProvider'; const DashboardPage = () => { const { user, logout } = useUser(); const router = useRouter(); const searchParams = useSearchParams(); const chatId = searchParams.get('chatId') || searchParams.get('chat'); const [currentView, setCurrentView] = useState<'overview' | 'profile' | 'offers' | 'subscription' | 'messages' | 'personal-profile'>('overview'); const [business, setBusiness] = useState(null); const [stats, setStats] = useState<{ totalViews: number, contactClicks: number } | null>(null); const [loading, setLoading] = useState(true); const [isMounted, setIsMounted] = useState(false); const [unreadCount, setUnreadCount] = useState(0); useEffect(() => { setIsMounted(true); // Handle view from URL const viewParam = searchParams.get('view'); if (viewParam && ['overview', 'profile', 'offers', 'subscription', 'messages', 'personal-profile'].includes(viewParam)) { setCurrentView(viewParam as any); } }, [searchParams]); // Fetch user's business useEffect(() => { if (!user || !isMounted) return; const fetchBusiness = async () => { try { const res = await fetch('/api/businesses/me', { headers: { 'x-user-id': user.id } }); const data = await res.json(); if (data && !data.error) { setBusiness(data); // Fetch stats for this business try { const statsRes = await fetch(`/api/analytics/businesses/${data.id}`); const statsData = await statsRes.json(); if (!statsData.error) { setStats(statsData); } } catch (e) { console.error('Error fetching stats:', e); } } } catch (error) { console.error('Error fetching dashboard business:', error); } finally { setLoading(false); } }; fetchBusiness(); }, [user, isMounted]); // Fetch unread messages count const fetchUnreadCount = async () => { if (!user || !isMounted) return; // If user has no id, try to find it via email (Session Reconciliation) let effectiveUserId = user.id; if (!effectiveUserId || effectiveUserId === 'undefined' || effectiveUserId === 'null') { try { const res = await fetch(`/api/users/profile?email=${encodeURIComponent(user.email)}`); const data = await res.json(); if (data.id) { effectiveUserId = data.id; // Note: Ideally we'd update the global user object here too } else { return; // Can't count without ID } } catch (e) { return; } } try { const res = await fetch('/api/messages/unread', { headers: { 'x-user-id': effectiveUserId } }); const data = await res.json(); if (!data.error) { setUnreadCount(data.count); } } catch (error) { console.error('Error fetching unread count:', error); } }; useEffect(() => { fetchUnreadCount(); const interval = setInterval(fetchUnreadCount, 15000); // Polling every 15s return () => clearInterval(interval); }, [user, isMounted]); // Update document title with unread count useEffect(() => { if (unreadCount > 0) { document.title = `(${unreadCount}) Messages - Afropreunariat`; } else { document.title = 'Tableau de Bord - Afropreunariat'; } }, [unreadCount]); useEffect(() => { if (!user && isMounted) { router.push('/login'); } }, [user, isMounted, router]); if (!isMounted || (loading && user)) { return (

Chargement de votre espace...

); } if (!user) { return null; } // Default business structure for new users const displayBusiness = business || { id: 'new', name: "Ma Boutique", category: "Technologie & IT", location: "Ma Ville", description: "Décrivez votre entreprise ici...", logoUrl: "https://picsum.photos/200/200?random=default", contactEmail: user?.email || "", contactPhone: "", slug: "", tags: [], socialLinks: {}, verified: false, viewCount: 0, rating: 0, offers: [] }; return (
{/* 1. Sidebar */}
A
Afropreunariat
{user.name.charAt(0)} {unreadCount > 0 && ( <> )}

{user.name}

En ligne
{/* 2. Main Content */}

{currentView === 'overview' && 'Vue d\'ensemble'} {currentView === 'messages' && 'Mes Messages'} {currentView === 'personal-profile' && 'Mon Profil Client'} {currentView === 'profile' && (user.role === 'ENTREPRENEUR' ? 'Ma Fiche Entreprise' : 'Créer mon Business')} {currentView === 'offers' && 'Gestion des Offres'} {currentView === 'subscription' && 'Mon Abonnement'}

Voir ma fiche
{business?.isSuspended && (

Boutique Suspendue

"{business.suspensionReason || "Votre boutique a été temporairement masquée suite à une décision de la modération."}"

Veuillez contacter l'administration pour plus d'informations.

)} {currentView === 'overview' && } {currentView === 'messages' && } {currentView === 'personal-profile' && } {currentView === 'profile' && } {currentView === 'offers' && } {currentView === 'subscription' && (

Abonnement Actuel : Starter (Gratuit)

Passez au niveau supérieur pour débloquer plus de fonctionnalités.

Actif
)}
); } export default DashboardPage;