"use client"; import React, { useEffect, useMemo, useState } from 'react'; import Link from 'next/link'; import { useParams, useRouter } from 'next/navigation'; import { ArrowLeft, MapPin, Globe, Mail, Phone, CheckCircle, Star, Facebook, Linkedin, Instagram, Play, Share2, Send, Award, Quote, MessageCircle, Lock, Loader2 } from 'lucide-react'; import { MOCK_BUSINESSES, MOCK_OFFERS } from '../../../lib/mockData'; import { Business, OfferType } from '../../../types'; import { toast } from 'react-hot-toast'; import { useUser } from '../../../components/UserProvider'; const BusinessDetailPage = () => { const { id } = useParams(); const router = useRouter(); const { user } = useUser(); const [business, setBusiness] = useState(null); const [loading, setLoading] = useState(true); const [existingConversationId, setExistingConversationId] = useState(null); const [contactForm, setContactForm] = useState({ name: '', email: '', message: '' }); const [formStatus, setFormStatus] = useState<'idle' | 'sending' | 'success'>('idle'); const businessOffers = useMemo(() => { if (!business) return []; // If the business has its own offers (from DB), use them if (business.offers && business.offers.length > 0) return business.offers; // Otherwise fallback to mock offers for mock businesses return MOCK_OFFERS.filter(o => o.businessId === id && o.active); }, [business, id]); useEffect(() => { window.scrollTo(0, 0); const loadBusiness = async () => { setLoading(true); // 1. Try Mock Data First (Instant) const mock = MOCK_BUSINESSES.find(b => b.id === id); if (mock) { setBusiness(mock); setLoading(false); return; } // 2. Try API (Database) try { const res = await fetch(`/api/businesses/${id}`); if (res.ok) { const data = await res.json(); setBusiness(data); // 3. Track view event // Only track if not owner const currentUserStr = localStorage.getItem('afro_user'); const currentUser = currentUserStr ? JSON.parse(currentUserStr) : null; if (!currentUser || currentUser.id !== data.ownerId) { fetch('/api/analytics', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ type: 'BUSINESS_VIEW', path: window.location.pathname, label: data.name, metadata: { businessId: data.id, businessName: data.name, userId: currentUser?.id || 'anonymous' } }) }).catch(console.error); } // Also increment views count in DB (Legacy support) fetch(`/api/businesses/${id}/view`, { method: 'POST' }).catch(console.error); } else { setBusiness(null); } } catch (err) { console.error("Error fetching business:", err); setBusiness(null); } finally { setLoading(false); } }; if (id) loadBusiness(); }, [id]); useEffect(() => { const checkExistingConversation = async () => { if (!user || user.id === 'undefined' || !business?.id) return; try { const res = await fetch(`/api/conversations?businessId=${business.id}`, { headers: { 'x-user-id': user.id } }); const data = await res.json(); if (Array.isArray(data) && data.length > 0) { setExistingConversationId(data[0].id); } } catch (error) { console.error('Error checking existing conversation:', error); } }; if (user && business) checkExistingConversation(); }, [user, business]); if (loading) { return (

Chargement du profil...

); } if (!business) { return (

Entreprise introuvable

Retour à l'annuaire
); } // Helper to get YouTube embed URL const getEmbedUrl = (url: string) => { const regExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|&v=)([^#&?]*).*/; const match = url.match(regExp); return (match && match[2].length === 11) ? `https://www.youtube.com/embed/${match[2]}` : null; }; const videoEmbedUrl = business.videoUrl ? getEmbedUrl(business.videoUrl) : null; const handleTrackEvent = async (type: string, label?: string) => { if (!business?.id) return; // Don't track if the current user is the owner if (user && user.id === business.ownerId) return; try { fetch('/api/analytics', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ type, path: window.location.pathname, label: label || business.name, metadata: { businessId: business.id, businessName: business.name, userId: user?.id || 'anonymous' } }) }); } catch (e) { console.error('Analytics error:', e); } }; const handleContactSubmit = async (e: React.FormEvent) => { e.preventDefault(); if (!user) { toast.error('Veuillez vous connecter pour envoyer un message'); router.push('/login'); return; } setFormStatus('sending'); try { const res = await fetch('/api/messages', { method: 'POST', headers: { 'Content-Type': 'application/json', 'x-user-id': user.id }, body: JSON.stringify({ businessId: business.id, content: contactForm.message }) }); const data = await res.json(); if (!data.error) { // Track contact event handleTrackEvent('BUSINESS_CONTACT_CLICK', 'Message Sent'); setFormStatus('success'); toast.success('Message envoyé ! Redirection vers votre messagerie...'); setContactForm({ ...contactForm, message: '' }); setTimeout(() => { router.push('/dashboard?view=messages'); // Hypothetical view param handle later }, 2000); } else { toast.error(data.error); setFormStatus('idle'); } } catch (error) { toast.error("Erreur lors de l'envoi"); setFormStatus('idle'); } }; return (
{/* Header Banner */}
Retour
{/* Profile Header */}
{business.name} {business.isFeatured && (
)}

{business.name}

{business.verified && }
{business.category}
{business.isFeatured && (
ENTREPRENEUR DU MOIS
)}
Contacter
{business.location}
{business.rating} ({business.viewCount} vues)
{business.tags.map(tag => ( #{tag} ))}
{/* Left Column: Main Content */}
{/* Presentation */}

À propos

{business.description}

{/* Founder Section (Specifically for Featured or if data exists) */} {(business.founderName || business.founderImageUrl) && (

Le Fondateur

{business.founderImageUrl && ( {business.founderName} )}

{business.founderName}

CEO & Fondateur

"Notre mission est d'apporter des solutions concrètes et adaptées aux réalités locales, tout en visant l'excellence internationale."

{business.keyMetric && (
🚀 {business.keyMetric}
)}
)} {/* Video */} {videoEmbedUrl && (

Présentation Vidéo

)} {/* Offers */} {businessOffers.length > 0 && (

Produits & Services

{businessOffers.map(offer => (
{offer.title} {offer.type === OfferType.PRODUCT ? 'Produit' : 'Service'}

{offer.title}

{new Intl.NumberFormat('fr-FR').format(offer.price)} {offer.currency}

))}
)}
{/* Right Column: Sidebar */}
{/* Contact Card */}

Contact

{/* Contact Section */}

Discuter avec l'entrepreneur

{existingConversationId ? (

Vous avez déjà une discussion en cours avec cet entrepreneur.

Continuer la discussion
) : formStatus === 'success' ? (

Message envoyé !

Redirection vers votre messagerie...

) : (