Spaces:
Runtime error
Runtime error
Download src/App.tsx from lasource87/bot: direct link, hf CLI and curl.
- Browser
- Download file 239 kB
-
https://huggingface.co/spaces/lasource87/bot/resolve/main/src/App.tsx
- Command line
-
hf download hf://spaces/lasource87/bot/src/App.tsx
-
curl -L -o App.tsx https://huggingface.co/spaces/lasource87/bot/resolve/main/src/App.tsx
239 kB
import React, { useEffect, useState, useMemo, useRef } from 'react';
import { BrowserRouter as Router, Routes, Route, useNavigate, useParams, Link, useLocation, Navigate } from 'react-router-dom';
import { supabase, getAppConfig } from './lib/supabase';
import { Category, Product, ProductPrice, ShopConfig, CartItem } from './types';
import {
ShoppingCart,
ArrowLeft,
Package,
Info,
ChevronDown,
LayoutGrid,
MessageSquare,
ExternalLink,
Leaf,
Plus,
Minus,
Trash2,
MapPin,
Check,
Send,
Search,
Loader2,
Heart,
ShieldCheck,
ChevronRight,
Settings,
Save,
X as CloseIcon,
Eye,
EyeOff,
Power,
Bell,
Users,
FileText,
Layout,
RefreshCw,
Truck,
UserCheck,
ImagePlus,
ShieldAlert,
Skull,
Terminal,
AlertTriangle,
CheckCircle2,
XCircle,
BarChart3,
Download,
Edit,
ChevronLeft,
Clock,
Globe,
Cpu,
Activity,
Shield,
Lock,
ClipboardList,
User,
Calendar,
History,
Navigation
} from 'lucide-react';
import { motion, AnimatePresence, useScroll, useTransform, Reorder } from 'motion/react';
import { clsx, type ClassValue } from 'clsx';
import { twMerge } from 'tailwind-merge';
const cn = (...inputs: ClassValue[]) => {
return twMerge(clsx(inputs));
};
const darkenColor = (hex: string, percent: number) => {
const num = parseInt(hex.replace('#', ''), 16);
const amt = Math.round(2.55 * percent);
const R = (num >> 16) - amt;
const G = (num >> 8 & 0x00FF) - amt;
const B = (num & 0x0000FF) - amt;
return '#' + (0x1000000 + (R < 255 ? R < 0 ? 0 : R : 255) * 0x10000 + (G < 255 ? G < 0 ? 0 : G : 255) * 0x100 + (B < 255 ? B < 0 ? 0 : B : 255)).toString(16).slice(1);
};
// --- Components ---
const BackgroundParticles = () => {
return (
<div className="fixed inset-0 pointer-events-none overflow-hidden z-0">
{/* Nebula Glows */}
<motion.div
animate={{
scale: [1, 1.2, 1],
opacity: [0.1, 0.2, 0.1],
x: [-20, 20, -20],
y: [-20, 20, -20],
}}
transition={{ duration: 15, repeat: Infinity, ease: "easeInOut" }}
className="absolute top-[-10%] left-[-10%] w-[60%] h-[60%] bg-accent/10 rounded-full blur-[120px]"
/>
<motion.div
animate={{
scale: [1.2, 1, 1.2],
opacity: [0.05, 0.15, 0.05],
x: [20, -20, 20],
y: [20, -20, 20],
}}
transition={{ duration: 20, repeat: Infinity, ease: "easeInOut" }}
className="absolute bottom-[-10%] right-[-10%] w-[50%] h-[50%] bg-accent/5 rounded-full blur-[100px]"
/>
{/* Standard Stars */}
{[...Array(80)].map((_, i) => (
<motion.div
key={`star-${i}`}
initial={{
opacity: Math.random() * 0.4,
x: Math.random() * (typeof window !== 'undefined' ? window.innerWidth : 400),
y: Math.random() * (typeof window !== 'undefined' ? window.innerHeight : 800),
scale: Math.random() * 0.6 + 0.2,
}}
animate={{
y: [null, Math.random() * -250 - 150],
opacity: [null, 0],
scale: [null, Math.random() * 0.3 + 0.1]
}}
transition={{
duration: Math.random() * 15 + 15,
repeat: Infinity,
ease: "linear",
delay: Math.random() * 30
}}
className={cn(
"absolute w-1 h-1 rounded-full",
i % 5 === 0 ? "bg-white" : "bg-accent"
)}
/>
))}
{/* Shooting Stars */}
{[...Array(3)].map((_, i) => (
<motion.div
key={`shooting-star-${i}`}
initial={{
x: "-10%",
y: Math.random() * 40 + "%",
opacity: 0,
scaleX: 10,
scaleY: 0.5,
rotate: -25
}}
animate={{
x: "110%",
y: (Math.random() * 60 + 20) + "%",
opacity: [0, 1, 0],
}}
transition={{
duration: Math.random() * 1 + 1,
repeat: Infinity,
repeatDelay: Math.random() * 10 + 5,
ease: "easeIn",
delay: i * 4
}}
className="absolute w-12 h-[1px] bg-gradient-to-r from-transparent via-accent to-transparent"
/>
))}
</div>
);
};
const ImageWithFallback = ({ src, alt, className, forceImageOnly, ...props }: React.ImgHTMLAttributes<HTMLImageElement> & { forceImageOnly?: boolean }) => {
const [error, setError] = useState(false);
const [loading, setLoading] = useState(true);
const [isInView, setIsInView] = useState(false);
const containerRef = useRef<HTMLDivElement>(null);
const videoRef = useRef<HTMLVideoElement>(null);
const getMediaInfo = (s: string | null | undefined) => {
if (!s) return { url: '', type: 'image', thumbnail: '' };
try {
const media = JSON.parse(s);
if (Array.isArray(media) && media.length > 0) {
let selectedMedia = media[0];
if (forceImageOnly) {
const firstImage = media.find(m => {
const url = typeof m === 'string' ? m : m.url;
return url && !url.match(/\.(mp4|webm|ogg|mov)$/i);
});
if (firstImage) {
selectedMedia = firstImage;
}
}
const first = typeof selectedMedia === 'string'
? { url: selectedMedia, type: selectedMedia.match(/\.(mp4|webm|ogg|mov)$/i) ? 'video' : 'image' }
: { ...selectedMedia };
// Cherche une miniature ou la première image de la liste pour servir de poster
let thumbnail = first.thumbnail || first.poster || '';
if (!thumbnail && Array.isArray(media)) {
const firstImage = media.find(m => {
const url = typeof m === 'string' ? m : m.url;
return url && !url.match(/\.(mp4|webm|ogg|mov)$/i);
});
if (firstImage) {
thumbnail = typeof firstImage === 'string' ? firstImage : firstImage.url;
}
}
if (forceImageOnly && first.type === 'video') {
return { url: thumbnail || `${first.url}#t=0.1`, type: 'image', thumbnail };
}
return { ...first, thumbnail };
}
} catch (e) {}
const isVideo = s.match(/\.(mp4|webm|ogg|mov)$/i);
if (forceImageOnly && isVideo) {
return { url: `${s}#t=0.1`, type: 'image', thumbnail: `${s}#t=0.1` };
}
return { url: s, type: isVideo ? 'video' : 'image', thumbnail: isVideo ? `${s}#t=0.1` : '' };
};
const media = getMediaInfo(src);
useEffect(() => {
const observer = new IntersectionObserver(
(entries) => {
entries.forEach((entry) => {
setIsInView(entry.isIntersecting);
});
},
{
threshold: 0.01,
rootMargin: '50px' // Charge un peu avant pour plus de fluidité
}
);
if (containerRef.current) observer.observe(containerRef.current);
return () => observer.disconnect();
}, []);
useEffect(() => {
if (media.type === 'video' && videoRef.current) {
if (isInView) {
videoRef.current.play().catch(() => {});
} else {
videoRef.current.pause();
}
}
}, [isInView, media.type]);
return (
<div ref={containerRef} className={cn("relative overflow-hidden bg-bg-card", className)}>
{loading && (
<div className="absolute inset-0 flex items-center justify-center bg-bg-card animate-pulse">
<Package className="w-8 h-8 text-white/5" />
</div>
)}
{media.type === 'video' ? (
<video
ref={videoRef}
src={isInView ? media.url : undefined}
poster={media.thumbnail}
className={cn(
"w-full h-full object-cover transition-opacity duration-300",
loading ? "opacity-0" : "opacity-100",
error ? "hidden" : "block"
)}
muted
loop
playsInline
onLoadedData={() => setLoading(false)}
onError={() => {
setError(true);
setLoading(false);
}}
/>
) : (
<img
{...props}
src={error || !media.url ? undefined : media.url}
alt={alt}
className={cn(
"w-full h-full object-cover transition-opacity duration-300",
loading ? "opacity-0" : "opacity-100",
error ? "hidden" : "block"
)}
onLoad={() => setLoading(false)}
onError={() => {
setError(true);
setLoading(false);
}}
referrerPolicy="no-referrer"
/>
)}
{error && (
<div className="absolute inset-0 flex flex-col items-center justify-center bg-bg-card p-4 text-center">
<Package className="w-10 h-10 text-white/10 mb-2" />
<p className="text-[10px] text-text-muted font-bold uppercase tracking-wider">Média non disponible</p>
</div>
)}
</div>
);
};
const BottomNav = ({ cartCount, config }: { cartCount: number, config: ShopConfig | null }) => {
const location = useLocation();
const navigate = useNavigate();
const handleContact = () => {
const username = import.meta.env.VITE_ORDER_MANAGER_USERNAME || config?.orderManager?.replace('@', '') || 'username';
const url = `https://t.me/${username}`;
if (window.Telegram?.WebApp) {
window.Telegram.WebApp.openTelegramLink(url);
} else {
window.open(url, '_blank');
}
};
const tgUser = (window as any).Telegram?.WebApp?.initDataUnsafe?.user;
const userId = tgUser?.id?.toString() || '';
const isPrivileged = config && (userId === config.adminId || userId === config.managerChatId);
const tabs = [
{ id: 'catalogue', label: 'Catalogue', icon: LayoutGrid, onClick: () => navigate('/'), isActive: location.pathname === '/' },
{ id: 'cart', label: 'Panier', icon: ShoppingCart, onClick: () => navigate('/cart'), isActive: location.pathname === '/cart' },
{ id: 'infos', label: 'Infos', icon: Info, onClick: () => navigate('/infos'), isActive: location.pathname === '/infos' },
{ id: 'contact', label: 'Contact', icon: MessageSquare, onClick: handleContact, isActive: false },
{
id: 'orders',
label: 'Profil',
icon: tgUser?.photo_url ? () => (
<div className="w-5 h-5 rounded-full overflow-hidden border border-accent/30">
<img src={tgUser.photo_url} alt="Profile" className="w-full h-full object-cover" referrerPolicy="no-referrer" />
</div>
) : ClipboardList,
onClick: () => navigate('/orders'),
isActive: location.pathname === '/orders'
},
];
return (
<nav className="fixed bottom-6 left-1/2 -translate-x-1/2 z-[60] glass px-6 py-2.5 flex justify-around items-center w-[95%] max-w-md rounded-full premium-shadow">
{tabs.map((tab) => {
const Icon = tab.icon;
return (
<button
key={tab.id}
onClick={tab.onClick}
className={cn(
"flex flex-col items-center gap-1.5 transition-all relative",
tab.isActive ? "text-accent" : "text-text-muted hover:text-white"
)}
>
{tab.isActive && (
<motion.div
layoutId="activeTab"
className="absolute -top-1 w-1 h-1 bg-accent rounded-full"
/>
)}
<div className="relative">
{typeof Icon === 'function' ? <Icon /> : <Icon className={cn("w-5 h-5", tab.isActive && "drop-shadow-[0_0_8px_rgba(16,185,129,0.5)]")} />}
{tab.id === 'cart' && cartCount > 0 && (
<span className="absolute -top-2 -right-2 bg-accent text-white text-[8px] font-black w-4 h-4 rounded-full flex items-center justify-center shadow-lg border border-bg-dark">
{cartCount}
</span>
)}
</div>
<span className="text-[8px] font-black uppercase tracking-[0.2em] font-display">{tab.label}</span>
</button>
);
})}
</nav>
);
};
const SplashScreen = ({ config }: { config: ShopConfig | null }) => {
const [progress, setProgress] = useState(0);
const accentColor = config?.accentColor || '#A855F7';
useEffect(() => {
const interval = setInterval(() => {
setProgress(prev => {
if (prev >= 100) {
clearInterval(interval);
return 100;
}
return prev + 1;
});
}, 25);
return () => clearInterval(interval);
}, []);
return (
<motion.div
initial={{ opacity: 1 }}
exit={{
opacity: 0,
scale: 1.1,
filter: "blur(20px)",
transition: { duration: 0.8, ease: "easeInOut" }
}}
className="fixed inset-0 z-[100] bg-black flex flex-col items-center justify-center overflow-hidden"
style={{ '--accent': accentColor } as any}
>
{/* Background Grid & Energy */}
<div className="absolute inset-0 z-0">
<div
className="absolute inset-0 bg-[linear-gradient(rgba(255,255,255,0.03)_1px,transparent_1px),linear-gradient(90deg,rgba(255,255,255,0.03)_1px,transparent_1px)] bg-[size:40px_40px] [mask-image:radial-gradient(ellipse_60%_50%_at_50%_50%,#000_70%,transparent_100%)]"
/>
<motion.div
animate={{
opacity: [0.1, 0.2, 0.1],
scale: [1, 1.2, 1]
}}
transition={{ duration: 5, repeat: Infinity, ease: "easeInOut" }}
className="absolute inset-0"
style={{ background: `radial-gradient(circle at 50% 50%, ${accentColor}33, transparent 70%)` }}
/>
</div>
{/* Central Core */}
<div className="relative flex flex-col items-center z-10">
<motion.div
initial={{ scale: 0.5, opacity: 0 }}
animate={{ scale: 1, opacity: 1 }}
transition={{ duration: 1, ease: [0.16, 1, 0.3, 1] }}
className="relative"
>
{/* Multi-Layered Neon Rings */}
<motion.div
animate={{ rotate: 360 }}
transition={{ duration: 10, repeat: Infinity, ease: "linear" }}
className="absolute -inset-20 border-[2px] rounded-full"
style={{ borderColor: `${accentColor}66`, boxShadow: `0 0 40px ${accentColor}4d` }}
/>
<motion.div
animate={{ rotate: -360 }}
transition={{ duration: 15, repeat: Infinity, ease: "linear" }}
className="absolute -inset-24 border rounded-full border-dashed"
style={{ borderColor: `${accentColor}33` }}
/>
<motion.div
animate={{ rotate: 180 }}
transition={{ duration: 20, repeat: Infinity, ease: "linear" }}
className="absolute -inset-28 border-[0.5px] rounded-full"
style={{ borderColor: `${accentColor}1a` }}
/>
{/* Scanning Light Ring */}
<motion.div
animate={{ rotate: 360 }}
transition={{ duration: 3, repeat: Infinity, ease: "linear" }}
className="absolute -inset-20 rounded-full opacity-40"
style={{ background: `conic-gradient(from 0deg, transparent 0deg, ${accentColor}66 180deg, transparent 360deg)` }}
/>
{/* Intense Pulsing Glow */}
<motion.div
animate={{
opacity: [0.2, 0.4, 0.2],
scale: [0.8, 1.1, 0.8]
}}
transition={{ duration: 2, repeat: Infinity, ease: "easeInOut" }}
className="absolute inset-0 blur-[80px] rounded-full"
style={{ backgroundColor: `${accentColor}66` }}
/>
{/* Main Logo Container */}
<motion.div
whileHover={{ scale: 1.05 }}
className="relative w-72 h-72 rounded-full p-[2px] shadow-2xl"
style={{
background: `linear-gradient(135deg, ${accentColor}, ${accentColor}88, ${accentColor}44)`,
boxShadow: `0 0 80px ${accentColor}4d`
}}
>
<div className="absolute inset-0 bg-black rounded-full overflow-hidden">
<ImageWithFallback
src={config?.shopLogo || ''}
alt="Logo"
className="w-full h-full object-cover rounded-full relative z-10"
style={{ filter: `drop-shadow(0 0 30px ${accentColor}80)` }}
/>
{/* High-speed scan line */}
<motion.div
animate={{ y: ["-100%", "200%"] }}
transition={{ duration: 2, repeat: Infinity, ease: "linear" }}
className="absolute inset-x-0 h-1/2"
style={{ background: `linear-gradient(to bottom, transparent, ${accentColor}33, transparent)` }}
/>
</div>
</motion.div>
</motion.div>
{/* Text Section */}
<div className="mt-20 flex flex-col items-center gap-10">
<motion.div
initial={{ y: 30, opacity: 0 }}
animate={{ y: 0, opacity: 1 }}
transition={{ delay: 0.4, duration: 0.8 }}
className="relative text-center"
>
<motion.h1
animate={{
textShadow: [
`0 0 20px ${accentColor}cc`,
`0 0 40px ${accentColor}`,
`0 0 20px ${accentColor}cc`
]
}}
transition={{ duration: 2, repeat: Infinity }}
className="text-7xl font-black text-white tracking-tighter uppercase italic leading-none"
>
{config?.shopName || 'QUALITÉ'}
</motion.h1>
<div className="mt-3 flex items-center justify-center gap-6">
<div className="h-[1px] w-16" style={{ background: `linear-gradient(to right, transparent, ${accentColor}, transparent)` }} />
<span className="text-[10px] font-black uppercase tracking-[0.8em] italic" style={{ color: accentColor }}>SERVICE PREMIUM</span>
<div className="h-[1px] w-16" style={{ background: `linear-gradient(to left, transparent, ${accentColor}, transparent)` }} />
</div>
</motion.div>
{/* Progress Bar Container */}
<div className="w-80 space-y-5">
<div className="relative h-[3px] w-full bg-white/5 rounded-full overflow-hidden">
<motion.div
initial={{ width: 0 }}
animate={{ width: `${progress}%` }}
className="absolute inset-y-0 left-0"
style={{
background: `linear-gradient(to right, ${accentColor}, ${accentColor}cc, ${accentColor}88)`,
boxShadow: `0 0 20px ${accentColor}`
}}
/>
{/* Progress Glow Tip */}
<motion.div
style={{ left: `${progress}%` }}
className="absolute top-1/2 -translate-y-1/2 w-4 h-4 bg-white blur-sm rounded-full opacity-50"
/>
</div>
<div className="flex justify-between items-end px-1">
<div className="flex flex-col gap-1">
<span className="text-[8px] font-bold uppercase tracking-[0.3em] opacity-60" style={{ color: accentColor }}>System Initialization</span>
<div className="flex items-center gap-2">
<div className="w-1.5 h-1.5 rounded-full animate-ping" style={{ backgroundColor: accentColor }} />
<span className="text-[10px] font-black text-white uppercase tracking-widest">Loading Assets...</span>
</div>
</div>
<div className="flex flex-col items-end">
<span className="text-2xl font-black text-white italic tracking-tighter leading-none">
{progress}<span className="text-xs ml-0.5" style={{ color: accentColor }}>%</span>
</span>
</div>
</div>
</div>
</div>
</div>
{/* Final Exit Flash */}
<motion.div
initial={{ opacity: 0 }}
exit={{
opacity: [0, 1, 0],
transition: { duration: 0.3 }
}}
className="absolute inset-0 bg-white z-[110] pointer-events-none"
/>
</motion.div>
);
};
const Home = ({
config,
fulfillmentType,
setFulfillmentType,
favorites,
toggleFavorite
}: {
config: ShopConfig | null,
fulfillmentType: 'delivery' | 'meetup' | null,
setFulfillmentType: (type: 'delivery' | 'meetup' | null) => void,
favorites: string[],
toggleFavorite: (productId: string, onUpdate?: (isLiked: boolean) => void) => void
}) => {
const [categories, setCategories] = useState<Category[]>([]);
const [products, setProducts] = useState<(Product & { prices?: ProductPrice[] })[]>([]);
const [loading, setLoading] = useState(true);
const [selectedCategory, setSelectedCategory] = useState<string | null>(null);
const [searchQuery, setSearchQuery] = useState('');
useEffect(() => {
const fetchData = async () => {
const [catRes, prodRes, priceRes] = await Promise.all([
supabase.from('categories').select('*').order('display_order', { ascending: true }),
supabase.from('products').select('*').order('display_order', { ascending: true }),
supabase.from('product_prices').select('*')
]);
if (catRes.data) setCategories(catRes.data);
if (prodRes.data) {
const prodsWithPrices = prodRes.data.map(p => ({
...p,
prices: (priceRes.data || []).filter((pr: any) => pr.product_id === p.id).sort((a: any, b: any) => a.price - b.price)
}));
setProducts(prodsWithPrices);
}
setLoading(false);
};
fetchData();
}, []);
// Filter categories and products based on fulfillment type and search
const activeFulfillment = fulfillmentType || 'delivery';
const { scrollY } = useScroll();
// Header animations
const headerOpacity = useTransform(scrollY, [0, 100], [1, 0]);
const headerScale = useTransform(scrollY, [0, 100], [1, 0.9]);
const stickyLogoOpacity = useTransform(scrollY, [120, 180], [0, 1]);
const stickyLogoScale = useTransform(scrollY, [120, 180], [0.5, 1]);
const categoriesTranslateX = useTransform(scrollY, [120, 180], [0, 45]);
const filteredCategories = categories.filter(c => (c.type || 'delivery') === activeFulfillment);
const filteredProducts = products.filter(p => (p.type || 'delivery') === activeFulfillment)
.filter(p => !selectedCategory || p.category_id === selectedCategory)
.filter(p => p.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
p.description?.toLowerCase().includes(searchQuery.toLowerCase()));
if (loading) return (
<div className="flex items-center justify-center min-h-screen bg-bg-dark">
<BackgroundParticles />
</div>
);
if (config?.isMeetupEnabled && !fulfillmentType) {
return (
<div className="min-h-screen flex flex-col items-center justify-center p-6 space-y-12 bg-bg-dark relative overflow-hidden">
<BackgroundParticles />
<motion.div
initial={{ opacity: 0, scale: 0.8 }}
animate={{ opacity: 1, scale: 1 }}
className="text-center space-y-6 relative z-10"
>
{config?.shopLogo ? (
<div className="w-32 h-32 rounded-full p-1 bg-gradient-to-br from-accent to-accent/20 shadow-[0_0_40px_rgba(16,185,129,0.3)] mx-auto mb-8">
<ImageWithFallback src={config.shopLogo} alt="Logo" className="w-full h-full rounded-full border-2 border-bg-dark" />
</div>
) : (
<div className="w-24 h-24 bg-accent/10 rounded-3xl flex items-center justify-center mx-auto mb-8 border border-accent/20">
<Package className="w-10 h-10 text-accent" />
</div>
)}
<div className="space-y-2">
<h1 className="text-xl font-black text-white uppercase tracking-[0.2em] font-display">
Mode de Réception
</h1>
<div className="h-1 w-12 bg-accent mx-auto rounded-full" />
</div>
<p className="text-text-muted text-[10px] font-bold uppercase tracking-widest max-w-[200px] mx-auto leading-relaxed opacity-60">
Choisissez votre préférence de retrait
</p>
</motion.div>
<div className="grid grid-cols-2 gap-4 w-full max-w-sm relative z-10">
<motion.button
whileHover={{ scale: 1.05, translateY: -5 }}
whileTap={{ scale: 0.95 }}
onClick={() => setFulfillmentType('delivery')}
className="group relative overflow-hidden bg-bg-card/40 backdrop-blur-xl border border-white/5 p-8 rounded-[2.5rem] flex flex-col items-center gap-4 transition-all hover:border-accent/40 hover:shadow-[0_20px_40px_rgba(0,0,0,0.4)]"
>
<div className="absolute inset-0 bg-gradient-to-br from-accent/10 to-transparent opacity-0 group-hover:opacity-100 transition-opacity" />
<div className="w-12 h-12 bg-accent/10 rounded-full flex items-center justify-center group-hover:bg-accent group-hover:text-white transition-all">
<Package className="w-6 h-6 text-accent group-hover:text-white" />
</div>
<div className="text-center">
<span className="block text-xs font-black text-white uppercase tracking-tight font-display mb-1">Livraison</span>
<span className="block text-[7px] text-text-muted font-bold uppercase tracking-widest opacity-40">À domicile</span>
</div>
</motion.button>
<motion.button
whileHover={{ scale: 1.05, translateY: -5 }}
whileTap={{ scale: 0.95 }}
onClick={() => setFulfillmentType('meetup')}
className="group relative overflow-hidden bg-bg-card/40 backdrop-blur-xl border border-white/5 p-8 rounded-[2.5rem] flex flex-col items-center gap-4 transition-all hover:border-accent/40 hover:shadow-[0_20px_40px_rgba(0,0,0,0.4)]"
>
<div className="absolute inset-0 bg-gradient-to-br from-accent/10 to-transparent opacity-0 group-hover:opacity-100 transition-opacity" />
<div className="w-12 h-12 bg-accent/10 rounded-full flex items-center justify-center group-hover:bg-accent group-hover:text-white transition-all">
<MapPin className="w-6 h-6 text-accent group-hover:text-white" />
</div>
<div className="text-center">
<span className="block text-xs font-black text-white uppercase tracking-tight font-display mb-1">Meet-up</span>
<span className="block text-[7px] text-text-muted font-bold uppercase tracking-widest opacity-40">Main à main</span>
</div>
</motion.button>
</div>
<p className="text-[8px] text-text-muted/30 font-black uppercase tracking-[0.6em] relative z-10 pt-12">
{config?.shopName || 'HFT FRANCE'} • PREMIUM SERVICE
</p>
</div>
);
}
return (
<motion.div
initial={{ opacity: 0, scale: 0.8, filter: "blur(20px)" }}
animate={{ opacity: 1, scale: 1, filter: "blur(0px)" }}
transition={{ duration: 1, ease: [0.23, 1, 0.32, 1], delay: 0.2 }}
className="pt-0 pb-32 bg-transparent min-h-screen"
>
{/* Header Section - Video Style */}
<div className="bg-transparent pt-0 pb-0 px-0 text-center space-y-0 relative overflow-hidden min-h-[150px] flex flex-col justify-center rounded-b-[3rem]">
{/* Banner Background */}
{config?.shopBanner && (
<div className="absolute inset-0 z-0">
<img
src={config.shopBanner}
alt="Banner"
className="w-full h-full object-cover opacity-85"
/>
<div className="absolute inset-0 bg-gradient-to-b from-bg-dark/0 via-bg-dark/20 to-bg-dark/60" />
</div>
)}
<div className="absolute inset-0 pointer-events-none overflow-hidden">
<motion.div
animate={{
scale: [1, 1.2, 1],
opacity: [0.1, 0.2, 0.1],
}}
transition={{ duration: 10, repeat: Infinity }}
className="absolute top-0 left-1/2 -translate-x-1/2 w-full h-full bg-[radial-gradient(circle_at_50%_0%,rgba(16,185,129,0.15),transparent_70%)]"
/>
</div>
<motion.div
style={{ opacity: headerOpacity, scale: headerScale }}
className="flex flex-col items-center gap-0 relative z-10 py-4"
>
<motion.div
initial={{ scale: 0.8, opacity: 0 }}
animate={{ scale: 1, opacity: 1 }}
className="relative"
>
<div className="w-16 h-16 rounded-full border-2 border-accent/30 p-1 bg-bg-card/40 shadow-2xl relative z-10">
{config?.shopLogo ? (
<img src={config.shopLogo} alt="Logo" className="w-full h-full object-cover rounded-full" />
) : (
<div className="w-full h-full bg-white/5 rounded-full flex items-center justify-center">
<Package className="w-5 h-5 text-accent/40" />
</div>
)}
</div>
<motion.div
animate={{ scale: [1, 1.2, 1], opacity: [0.3, 0.6, 0.3] }}
transition={{ duration: 3, repeat: Infinity }}
className="absolute inset-0 bg-accent rounded-full blur-xl -z-10"
/>
</motion.div>
<h1 className="text-lg font-black text-white tracking-tight uppercase font-display">
{config?.shopName || 'HFT FRANCE'}
</h1>
{config?.isMeetupEnabled && (
<button
onClick={() => {
setFulfillmentType(null);
}}
className="mt-2 px-3 py-1 glass rounded-full flex items-center gap-2 border border-accent/20 active:scale-95 transition-all"
>
<div className="w-1.5 h-1.5 rounded-full bg-accent animate-pulse" />
<span className="text-[8px] font-black text-accent uppercase tracking-widest">
{activeFulfillment === 'meetup' ? 'Mode Meet-up' : 'Mode Livraison'}
</span>
<ChevronRight className="w-2.5 h-2.5 text-accent/40" />
</button>
)}
</motion.div>
</div>
{/* Content Section - Rounded Sheet */}
<div className="bg-transparent -mt-12 rounded-t-[4rem] relative z-20 pt-10">
{/* Categories Section - Video Style */}
<div className="sticky top-0 z-40 px-4 py-2">
<div className="glass rounded-full border border-white/5 shadow-xl overflow-hidden relative">
{/* Sticky Logo - Appears on scroll */}
<motion.div
style={{ opacity: stickyLogoOpacity, scale: stickyLogoScale }}
className="absolute left-3 top-1/2 -translate-y-1/2 w-8 h-8 rounded-full border border-accent/30 p-0.5 bg-bg-card shadow-lg z-10"
>
{config?.shopLogo ? (
<img src={config.shopLogo} alt="Logo" className="w-full h-full object-cover rounded-full" />
) : (
<div className="w-full h-full bg-white/5 rounded-full flex items-center justify-center">
<Package className="w-3 h-3 text-accent/40" />
</div>
)}
</motion.div>
<motion.div
style={{ x: categoriesTranslateX }}
className="px-2 py-3 flex gap-2.5 overflow-x-auto no-scrollbar scroll-smooth"
>
<button
onClick={() => setSelectedCategory(null)}
className={cn(
"flex-shrink-0 px-6 py-2.5 rounded-full text-[10px] font-black uppercase tracking-widest transition-all duration-300 font-display border flex items-center gap-2",
!selectedCategory
? "bg-accent text-white border-accent shadow-[0_0_20px_rgba(16,185,129,0.3)]"
: "bg-bg-card/50 text-text-muted border-border hover:border-accent/30"
)}
>
<LayoutGrid className="w-3 h-3" />
Toutes les catégories
</button>
{filteredCategories.map(cat => (
<button
key={cat.id}
onClick={() => setSelectedCategory(cat.id)}
className={cn(
"flex-shrink-0 px-6 py-2.5 rounded-full text-[10px] font-black uppercase tracking-widest transition-all duration-300 font-display border",
selectedCategory === cat.id
? "bg-accent text-white border-accent shadow-[0_0_20px_rgba(16,185,129,0.3)]"
: "bg-bg-card/50 text-text-muted border-border hover:border-accent/30"
)}
>
{cat.name}
</button>
))}
</motion.div>
</div>
</div>
{/* Search Bar - Moved below categories */}
<div className="px-6 py-4">
<div className="relative max-w-sm mx-auto z-10">
<div className="absolute inset-y-0 left-4 flex items-center pointer-events-none">
<Search className="w-4 h-4 text-text-muted" />
</div>
<input
type="text"
placeholder="Rechercher un produit..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="w-full bg-bg-card/50 border border-border rounded-full py-3.5 pl-12 pr-4 text-xs font-bold text-white placeholder:text-text-muted/50 focus:outline-none focus:border-accent/50 transition-all backdrop-blur-md"
/>
</div>
</div>
{/* Products Grid - Video Style */}
<div className="px-4 py-6 grid grid-cols-2 gap-4">
<AnimatePresence mode="popLayout">
{filteredProducts.map((product) => (
<motion.div
layout
key={product.id}
initial={{ opacity: 0, scale: 0.9 }}
animate={{ opacity: 1, scale: 1 }}
exit={{ opacity: 0, scale: 0.9 }}
transition={{ duration: 0.4, ease: [0.23, 1, 0.32, 1] }}
>
<div className="group relative bg-bg-card/40 backdrop-blur-md rounded-[2.5rem] overflow-hidden border border-white/5 transition-all hover:border-accent/40 shadow-[0_0_20px_rgba(16,185,129,0.25)] hover:shadow-[0_20px_60px_rgba(0,0,0,0.6)] active:scale-[0.98]">
<Link to={`/product/${product.id}`} className="block">
<div className="aspect-square relative overflow-hidden">
<ImageWithFallback
src={product.image_url || undefined}
alt={product.name}
forceImageOnly={true}
className="w-full h-full group-hover:scale-110 transition-transform duration-1000 ease-out"
/>
{/* Badges */}
<div className="absolute top-4 left-4 flex flex-col gap-1.5">
<motion.div
initial={{ x: -20, opacity: 0 }}
animate={{ x: 0, opacity: 1 }}
className={cn(
"backdrop-blur-md px-2 py-0.5 rounded-full shadow-lg border border-white/10",
product.is_in_stock ? "bg-accent/90" : "bg-red-500/90"
)}
>
<span className="text-[8px] font-black text-white uppercase tracking-tighter">
{product.is_in_stock ? 'En stock' : 'Rupture'}
</span>
</motion.div>
</div>
{/* Gradient Overlay */}
<div className="absolute inset-0 bg-gradient-to-t from-bg-dark via-transparent to-transparent opacity-80" />
</div>
</Link>
{/* Heart Icon */}
<button
onClick={(e) => {
e.preventDefault();
toggleFavorite(product.id, (isLiked) => {
setProducts(prev => prev.map(p => {
if (p.id === product.id) {
return {
...p,
real_likes_count: (p.real_likes_count || 0) + (isLiked ? -1 : 1)
};
}
return p;
}));
});
}}
className="absolute top-4 right-4 z-20 flex items-center gap-1.5 px-3 py-2 rounded-full glass border-white/5 active:scale-90 transition-all hover:bg-white/10"
>
<motion.div
animate={{ scale: favorites.includes(product.id) ? [1, 1.2, 1] : 1 }}
transition={{ duration: 0.3 }}
>
<Heart
className={cn("w-3 h-3 transition-colors", favorites.includes(product.id) ? "fill-accent text-accent" : "text-white/60")}
strokeWidth={2.5}
/>
</motion.div>
<span className="text-[10px] font-black text-white/80">
{(product.fictitious_likes || 0) + (product.real_likes_count || 0)}
</span>
</button>
{/* Product Info - Video Style */}
<div className="p-5 space-y-3 relative">
<div className="space-y-1">
<h3 className="text-[11px] font-black text-white uppercase tracking-tight line-clamp-1 font-display group-hover:text-accent transition-colors">
{product.name}
</h3>
<p className="text-[9px] text-text-muted font-bold uppercase tracking-widest line-clamp-1 opacity-60">
{product.description || 'Qualité supérieure'}
</p>
</div>
<div className="flex items-center justify-between gap-2 pt-1">
<div className="flex flex-col">
<span className="text-sm font-black text-white font-display tracking-tight">
{product.prices?.[0]?.price || 0}€
</span>
</div>
<Link
to={`/product/${product.id}`}
className="bg-accent/10 hover:bg-accent/20 p-2.5 rounded-xl border border-accent/20 transition-colors group-hover:bg-accent group-hover:text-white"
>
<Plus className="w-4 h-4 text-accent group-hover:text-white" />
</Link>
</div>
</div>
</div>
</motion.div>
))}
</AnimatePresence>
</div>
{filteredProducts.length === 0 && (
<div className="text-center py-20 px-10">
<Package className="w-12 h-12 text-text-muted mx-auto mb-4 opacity-20" />
<p className="text-text-muted font-bold uppercase text-[10px] tracking-widest">Aucun produit trouvé</p>
</div>
)}
</div>
</motion.div>
);
};
const ImageLightbox = ({ images, initialIndex = 0, onClose }: { images: string[]; initialIndex?: number; onClose: () => void }) => {
const [currentIndex, setCurrentIndex] = useState(initialIndex);
const handleNext = (e: React.MouseEvent) => {
e.stopPropagation();
setCurrentIndex((prev) => (prev + 1) % images.length);
};
const handlePrev = (e: React.MouseEvent) => {
e.stopPropagation();
setCurrentIndex((prev) => (prev - 1 + images.length) % images.length);
};
return (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
className="fixed inset-0 z-[100] bg-black/95 flex items-center justify-center p-4"
onClick={onClose}
>
<button
onClick={onClose}
className="absolute top-6 right-6 p-3 bg-white/10 rounded-full text-white hover:bg-white/20 transition-colors z-[110]"
>
<CloseIcon className="w-6 h-6" />
</button>
{images.length > 1 && (
<>
<button
onClick={handlePrev}
className="absolute left-6 p-3 bg-white/10 rounded-full text-white hover:bg-white/20 transition-colors z-[110]"
>
<ChevronLeft className="w-6 h-6" />
</button>
<button
onClick={handleNext}
className="absolute right-6 p-3 bg-white/10 rounded-full text-white hover:bg-white/20 transition-colors z-[110]"
>
<ChevronRight className="w-6 h-6" />
</button>
<div className="absolute bottom-10 left-1/2 -translate-x-1/2 flex gap-2 z-[110]">
{images.map((_, i) => (
<div
key={i}
className={cn(
"w-2 h-2 rounded-full transition-all",
i === currentIndex ? "bg-accent w-4" : "bg-white/20"
)}
/>
))}
</div>
</>
)}
<AnimatePresence mode="wait">
<motion.img
key={currentIndex}
initial={{ scale: 0.9, opacity: 0, x: 20 }}
animate={{ scale: 1, opacity: 1, x: 0 }}
exit={{ scale: 0.9, opacity: 0, x: -20 }}
src={images[currentIndex]}
alt=""
className="max-w-full max-h-[80vh] object-contain rounded-2xl shadow-2xl"
onClick={(e) => e.stopPropagation()}
/>
</AnimatePresence>
</motion.div>
);
};
const ProductDetail = ({ config, addToCart, favorites, toggleFavorite }: { config: ShopConfig | null, addToCart: (item: CartItem) => void, favorites: string[], toggleFavorite: (productId: string, onUpdate?: (isLiked: boolean) => void) => void }) => {
const { productId } = useParams();
const navigate = useNavigate();
const [product, setProduct] = useState<Product | null>(null);
const [prices, setPrices] = useState<ProductPrice[]>([]);
const [loading, setLoading] = useState(true);
const [addedPriceId, setAddedPriceId] = useState<string | null>(null);
const [currentImageIndex, setCurrentImageIndex] = useState(0);
const getProductImages = (imgUrl: string | null | undefined): { url: string, type: 'image' | 'video' }[] => {
if (!imgUrl) return [];
try {
const parsed = JSON.parse(imgUrl);
if (Array.isArray(parsed)) {
const media = parsed.map(item => typeof item === 'string' ? { url: item, type: item.match(/\.(mp4|webm|ogg|mov)$/i) ? 'video' : 'image' } : item);
// Trier pour mettre les vidéos en premier
return media.sort((a, b) => {
if (a.type === 'video' && b.type !== 'video') return -1;
if (a.type !== 'video' && b.type === 'video') return 1;
return 0;
});
}
} catch (e) {}
return imgUrl ? [{ url: imgUrl, type: imgUrl.match(/\.(mp4|webm|ogg|mov)$/i) ? 'video' : 'image' }] : [];
};
const productImages = getProductImages(product?.image_url);
useEffect(() => {
const fetchData = async () => {
const [prodRes, priceRes] = await Promise.all([
supabase.from('products').select('*').eq('id', productId).single(),
supabase.from('product_prices').select('*').eq('product_id', productId).order('price', { ascending: true })
]);
if (prodRes.data) setProduct(prodRes.data);
if (priceRes.data) setPrices(priceRes.data);
setLoading(false);
};
fetchData();
}, [productId]);
const handleAddToCart = (price: ProductPrice) => {
if (!product) return;
addToCart({
productId: product.id,
productName: product.name,
priceId: price.id,
quantityLabel: price.quantity,
price: price.price,
count: 1
});
setAddedPriceId(price.id);
setTimeout(() => setAddedPriceId(null), 2000);
};
if (loading) return (
<div className="flex items-center justify-center min-h-screen bg-bg-dark">
<div className="w-8 h-8 border-4 border-accent border-t-transparent rounded-full animate-spin"></div>
</div>
);
if (!product) return <div className="p-8 text-center text-red-500">Produit non trouvé.</div>;
return (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
className="flex flex-col min-h-screen bg-bg-dark pb-32"
>
{/* Immersive Product Image Header with Carousel */}
<div className="relative h-[65vh] w-full overflow-hidden">
<AnimatePresence mode="wait">
<motion.div
key={currentImageIndex}
initial={{ opacity: 0, scale: 1.1 }}
animate={{ opacity: 1, scale: 1 }}
exit={{ opacity: 0, scale: 0.9 }}
transition={{ duration: 0.6, ease: "easeInOut" }}
className="absolute inset-0"
>
<ImageWithFallback
src={JSON.stringify([productImages[currentImageIndex]])}
alt={product.name}
className="w-full h-full object-cover"
/>
</motion.div>
</AnimatePresence>
{/* Carousel Controls */}
{productImages.length > 1 && (
<>
<div className="absolute inset-y-0 left-0 flex items-center px-4 z-20">
<button
onClick={() => setCurrentImageIndex(prev => (prev - 1 + productImages.length) % productImages.length)}
className="w-10 h-10 rounded-full glass flex items-center justify-center text-white active:scale-90 transition-transform border border-white/10"
>
<ChevronLeft className="w-6 h-6" />
</button>
</div>
<div className="absolute inset-y-0 right-0 flex items-center px-4 z-20">
<button
onClick={() => setCurrentImageIndex(prev => (prev + 1) % productImages.length)}
className="w-10 h-10 rounded-full glass flex items-center justify-center text-white active:scale-90 transition-transform border border-white/10"
>
<ChevronRight className="w-6 h-6" />
</button>
</div>
{/* Dots */}
<div className="absolute bottom-24 left-1/2 -translate-x-1/2 flex gap-2 z-20">
{productImages.map((_, idx) => (
<button
key={idx}
onClick={() => setCurrentImageIndex(idx)}
className={cn(
"w-2 h-2 rounded-full transition-all",
currentImageIndex === idx ? "bg-accent w-6" : "bg-white/30"
)}
/>
))}
</div>
</>
)}
<div className="absolute inset-0 bg-gradient-to-b from-black/60 via-transparent to-bg-dark z-10" />
{/* Floating Back Button */}
<button
onClick={() => navigate(-1)}
className="absolute top-12 left-6 z-50 w-12 h-12 rounded-full glass flex items-center justify-center text-white active:scale-90 transition-transform border border-white/10"
>
<ArrowLeft className="w-6 h-6" />
</button>
{/* Floating Favorite Button */}
<button
onClick={() => product && toggleFavorite(product.id, (isLiked) => {
setProduct(prev => prev ? {
...prev,
real_likes_count: (prev.real_likes_count || 0) + (isLiked ? -1 : 1)
} : null);
})}
className="absolute top-12 right-6 z-50 flex items-center gap-2 px-4 py-2.5 rounded-full glass active:scale-90 transition-transform border border-white/10"
>
<Heart
className={cn("w-5 h-5 transition-colors", product && favorites.includes(product.id) ? "fill-accent text-accent" : "text-white/60")}
strokeWidth={2.5}
/>
<span className="text-xs font-black text-white/80">
{product ? (product.fictitious_likes || 0) + (product.real_likes_count || 0) : 0}
</span>
</button>
</div>
<div className="px-6 -mt-20 relative z-10 space-y-8">
{/* Product Title & Badge */}
<div className="space-y-4">
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
className={cn(
"inline-flex px-2 py-0.5 rounded-full border backdrop-blur-md",
product.is_in_stock ? "bg-accent/20 border-accent/30" : "bg-red-500/20 border-red-500/30"
)}
>
<span className={cn(
"text-[8px] font-black uppercase tracking-[0.2em] font-display",
product.is_in_stock ? "text-accent" : "text-red-500"
)}>
{product.is_in_stock ? '✨ En stock' : '❌ Rupture de stock'}
</span>
</motion.div>
<motion.h1
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.1 }}
className="text-4xl font-black text-white tracking-tight leading-none font-display uppercase"
>
{product.name}
</motion.h1>
<motion.p
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.2 }}
className="text-text-muted text-xs font-bold leading-relaxed uppercase tracking-widest opacity-80"
>
{product.description || "Un produit d'exception sélectionné pour sa qualité inégalée."}
</motion.p>
</div>
{/* Prices Section */}
<div className="space-y-6">
<div className="flex items-center justify-between">
<h3 className="text-[11px] font-black text-white uppercase tracking-[0.4em] flex items-center gap-3">
<div className="w-6 h-[1px] bg-accent/40" />
Formats Disponibles
</h3>
</div>
<div className="grid gap-4">
{prices.map((price, idx) => (
<motion.div
key={price.id}
initial={{ opacity: 0, x: -20 }}
animate={{ opacity: 1, x: 0 }}
transition={{ delay: 0.3 + idx * 0.1 }}
className="group relative overflow-hidden bg-bg-card/40 backdrop-blur-md rounded-[2.5rem] border border-border p-5 flex items-center justify-between transition-all hover:border-accent/40 hover:bg-bg-card/60"
>
<div className="flex flex-col gap-1">
<span className="text-[8px] font-black text-accent uppercase tracking-widest opacity-60">Quantité</span>
<span className="text-xl font-black text-white font-display uppercase tracking-tight">{price.quantity}</span>
</div>
<div className="flex items-center gap-6">
<div className="text-right">
<span className="text-[8px] font-black text-white/20 uppercase tracking-widest mb-1 block">Prix unitaire</span>
<span className="text-2xl font-black text-white font-display">{price.price}€</span>
</div>
<button
onClick={() => product.is_in_stock !== false && handleAddToCart(price)}
disabled={product.is_in_stock === false}
className={cn(
"w-14 h-14 rounded-full flex items-center justify-center transition-all active:scale-90 border relative overflow-hidden group/btn",
product.is_in_stock === false
? "bg-white/5 text-white/10 border-transparent cursor-not-allowed"
: addedPriceId === price.id
? "bg-accent text-white border-accent shadow-[0_0_30px_rgba(16,185,129,0.5)]"
: "bg-bg-card/60 backdrop-blur-md text-accent border-white/10 hover:border-accent/40 hover:bg-bg-card/80"
)}
>
{product.is_in_stock === false ? (
<Minus className="w-6 h-6" />
) : addedPriceId === price.id ? (
<Check className="w-6 h-6" />
) : (
<>
<Plus className="w-6 h-6 relative z-10" />
<div className="absolute inset-0 bg-accent/10 opacity-0 group-hover/btn:opacity-100 transition-opacity" />
</>
)}
</button>
</div>
</motion.div>
))}
</div>
</div>
</div>
</motion.div>
);
};
const Infos = ({ config }: { config: ShopConfig | null }) => {
const navigate = useNavigate();
const tgUser = (window as any).Telegram?.WebApp?.initDataUnsafe?.user;
const userId = tgUser?.id?.toString() || '';
const isPrivileged = config && (userId === config.adminId || userId === config.managerChatId);
return (
<div className="min-h-screen bg-transparent p-8 pb-32">
<div className="space-y-10 pt-12">
<div className="flex items-start justify-between">
<div className="space-y-3">
<div className="inline-flex items-center gap-2 bg-accent/10 px-3 py-1 rounded-full border border-accent/20">
<Info className="w-3 h-3 text-accent" />
<span className="text-[9px] font-black text-accent uppercase tracking-widest">À propos</span>
</div>
<h2 className="text-4xl font-black text-white tracking-tight font-display">Informations</h2>
<p className="text-text-muted font-medium text-sm leading-relaxed">
Découvrez comment nous garantissons la meilleure expérience pour {config?.shopName || 'notre communauté'}.
</p>
</div>
{isPrivileged && (
<button
onClick={() => navigate('/settings')}
className="w-12 h-12 rounded-full glass flex items-center justify-center text-accent shadow-[0_0_20px_rgba(16,185,129,0.3)] border border-accent/20"
>
<Settings className="w-6 h-6" />
</button>
)}
</div>
<div className="grid gap-5">
{config?.infoText ? (
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
className="p-6 bg-bg-card rounded-[2rem] border border-white/5 shadow-2xl space-y-4"
>
<div className="w-12 h-12 bg-accent/10 rounded-2xl flex items-center justify-center border border-accent/20">
<FileText className="w-6 h-6 text-accent" />
</div>
<div className="space-y-3">
<h3 className="font-black text-white uppercase tracking-wider text-sm font-display">Guide d'utilisation</h3>
<div className="text-text-muted text-xs font-medium leading-relaxed whitespace-pre-wrap">
{config.infoText}
</div>
</div>
</motion.div>
) : (
[
{ title: 'Livraison', content: 'Expédition rapide et discrète sous 24/48h avec suivi en temps réel.', icon: Package, color: 'text-accent' },
{ title: 'Paiement', content: 'Transactions sécurisées via Crypto-monnaies pour une confidentialité totale.', icon: ShoppingCart, color: 'text-accent' },
{ title: 'Support 24/7', content: 'Une équipe dédiée à votre écoute sur Telegram pour toute question.', icon: MessageSquare, color: 'text-accent' },
].map((item, i) => (
<motion.div
key={i}
initial={{ opacity: 0, x: -20 }}
animate={{ opacity: 1, x: 0 }}
transition={{ delay: i * 0.1 }}
className="p-6 bg-bg-card rounded-[2rem] border border-white/5 shadow-2xl space-y-4 group hover:border-accent/20 transition-all"
>
<div className={cn("w-12 h-12 bg-white/5 rounded-2xl flex items-center justify-center border border-white/5 group-hover:scale-110 transition-transform", item.color)}>
<item.icon className="w-6 h-6" />
</div>
<div className="space-y-1">
<h3 className="font-black text-white uppercase tracking-wider text-sm font-display">{item.title}</h3>
<p className="text-text-muted text-xs font-medium leading-relaxed">{item.content}</p>
</div>
</motion.div>
))
)}
</div>
{/* Premium Badge */}
<div className="mt-8 p-6 bg-gradient-to-br from-gold/20 to-transparent rounded-[2rem] border border-gold/30 flex items-center gap-4">
<div className="w-12 h-12 bg-gold/20 rounded-full flex items-center justify-center border border-gold/50">
<Leaf className="w-6 h-6 text-gold" />
</div>
<div>
<h4 className="text-gold font-black text-xs uppercase tracking-widest">Service Gold</h4>
<p className="text-gold/60 text-[10px] font-bold uppercase tracking-wider">Qualité supérieure garantie</p>
</div>
</div>
</div>
</div>
);
};
const ShopClosed = ({ config }: { config: ShopConfig | null }) => {
const handleContact = () => {
const url = `https://t.me/${config?.orderManager || 'username'}`;
if (window.Telegram?.WebApp) {
window.Telegram.WebApp.openTelegramLink(url);
} else {
window.open(url, '_blank');
}
};
return (
<div className="min-h-screen bg-transparent flex flex-col items-center justify-center p-8 text-center">
<div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-[500px] h-[500px] bg-red-500/5 rounded-full blur-[120px] pointer-events-none" />
<motion.div
initial={{ scale: 0.9, opacity: 0 }}
animate={{ scale: 1, opacity: 1 }}
className="space-y-8 relative z-10"
>
<div className="relative">
<div className="w-32 h-32 bg-bg-card rounded-full flex items-center justify-center mx-auto border-4 border-red-500/20 shadow-[0_0_50px_rgba(239,68,68,0.1)]">
<Package className="w-16 h-16 text-red-500/40" />
<div className="absolute -top-2 -right-2 bg-red-500 text-white text-[10px] font-black px-3 py-1 rounded-full shadow-lg">
FERMÉ
</div>
</div>
</div>
<div className="space-y-4">
<h2 className="text-4xl font-black text-white tracking-tight font-display">
{config?.shopName || 'Le Shop'} est fermé
</h2>
<p className="text-text-muted font-medium text-sm leading-relaxed max-w-xs mx-auto">
Nous sommes actuellement fermés. Revenez plus tard pour passer commande ou contactez-nous directement.
</p>
</div>
<div className="flex flex-col gap-4 pt-4">
<button
onClick={handleContact}
className="w-full bg-white/5 border border-white/10 text-white font-black py-4 rounded-2xl transition-all active:scale-[0.98] flex items-center justify-center gap-3 font-display"
>
<MessageSquare className="w-5 h-5 text-accent" />
CONTACTER LE SUPPORT
</button>
<button
onClick={() => window.Telegram?.WebApp?.close()}
className="text-[10px] font-black text-white/30 uppercase tracking-[0.3em] hover:text-white transition-colors"
>
Fermer l'application
</button>
</div>
</motion.div>
</div>
);
};
// --- Main App ---
const Cart = ({
config,
cart,
updateQuantity,
removeFromCart,
fulfillmentType,
modifyingOrderId,
modifyingOrderAddress,
clearCart
}: {
config: ShopConfig | null,
cart: CartItem[],
updateQuantity: (priceId: string, delta: number) => void,
removeFromCart: (priceId: string) => void,
fulfillmentType: 'delivery' | 'meetup' | null,
modifyingOrderId: string | null,
modifyingOrderAddress: any | null,
clearCart: () => void
}) => {
const [streetNumber, setStreetNumber] = useState('');
const [streetName, setStreetName] = useState('');
const [city, setCity] = useState('');
const [postalCode, setPostalCode] = useState('');
const [comment, setComment] = useState('');
const [phone, setPhone] = useState('');
const [suggestions, setSuggestions] = useState<any[]>([]);
const [selectedCoords, setSelectedCoords] = useState<{lat: string, lon: string} | null>(null);
const [isSearching, setIsSearching] = useState(false);
const [showSuggestions, setShowSuggestions] = useState(false);
const navigate = useNavigate();
const tgUser = (window as any).Telegram?.WebApp?.initDataUnsafe?.user;
// Pre-fill address when modifying an order
useEffect(() => {
if (modifyingOrderId && modifyingOrderAddress) {
if (typeof modifyingOrderAddress === 'object') {
setStreetNumber(modifyingOrderAddress.streetNumber || '');
setStreetName(modifyingOrderAddress.streetName || '');
setCity(modifyingOrderAddress.city || '');
setPostalCode(modifyingOrderAddress.postalCode || '');
setComment(modifyingOrderAddress.comment || '');
} else if (typeof modifyingOrderAddress === 'string' && modifyingOrderAddress !== 'MEETUP') {
// Parse the address string if it's not JSON
// Format: "123 Rue de la Paix, 75000 Paris (Comment)|lat,lon"
const parts = modifyingOrderAddress.split('|');
const mainPart = parts[0];
const coordsPart = parts[1];
// Simple parsing logic
const commentMatch = mainPart.match(/\((.*?)\)$/);
const commentText = commentMatch ? commentMatch[1] : '';
const addressWithoutComment = mainPart.replace(/\s*\(.*?\)$/, '');
const addressParts = addressWithoutComment.split(', ');
if (addressParts.length >= 2) {
const streetPart = addressParts[0];
const cityPart = addressParts[1];
// Street number and name
const streetMatch = streetPart.match(/^(\d+)?\s*(.*)$/);
if (streetMatch) {
setStreetNumber(streetMatch[1] || '');
setStreetName(streetMatch[2] || '');
}
// Postal code and city
const cityMatch = cityPart.match(/^(\d{5})?\s*(.*)$/);
if (cityMatch) {
setPostalCode(cityMatch[1] || '');
setCity(cityMatch[2] || '');
}
setComment(commentText);
if (coordsPart) {
const [lat, lon] = coordsPart.split(',');
setSelectedCoords({ lat, lon });
}
}
}
}
}, [modifyingOrderId, modifyingOrderAddress]);
useEffect(() => {
if (tgUser?.username) {
setPhone(`@${tgUser.username}`);
}
}, [tgUser]);
const handleGeolocation = () => {
if (!navigator.geolocation) {
(window as any).Telegram?.WebApp?.showAlert?.("La géolocalisation n'est pas supportée par votre navigateur.");
return;
}
setIsSearching(true);
navigator.geolocation.getCurrentPosition(async (position) => {
const { latitude, longitude } = position.coords;
try {
const response = await fetch(`https://nominatim.openstreetmap.org/reverse?format=jsonv2&lat=${latitude}&lon=${longitude}`);
const data = await response.json();
if (data.address) {
setStreetNumber(data.address.house_number || '');
setStreetName(data.address.road || '');
setCity(data.address.city || data.address.town || data.address.village || '');
setPostalCode(data.address.postcode || '');
setSelectedCoords({ lat: latitude.toString(), lon: longitude.toString() });
}
} catch (error) {
console.error("Error reverse geocoding:", error);
} finally {
setIsSearching(false);
}
}, (error) => {
console.error("Geolocation error:", error);
setIsSearching(false);
let errorMsg = "Erreur lors de la récupération de votre position.";
if (error.code === 1) errorMsg = "Permission de géolocalisation refusée. Veuillez l'activer dans les réglages de votre navigateur.";
else if (error.code === 2) errorMsg = "Position indisponible.";
else if (error.code === 3) errorMsg = "Délai d'attente dépassé.";
(window as any).Telegram?.WebApp?.showAlert?.(errorMsg);
}, {
enableHighAccuracy: true,
timeout: 10000,
maximumAge: 0
});
};
useEffect(() => {
const timer = setTimeout(async () => {
const fullSearch = `${streetNumber} ${streetName} ${city} ${postalCode}`.trim();
if (fullSearch.length > 3 && showSuggestions) {
setIsSearching(true);
try {
const response = await fetch(`https://nominatim.openstreetmap.org/search?format=jsonv2&q=${encodeURIComponent(fullSearch)}&limit=10&addressdetails=1&countrycodes=fr&dedupe=1`);
const data = await response.json();
const sorted = data.sort((a: any, b: any) => (b.importance || 0) - (a.importance || 0));
setSuggestions(sorted);
} catch (error) {
console.error("Error fetching suggestions:", error);
} finally {
setIsSearching(false);
}
} else {
setSuggestions([]);
}
}, 600);
return () => clearTimeout(timer);
}, [streetNumber, streetName, city, postalCode, showSuggestions]);
const handleSelectAddress = (suggestion: any) => {
if (suggestion.address) {
setStreetNumber(suggestion.address.house_number || '');
setStreetName(suggestion.address.road || '');
setCity(suggestion.address.city || suggestion.address.town || suggestion.address.village || '');
setPostalCode(suggestion.address.postcode || '');
}
setSelectedCoords({ lat: suggestion.lat, lon: suggestion.lon });
setSuggestions([]);
setShowSuggestions(false);
};
const [isCheckingOut, setIsCheckingOut] = useState(false);
const [orderSuccess, setOrderSuccess] = useState(false);
const total = cart.reduce((acc, item) => acc + (item.price * item.count), 0);
const handleCheckout = async () => {
if (cart.length === 0) return;
if (fulfillmentType !== 'meetup' && (!streetName.trim() || !city.trim() || !postalCode.trim())) {
(window as any).Telegram?.WebApp?.showAlert?.("Veuillez remplir les informations de livraison (Rue, Ville, Code Postal).");
return;
}
const telegramUser = (window.Telegram?.WebApp as any)?.initDataUnsafe?.user;
if (!telegramUser?.username && !phone.trim()) {
(window as any).Telegram?.WebApp?.showAlert?.("Veuillez entrer votre numéro de téléphone ou avoir un nom d'utilisateur Telegram.");
return;
}
setIsCheckingOut(true);
const date = new Date().toLocaleDateString('fr-FR', {
day: '2-digit',
month: 'long',
year: 'numeric',
hour: '2-digit',
minute: '2-digit'
});
try {
const fullAddress = `${streetNumber} ${streetName}, ${postalCode} ${city}${comment ? ` (${comment})` : ''}`.trim();
const orderAddress = fulfillmentType === 'meetup' ? 'MEETUP' : (selectedCoords ? `${fullAddress}|${selectedCoords.lat},${selectedCoords.lon}` : fullAddress);
const endpoint = modifyingOrderId ? '/api/orders/modify' : '/api/orders';
const payload = {
orderId: modifyingOrderId,
cart,
total,
address: orderAddress,
phone,
date,
type: fulfillmentType || 'delivery',
telegramId: telegramUser?.id,
telegramUsername: telegramUser?.username,
telegramFirstName: telegramUser?.first_name
};
const response = await fetch(endpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
});
if (response.ok) {
setOrderSuccess(true);
clearCart();
} else {
const errData = await response.json();
(window as any).Telegram?.WebApp?.showAlert?.(errData.error || "Une erreur est survenue.");
}
} catch (error) {
console.error('Order error:', error);
(window as any).Telegram?.WebApp?.showAlert?.("Une erreur est survenue lors de l'envoi de la commande.");
} finally {
setIsCheckingOut(false);
}
};
if (orderSuccess) {
return (
<div className="min-h-screen bg-[#0a0a0a] text-white flex flex-col items-center justify-center p-6 text-center">
<motion.div
initial={{ scale: 0.8, opacity: 0 }}
animate={{ scale: 1, opacity: 1 }}
className="bg-[#1a1a1a] p-8 rounded-3xl border border-emerald-500/30 shadow-2xl shadow-emerald-500/10 max-w-md w-full"
>
<div className="w-20 h-20 bg-emerald-500/20 rounded-full flex items-center justify-center mx-auto mb-6">
<Check className="w-10 h-10 text-emerald-500" />
</div>
<h2 className="text-2xl font-bold mb-4">{modifyingOrderId ? "Commande Modifiée !" : "Commande Envoyée !"}</h2>
<p className="text-gray-400 mb-8 leading-relaxed">
{modifyingOrderId
? "Votre commande a été mise à jour avec succès. Le livreur en a été informé."
: (fulfillmentType === 'meetup'
? "Votre commande a été reçue. Un collaborateur va vous contacter sous peu pour le point de rendez-vous."
: "Un livreur va vous répondre sous peu veuillez rester attentif")}
</p>
<button
onClick={() => navigate('/')}
className="w-full py-4 bg-emerald-600 hover:bg-emerald-500 rounded-2xl font-bold transition-all active:scale-95"
>
RETOUR À L'ACCUEIL
</button>
</motion.div>
</div>
);
}
return (
<div className="min-h-screen bg-bg-dark pb-40 relative overflow-hidden">
{/* Background Glows */}
<div className="absolute top-0 left-1/2 -translate-x-1/2 w-full h-[600px] bg-[radial-gradient(circle_at_50%_0%,rgba(16,185,129,0.15),transparent_70%)] pointer-events-none" />
<div className="absolute -bottom-40 -left-40 w-96 h-96 bg-accent/5 rounded-full blur-[120px] pointer-events-none" />
<div className="pt-12 px-6 space-y-10 relative z-10">
{/* Header Section */}
<div className="space-y-4">
{modifyingOrderId && (
<motion.div
initial={{ opacity: 0, y: -10 }}
animate={{ opacity: 1, y: 0 }}
className="bg-accent/10 border border-accent/20 p-4 rounded-2xl flex flex-col gap-4 mb-4"
>
<div className="flex items-center gap-3">
<div className="w-10 h-10 rounded-xl bg-accent/20 flex items-center justify-center">
<Edit className="w-5 h-5 text-accent" />
</div>
<div className="flex-1">
<p className="text-[10px] font-black text-accent uppercase tracking-widest">Mode Modification</p>
<p className="text-[11px] font-bold text-white uppercase tracking-tight">Modification de la commande de {tgUser?.first_name || 'Client'}</p>
</div>
<button
onClick={clearCart}
className="p-2 text-white/40 hover:text-red-500 transition-colors"
>
<Trash2 className="w-4 h-4" />
</button>
</div>
</motion.div>
)}
<motion.div
initial={{ opacity: 0, x: -20 }}
animate={{ opacity: 1, x: 0 }}
className="flex items-center gap-4"
>
<button
onClick={() => navigate(-1)}
className="p-3 glass rounded-2xl border-white/10 text-white active:scale-90 transition-transform"
>
<ArrowLeft className="w-5 h-5" />
</button>
<h1 className="text-4xl font-black text-white tracking-tight font-display uppercase">Mon Panier</h1>
</motion.div>
<div className="flex items-center gap-3 pl-16">
<div className="h-[1px] w-8 bg-accent/40" />
<p className="text-[10px] text-text-muted font-black uppercase tracking-[0.4em] opacity-60">
{cart.length} {cart.length > 1 ? 'articles sélectionnés' : 'article sélectionné'}
</p>
</div>
</div>
{cart.length === 0 ? (
<motion.div
initial={{ scale: 0.8, opacity: 0, y: 20 }}
animate={{ scale: 1, opacity: 1, y: 0 }}
className="py-24 text-center space-y-10"
>
<div className="relative inline-block">
<div className="w-32 h-32 bg-bg-card/40 backdrop-blur-md rounded-[3rem] flex items-center justify-center mx-auto border border-white/5 shadow-2xl relative z-10">
<ShoppingCart className="w-12 h-12 text-white/5" />
</div>
<motion.div
animate={{ scale: [1, 1.3, 1], opacity: [0.2, 0.5, 0.2] }}
transition={{ duration: 4, repeat: Infinity }}
className="absolute inset-0 bg-accent/20 rounded-full blur-3xl -z-10"
/>
</div>
<div className="space-y-3">
<h2 className="text-xl font-black text-white uppercase tracking-tight font-display">Votre panier est vide</h2>
<p className="text-text-muted/40 text-[9px] font-bold uppercase tracking-[0.3em] max-w-[220px] mx-auto leading-relaxed">
Explorez notre catalogue premium pour commencer votre sélection
</p>
</div>
<button
onClick={() => navigate('/')}
className="px-12 py-5 bg-accent text-white font-black rounded-2xl text-[11px] uppercase tracking-[0.2em] shadow-[0_20px_40px_rgba(16,185,129,0.3)] active:scale-95 transition-all font-display hover:shadow-[0_25px_50px_rgba(16,185,129,0.4)]"
>
Retour au catalogue
</button>
</motion.div>
) : (
<>
{/* Cart Items List */}
<div className="space-y-4">
<h3 className="text-[10px] font-black text-white/30 uppercase tracking-[0.5em] flex items-center gap-4 ml-2">
<div className="w-8 h-[1px] bg-white/10" />
Détails de la commande
</h3>
<div className="space-y-4">
<AnimatePresence mode="popLayout">
{cart.map((item, idx) => (
<motion.div
layout
key={item.priceId}
initial={{ opacity: 0, x: -20 }}
animate={{ opacity: 1, x: 0 }}
exit={{ opacity: 0, scale: 0.95, x: 20 }}
transition={{ delay: idx * 0.05 }}
className="bg-bg-card/40 backdrop-blur-md p-6 rounded-[2.5rem] border border-white/5 premium-shadow flex items-center gap-6 group hover:border-accent/30 transition-all relative overflow-hidden"
>
<div className="absolute top-0 right-0 w-24 h-24 bg-accent/5 rounded-full blur-2xl -z-10 opacity-0 group-hover:opacity-100 transition-opacity" />
<div className="flex-1 space-y-3">
<div className="space-y-1">
<span className="text-[8px] font-black text-accent uppercase tracking-widest opacity-60">
Article sélectionné
</span>
<h4 className="font-black text-white text-base uppercase tracking-tight font-display line-clamp-1">{item.productName}</h4>
</div>
<div className="flex items-center gap-5">
<div className="flex flex-col">
<span className="text-[7px] font-black text-white/20 uppercase tracking-widest mb-0.5">Format</span>
<span className="text-xs font-black text-white uppercase tracking-tighter bg-white/5 px-2 py-0.5 rounded-md border border-white/5">{item.quantityLabel}</span>
</div>
<div className="w-[1px] h-6 bg-white/5" />
<div className="flex flex-col">
<span className="text-[7px] font-black text-white/20 uppercase tracking-widest mb-0.5">Prix</span>
<span className="text-xs font-black text-accent uppercase tracking-tighter">{item.price}€</span>
</div>
</div>
</div>
<div className="flex flex-col items-center gap-3">
<div className="flex items-center bg-bg-dark/60 p-1 rounded-2xl border border-white/5">
<button
onClick={() => updateQuantity(item.priceId, -1)}
className="w-9 h-9 flex items-center justify-center hover:bg-white/5 rounded-xl transition-colors text-white/20 hover:text-white active:scale-90"
>
<Minus className="w-3.5 h-3.5" />
</button>
<span className="text-sm font-black text-white min-w-[1.5rem] text-center font-display">{item.count}</span>
<button
onClick={() => updateQuantity(item.priceId, 1)}
className="w-9 h-9 flex items-center justify-center hover:bg-white/5 rounded-xl transition-colors text-accent active:scale-90"
>
<Plus className="w-3.5 h-3.5" />
</button>
</div>
<button
onClick={() => removeFromCart(item.priceId)}
className="text-[9px] font-black text-red-500/40 hover:text-red-500 uppercase tracking-widest transition-colors"
>
Supprimer
</button>
</div>
</motion.div>
))}
</AnimatePresence>
</div>
{modifyingOrderId && (
<motion.div
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
className="px-2"
>
<button
onClick={() => navigate('/')}
className="w-full py-4 bg-accent text-white font-black rounded-2xl text-[11px] uppercase tracking-[0.2em] flex items-center justify-center gap-3 shadow-xl shadow-accent/20 active:scale-95 transition-all group"
>
<Plus className="w-5 h-5 group-hover:rotate-90 transition-transform" />
Ajouter un nouveau produit du catalogue
</button>
</motion.div>
)}
{fulfillmentType !== 'meetup' && (
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
className="space-y-4"
>
<div className="flex items-center justify-between ml-2">
<label className="text-[9px] font-black text-white uppercase tracking-[0.4em] flex items-center gap-3">
<MapPin className="w-3 h-3 text-accent" />
Informations de Livraison
</label>
<button
onClick={handleGeolocation}
disabled={isSearching}
className="text-[8px] font-black text-accent uppercase tracking-widest flex items-center gap-2 bg-accent/10 px-3 py-1.5 rounded-full border border-accent/20 active:scale-95 transition-all disabled:opacity-50"
>
{isSearching ? <Loader2 className="w-3 h-3 animate-spin" /> : <Navigation className="w-3 h-3" />}
Ma Position
</button>
</div>
<div className="grid grid-cols-4 gap-3">
<div className="col-span-1">
<input
type="text"
value={streetNumber}
onChange={(e) => setStreetNumber(e.target.value)}
placeholder="N°"
className="w-full bg-bg-card/40 backdrop-blur-md border border-border rounded-2xl p-4 text-white text-base font-bold placeholder:text-white/10 focus:border-accent/40 focus:outline-none transition-all premium-shadow uppercase"
/>
</div>
<div className="col-span-3 relative">
<input
type="text"
value={streetName}
onChange={(e) => {
setStreetName(e.target.value);
setShowSuggestions(true);
}}
onFocus={() => setShowSuggestions(true)}
onBlur={() => setTimeout(() => setShowSuggestions(false), 200)}
placeholder="Rue / Avenue..."
className="w-full bg-bg-card/40 backdrop-blur-md border border-border rounded-2xl p-4 text-white text-base font-bold placeholder:text-white/10 focus:border-accent/40 focus:outline-none transition-all premium-shadow uppercase"
/>
<AnimatePresence>
{suggestions.length > 0 && showSuggestions && (
<motion.div
initial={{ opacity: 0, y: -10 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: -10 }}
className="absolute z-[70] w-full mt-2 bg-bg-card border border-border rounded-2xl overflow-hidden shadow-2xl premium-shadow backdrop-blur-xl max-h-60 overflow-y-auto"
>
{suggestions.map((s, i) => (
<button
key={i}
type="button"
onClick={() => handleSelectAddress(s)}
className="w-full text-left p-4 text-[9px] text-white hover:bg-white/5 border-b border-white/5 last:border-0 transition-colors flex items-start gap-3"
>
<Search className="w-3 h-3 mt-0.5 text-accent flex-shrink-0" />
<span className="leading-relaxed font-bold uppercase tracking-tight">{s.display_name}</span>
</button>
))}
</motion.div>
)}
</AnimatePresence>
</div>
</div>
<div className="grid grid-cols-2 gap-3">
<input
type="text"
value={postalCode}
onChange={(e) => setPostalCode(e.target.value)}
placeholder="Code Postal"
className="w-full bg-bg-card/40 backdrop-blur-md border border-border rounded-2xl p-4 text-white text-base font-bold placeholder:text-white/10 focus:border-accent/40 focus:outline-none transition-all premium-shadow uppercase"
/>
<input
type="text"
value={city}
onChange={(e) => setCity(e.target.value)}
placeholder="Ville"
className="w-full bg-bg-card/40 backdrop-blur-md border border-border rounded-2xl p-4 text-white text-base font-bold placeholder:text-white/10 focus:border-accent/40 focus:outline-none transition-all premium-shadow uppercase"
/>
</div>
<textarea
value={comment}
onChange={(e) => setComment(e.target.value)}
placeholder="Commentaire (Bâtiment, étage, interphone...)"
className="w-full bg-bg-card/40 backdrop-blur-md border border-border rounded-2xl p-4 text-white text-base font-bold placeholder:text-white/10 focus:border-accent/40 focus:outline-none transition-all min-h-[80px] resize-none premium-shadow uppercase"
/>
</motion.div>
)}
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
className="space-y-4"
>
<label className="text-[9px] font-black text-white uppercase tracking-[0.4em] flex items-center gap-3 ml-2">
<MessageSquare className="w-3 h-3 text-accent" /> Contact Telegram / Tel
</label>
<input
type="text"
value={phone}
onChange={(e) => setPhone(e.target.value)}
placeholder="Ex: @username ou 06..."
className="w-full bg-bg-card/40 backdrop-blur-md border border-border rounded-[2rem] p-6 text-white text-base font-bold placeholder:text-white/10 focus:border-accent/40 focus:outline-none transition-all premium-shadow uppercase tracking-wider"
/>
</motion.div>
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
className="bg-bg-card/80 backdrop-blur-xl p-10 rounded-[3rem] border border-white/10 premium-shadow space-y-8 relative overflow-hidden"
>
<div className="absolute top-0 right-0 w-32 h-32 bg-accent/10 rounded-full blur-3xl -z-10" />
<div className="flex justify-between items-end px-2">
<div className="space-y-2">
<span className="text-[10px] font-black text-text-muted uppercase tracking-[0.4em] opacity-60">Total de la commande</span>
<div className="flex items-baseline gap-1">
<span className="text-5xl font-black text-white font-display tracking-tighter">{total}</span>
<span className="text-xl font-black text-accent font-display">€</span>
</div>
</div>
<div className="bg-white/5 px-5 py-3 rounded-2xl border border-white/5 backdrop-blur-md">
<span className="text-[10px] font-black text-white uppercase tracking-widest">{cart.reduce((a, b) => a + b.count, 0)} Articles</span>
</div>
</div>
<div className="space-y-4">
<div className="h-[1px] w-full bg-white/5" />
<div className="flex items-center gap-3 text-[9px] font-bold text-text-muted/40 uppercase tracking-widest px-2">
<ShieldCheck className="w-3.5 h-3.5 text-accent/40" />
Paiement sécurisé à la livraison
</div>
</div>
<button
onClick={handleCheckout}
disabled={isCheckingOut || (fulfillmentType !== 'meetup' && (!streetName || !city || !postalCode)) || !phone}
className="w-full py-7 bg-accent text-white font-black rounded-[2rem] text-xs uppercase tracking-[0.3em] shadow-[0_25px_50px_rgba(16,185,129,0.4)] active:scale-[0.98] transition-all font-display disabled:opacity-20 disabled:grayscale relative overflow-hidden group"
>
<div className="absolute inset-0 bg-white/20 translate-y-full group-hover:translate-y-0 transition-transform duration-500" />
<span className="relative z-10 flex items-center justify-center gap-3">
{isCheckingOut ? (
<>
<Loader2 className="w-5 h-5 animate-spin" />
Traitement...
</>
) : (
<>
Confirmer la commande
<ChevronRight className="w-5 h-5 group-hover:translate-x-1 transition-transform" />
</>
)}
</span>
</button>
</motion.div>
</div>
</>
)}
</div>
</div>
);
};
const MyOrders = ({ config, addToCart, clearCart, setCart, setModifyingOrderId, setModifyingOrderAddress, setFulfillmentType }: {
config: ShopConfig | null,
addToCart: (item: CartItem) => void,
clearCart: () => void,
setCart: React.Dispatch<React.SetStateAction<CartItem[]>>,
setModifyingOrderId: (id: string | null) => void,
setModifyingOrderAddress: (address: any | null) => void,
setFulfillmentType: (type: 'delivery' | 'meetup' | null) => void
}) => {
const [orders, setOrders] = useState<any[]>([]);
const [loading, setLoading] = useState(true);
const navigate = useNavigate();
const tgUser = (window as any).Telegram?.WebApp?.initDataUnsafe?.user;
const userId = tgUser?.id?.toString();
useEffect(() => {
const fetchOrders = async () => {
if (!userId) {
setLoading(false);
return;
}
try {
const response = await fetch(`/api/my-orders?userId=${userId}`);
const data = await response.json();
if (Array.isArray(data)) {
setOrders(data);
}
} catch (error) {
console.error('Error fetching orders:', error);
} finally {
setLoading(false);
}
};
fetchOrders();
}, [userId]);
const handleModifyOrder = (order: any) => {
if (['completed', 'cancelled', 'reported'].includes(order.status)) {
(window as any).Telegram?.WebApp?.showAlert?.("Cette commande ne peut plus être modifiée.");
return;
}
(window as any).Telegram?.WebApp?.showConfirm?.("Voulez-vous modifier cette commande ? Cela remplacera votre panier actuel.", async (confirmed: boolean) => {
if (confirmed) {
setModifyingOrderId(order.id);
setModifyingOrderAddress(order.address);
setFulfillmentType(order.type);
setCart(order.items);
navigate('/cart');
}
});
};
const getStatusStyles = (status: string) => {
switch (status) {
case 'pending': return 'text-amber-500 bg-amber-500/5 border-amber-500/10';
case 'validated': return 'text-sky-500 bg-sky-500/5 border-sky-500/10';
case 'completed': return 'text-emerald-500 bg-emerald-500/5 border-emerald-500/10';
case 'cancelled': return 'text-rose-500 bg-rose-500/5 border-rose-500/10';
default: return 'text-zinc-500 bg-zinc-500/5 border-zinc-500/10';
}
};
const getStatusLabel = (status: string) => {
switch (status) {
case 'pending': return 'En attente';
case 'validated': return 'En préparation';
case 'completed': return 'Livrée';
case 'cancelled': return 'Annulée';
case 'reported': return 'Archivée';
default: return status;
}
};
return (
<div className="min-h-screen bg-bg-dark pb-40 relative overflow-hidden font-sans">
{/* Background Atmosphere */}
<div className="absolute top-0 left-0 w-full h-full pointer-events-none overflow-hidden">
<div className="absolute top-[-10%] left-[-10%] w-[40%] h-[40%] bg-accent/5 rounded-full blur-[120px]" />
<div className="absolute bottom-[-10%] right-[-10%] w-[40%] h-[40%] bg-accent/5 rounded-full blur-[120px]" />
</div>
<div className="max-w-2xl mx-auto pt-12 px-6 space-y-12 relative z-10">
{/* User Profile Header - Editorial Style */}
<motion.div
initial={{ opacity: 0, y: -20 }}
animate={{ opacity: 1, y: 0 }}
className="flex flex-col items-center text-center space-y-6"
>
<div className="relative group">
<div className="w-24 h-24 rounded-full p-1 bg-gradient-to-br from-accent/40 via-accent/5 to-transparent shadow-2xl transition-transform group-hover:scale-105 duration-500">
<div className="w-full h-full rounded-full bg-[#0a0a0a] overflow-hidden border border-white/10 flex items-center justify-center">
{tgUser?.photo_url ? (
<img src={tgUser.photo_url} alt="Profile" className="w-full h-full object-cover grayscale-[0.2] hover:grayscale-0 transition-all duration-500" referrerPolicy="no-referrer" />
) : (
<User className="w-10 h-10 text-accent/40" />
)}
</div>
</div>
<motion.div
animate={{ scale: [1, 1.2, 1], opacity: [0.5, 1, 0.5] }}
transition={{ duration: 3, repeat: Infinity }}
className="absolute -bottom-1 -right-1 bg-accent text-[#050505] p-1.5 rounded-full border-4 border-[#050505]"
>
<ShieldCheck className="w-3 h-3" />
</motion.div>
</div>
<div className="space-y-2">
<h2 className="text-3xl font-black text-white uppercase tracking-tight font-display italic">
{tgUser?.first_name} {tgUser?.last_name}
</h2>
<div className="flex items-center justify-center gap-3">
<span className="text-[10px] text-accent font-black tracking-[0.4em] uppercase">
@{tgUser?.username || 'CLIENT_PREMIUM'}
</span>
<div className="w-1 h-1 bg-white/20 rounded-full" />
<span className="text-[10px] text-white/40 font-black tracking-[0.4em] uppercase">
ID: {userId?.slice(-6)}
</span>
</div>
</div>
</motion.div>
<div className="space-y-8">
<div className="flex items-end justify-between border-b border-white/10 pb-4">
<div className="space-y-1">
<h1 className="text-sm font-black text-white uppercase tracking-[0.3em]">Historique</h1>
<p className="text-[10px] text-white/40 font-serif italic">Vos commandes passées et en cours</p>
</div>
<div className="text-right">
<span className="text-2xl font-black text-white font-mono">{orders.length}</span>
<span className="text-[10px] text-white/40 font-black uppercase tracking-widest ml-2">Total</span>
</div>
</div>
{loading ? (
<div className="py-32 flex flex-col items-center justify-center gap-6">
<div className="relative">
<Loader2 className="w-10 h-10 text-accent animate-spin" />
<div className="absolute inset-0 bg-accent/20 blur-xl animate-pulse" />
</div>
<p className="text-[10px] font-black text-white/20 uppercase tracking-[0.5em] animate-pulse">Synchronisation...</p>
</div>
) : orders.length === 0 ? (
<div className="py-32 text-center space-y-8">
<div className="w-20 h-20 bg-white/5 rounded-full flex items-center justify-center mx-auto border border-white/5 opacity-20">
<Package className="w-8 h-8 text-white" />
</div>
<div className="space-y-3">
<p className="text-white/60 font-black uppercase tracking-[0.2em] text-xs">Aucune activité enregistrée</p>
<p className="text-[9px] text-white/20 font-bold uppercase tracking-[0.3em] max-w-[200px] mx-auto leading-relaxed">
Vos futures commandes apparaîtront dans cet espace sécurisé
</p>
</div>
<button
onClick={() => navigate('/')}
className="group relative px-10 py-4 bg-transparent text-accent font-black rounded-full text-[10px] uppercase tracking-[0.2em] border border-accent/20 hover:border-accent/60 transition-all overflow-hidden"
>
<div className="absolute inset-0 bg-accent/5 translate-y-full group-hover:translate-y-0 transition-transform duration-500" />
<span className="relative z-10">Explorer le catalogue</span>
</button>
</div>
) : (
<div className="grid gap-8">
{orders.map((order, idx) => (
<motion.div
key={order.id}
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: idx * 0.1 }}
className="group relative"
>
{/* Order Card - Technical Dashboard Style */}
<div className="bg-[#0a0a0a] border border-white/5 rounded-3xl overflow-hidden transition-all duration-500 hover:border-accent/20 hover:shadow-[0_20px_50px_rgba(0,0,0,0.5)]">
{/* Header Bar */}
<div className="px-6 py-4 border-b border-white/5 flex items-center justify-between bg-white/[0.02]">
<div className="flex items-center gap-4">
<div className="flex flex-col">
<span className="text-[8px] font-black text-white/20 uppercase tracking-widest">Référence</span>
<span className="text-[10px] font-black text-white font-mono uppercase tracking-tighter">#{order.id?.toString().slice(-8) || 'N/A'}</span>
</div>
<div className="w-[1px] h-6 bg-white/5" />
<div className="flex flex-col">
<span className="text-[8px] font-black text-white/20 uppercase tracking-widest">Date</span>
<span className="text-[10px] font-black text-white/60 uppercase tracking-tighter">
{order.date ? order.date.split(' à ')[0] : (order.created_at ? new Date(order.created_at).toLocaleDateString('fr-FR') : 'N/A')}
</span>
</div>
</div>
<span className={cn(
"text-[9px] font-black uppercase tracking-[0.2em] px-4 py-1.5 rounded-full border transition-all duration-500",
getStatusStyles(order.status)
)}>
{getStatusLabel(order.status)}
</span>
</div>
<div className="p-6 space-y-8">
{/* Items List */}
<div className="space-y-4">
<div className="flex items-center gap-3">
<span className="text-[9px] font-black text-white/20 uppercase tracking-[0.3em]">Articles</span>
<div className="flex-1 h-[1px] bg-white/5" />
</div>
<div className="grid gap-3">
{(Array.isArray(order.items) ? order.items : (typeof order.items === 'string' ? JSON.parse(order.items) : [])).map((item: any, i: number) => (
<div key={i} className="flex items-center justify-between group/item">
<div className="flex items-center gap-4">
<div className="w-10 h-10 rounded-xl bg-white/5 border border-white/5 flex items-center justify-center group-hover/item:border-accent/20 transition-colors">
<Package className="w-4 h-4 text-white/20 group-hover/item:text-accent transition-colors" />
</div>
<div className="space-y-0.5">
<p className="text-[11px] font-black text-white uppercase tracking-tight">{item.productName}</p>
<p className="text-[9px] text-white/40 font-bold uppercase tracking-widest">
{item.quantityLabel} <span className="text-accent/60 mx-1">×</span> {item.count}
</p>
</div>
</div>
<span className="text-xs font-black text-white font-mono">{item.price * item.count}€</span>
</div>
))}
</div>
</div>
{/* Footer Info */}
<div className="flex items-center justify-between pt-4 border-t border-white/5">
<div className="flex items-center gap-4">
<div className="flex flex-col">
<span className="text-[8px] font-black text-white/20 uppercase tracking-widest mb-1">Mode</span>
<div className={cn(
"flex items-center gap-2 px-3 py-1.5 rounded-xl border text-[9px] font-black uppercase tracking-tight",
order.type === 'delivery' ? "bg-accent/5 border-accent/10 text-accent" : "bg-blue-500/5 border-blue-500/10 text-blue-500"
)}>
{order.type === 'delivery' ? <Truck className="w-3 h-3" /> : <Users className="w-3 h-3" />}
{order.type === 'delivery' ? 'Livraison' : 'Meet-up'}
</div>
</div>
{order.type === 'delivery' && (
<div className="flex flex-col">
<span className="text-[8px] font-black text-white/20 uppercase tracking-widest mb-1">Destination</span>
<div className="flex items-center gap-2 px-3 py-1.5 rounded-xl border border-white/5 text-[9px] font-black text-white/60 uppercase tracking-tight max-w-[120px]">
<MapPin className="w-3 h-3 text-white/20" />
<span className="truncate">{order.address?.split('|')[0] || 'N/A'}</span>
</div>
</div>
)}
</div>
<div className="text-right space-y-1">
<span className="text-[8px] font-black text-white/20 uppercase tracking-widest block">Total</span>
<span className="text-3xl font-black text-white font-display tracking-tighter">{order.total}€</span>
</div>
</div>
{/* Action Button */}
{!['completed', 'cancelled', 'reported'].includes(order.status) && (
<button
onClick={() => handleModifyOrder(order)}
className="w-full py-5 bg-accent/10 hover:bg-accent/20 text-accent font-black rounded-2xl text-[10px] uppercase tracking-[0.3em] border border-accent/20 transition-all active:scale-[0.98] flex items-center justify-center gap-3 group/btn"
>
<Edit className="w-4 h-4 transition-transform group-hover/btn:rotate-12" />
Modifier la commande
</button>
)}
</div>
</div>
</motion.div>
))}
</div>
)}
</div>
</div>
</div>
);
};
const AdminSettings = ({ config, setConfig, isAdmin, isManager }: { config: ShopConfig | null, setConfig: (c: ShopConfig) => void, isAdmin: boolean, isManager: boolean }) => {
const [activeTab, setActiveTab] = useState<'dashboard' | 'shop' | 'categories' | 'products' | 'team' | 'clients' | 'reports' | 'orders' | 'status' | 'meetup'>('dashboard');
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const navigate = useNavigate();
// Shop Settings State
const [shopName, setShopName] = useState('');
const [shopDescription, setShopDescription] = useState('');
const [shopLogo, setShopLogo] = useState('');
const [shopBanner, setShopBanner] = useState('');
const [managerChatId, setManagerChatId] = useState('');
const [orderManager, setOrderManager] = useState('');
const [channelUrl, setChannelUrl] = useState('');
const [welcomeMessage, setWelcomeMessage] = useState('');
const [infoText, setInfoText] = useState('');
const [isOpen, setIsOpen] = useState(true);
const [isAutoBroadcastEnabled, setIsAutoBroadcastEnabled] = useState(true);
const [isMeetupEnabled, setIsMeetupEnabled] = useState(false);
const [isVerificationEnabled, setIsVerificationEnabled] = useState(false);
const [accentColor, setAccentColor] = useState('#10B981');
const [orderDispatchMode, setOrderDispatchMode] = useState<'private' | 'group'>('private');
const [deliveryGroupId, setDeliveryGroupId] = useState('');
const [meetupGroupId, setMeetupGroupId] = useState('');
// Orders Tracking State
const [orders, setOrders] = useState<any[]>([]);
const [showOrderTracking, setShowOrderTracking] = useState(false);
const groupedOrders = useMemo(() => {
return {
pending: orders.filter(o => o.status === 'pending'),
taken: orders.filter(o => o.status === 'validated'),
completed: orders.filter(o => o.status === 'completed'),
cancelled: orders.filter(o => o.status === 'cancelled')
};
}, [orders]);
// Categories & Products State
const [categories, setCategories] = useState<Category[]>([]);
const [products, setProducts] = useState<Product[]>([]);
const [prices, setPrices] = useState<ProductPrice[]>([]);
// Team & Clients State
const [drivers, setDrivers] = useState<any[]>([]);
const [workers, setWorkers] = useState<any[]>([]);
const [botUsers, setBotUsers] = useState<any[]>([]);
const [searchQuery, setSearchQuery] = useState('');
// Editing State
const [editingProduct, setEditingProduct] = useState<Product | null>(null);
const [editingCategory, setEditingCategory] = useState<Category | null>(null);
const [broadcastMessage, setBroadcastMessage] = useState('');
const [broadcastTarget, setBroadcastTarget] = useState<'clients' | 'channels' | 'both'>('clients');
const [broadcastPhoto, setBroadcastPhoto] = useState('');
const [uploadingBroadcastPhoto, setUploadingBroadcastPhoto] = useState(false);
const broadcastPhotoInputRef = useRef<HTMLInputElement>(null);
const productPhotoInputRef = useRef<HTMLInputElement>(null);
// Logo Upload State
const [uploadingLogo, setUploadingLogo] = useState(false);
const [uploadingProductMedia, setUploadingProductMedia] = useState(false);
const [uploadingBanner, setUploadingBanner] = useState(false);
const fileInputRef = useRef<HTMLInputElement>(null);
const bannerInputRef = useRef<HTMLInputElement>(null);
useEffect(() => {
const checkAuth = async () => {
if (config) {
if (!isAdmin && !isManager) {
navigate('/');
return;
}
// Initialize shop settings
setShopName(config.shopName);
setShopDescription(config.shopDescription);
setShopLogo(config.shopLogo);
setShopBanner(config.shopBanner || '');
setManagerChatId(config.managerChatId);
setOrderManager(config.orderManager || '');
setChannelUrl(config.channelUrl);
setWelcomeMessage(config.welcomeMessage);
setInfoText(config.infoText);
setIsOpen(config.isOpen);
setIsAutoBroadcastEnabled(config.isAutoBroadcastEnabled);
setIsMeetupEnabled(!!config.isMeetupEnabled);
setIsVerificationEnabled(!!config.isVerificationEnabled);
setOrderDispatchMode(config.orderDispatchMode || 'private');
setDeliveryGroupId(config.deliveryGroupId || '');
setMeetupGroupId(config.meetupGroupId || '');
setAccentColor(config.accentColor || '#10B981');
// Fetch all data
// Fetch non-sensitive data directly from Supabase
const [
{ data: cats },
{ data: prods },
{ data: prcs }
] = await Promise.all([
supabase.from('categories').select('*').order('display_order', { ascending: true }),
supabase.from('products').select('*').order('display_order', { ascending: true }),
supabase.from('product_prices').select('*')
]);
setCategories(cats || []);
setProducts(prods || []);
setPrices(prcs || []);
// Fetch sensitive data via Secure Backend Proxy
const tgUser = (window as any).Telegram?.WebApp?.initDataUnsafe?.user;
if (tgUser && (isAdmin || isManager)) {
try {
const response = await fetch(`/api/admin/data?userId=${tgUser.id}&username=${tgUser.username || ''}`);
const adminData = await response.json();
if (!adminData.error) {
setDrivers(adminData.drivers || []);
setWorkers(adminData.workers || []);
setBotUsers(adminData.botUsers || []);
setOrders(adminData.orders || []);
}
} catch (err) {
console.error('Error fetching admin data:', err);
}
}
setLoading(false);
}
};
checkAuth();
// Real-time orders subscription
const ordersSubscription = supabase
.channel('orders-realtime')
.on('postgres_changes', { event: '*', table: 'orders', schema: 'public' }, (payload) => {
if (payload.eventType === 'INSERT') {
setOrders(prev => [payload.new, ...prev]);
} else if (payload.eventType === 'UPDATE') {
setOrders(prev => prev.map(o => o.id === payload.new.id ? payload.new : o));
} else if (payload.eventType === 'DELETE') {
setOrders(prev => prev.filter(o => o.id === payload.old.id));
}
})
.subscribe();
return () => {
supabase.removeChannel(ordersSubscription);
};
}, [config, navigate]);
const handleToggleShop = async (newStatus: boolean) => {
const execute = async () => {
setSaving(true);
try {
const tgUser = (window as any).Telegram?.WebApp?.initDataUnsafe?.user;
const response = await fetch('/api/admin/toggle-shop', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
userId: tgUser?.id?.toString(),
username: tgUser?.username,
isOpen: newStatus
})
});
const result = await response.json();
if (result.success) {
setIsOpen(newStatus);
// Refresh global config
const newConfig = await getAppConfig();
setConfig(newConfig);
(window as any).Telegram?.WebApp?.showAlert?.(`Shop ${newStatus ? 'OUVERT' : 'FERMÉ'} avec succès ! ${newStatus ? '🟢' : '🔴'}`);
if (!newStatus) {
(window as any).Telegram?.WebApp?.showAlert?.("Le rapport de session a été envoyé au manager.");
}
} else {
throw new Error(result.error);
}
} catch (err: any) {
(window as any).Telegram?.WebApp?.showAlert?.("Erreur: " + err.message);
} finally {
setSaving(false);
}
};
if ((window as any).Telegram?.WebApp?.showConfirm) {
(window as any).Telegram.WebApp.showConfirm(
`Voulez-vous vraiment ${newStatus ? 'OUVRIR' : 'FERMER'} le shop ?`,
(confirmed: boolean) => {
if (confirmed) execute();
}
);
} else {
if (confirm(`Voulez-vous vraiment ${newStatus ? 'OUVRIR' : 'FERMER'} le shop ?`)) {
execute();
}
}
};
const handleToggleBroadcast = async (newStatus: boolean) => {
setSaving(true);
try {
const tgUser = (window as any).Telegram?.WebApp?.initDataUnsafe?.user;
const response = await fetch('/api/admin/toggle-broadcast', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
userId: tgUser?.id?.toString(),
username: tgUser?.username,
isEnabled: newStatus
})
});
const result = await response.json();
if (result.success) {
setIsAutoBroadcastEnabled(newStatus);
// Refresh global config
const newConfig = await getAppConfig();
setConfig(newConfig);
(window as any).Telegram?.WebApp?.showAlert?.(`Message automatique ${newStatus ? 'ACTIVÉ' : 'DÉSACTIVÉ'} !`);
} else {
throw new Error(result.error);
}
} catch (err: any) {
(window as any).Telegram?.WebApp?.showAlert?.("Erreur: " + err.message);
} finally {
setSaving(false);
}
};
const handleLogoUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
setUploadingLogo(true);
try {
const fileExt = file.name.split('.').pop();
const fileName = `logo-${Math.random().toString(36).substring(7)}.${fileExt}`;
const filePath = `logos/${fileName}`;
const { error: uploadError } = await supabase.storage
.from('product-images')
.upload(filePath, file);
if (uploadError) throw uploadError;
const { data: { publicUrl } } = supabase.storage
.from('product-images')
.getPublicUrl(filePath);
setShopLogo(publicUrl);
(window as any).Telegram?.WebApp?.showAlert?.('Logo téléchargé avec succès ! 📸');
// Auto-save after upload to ensure persistence
handleSaveShopSettings({ logo_url: publicUrl });
} catch (error: any) {
(window as any).Telegram?.WebApp?.showAlert?.(`Erreur d'upload: ${error.message}`);
} finally {
setUploadingLogo(false);
}
};
const handleBannerUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
setUploadingBanner(true);
try {
const fileExt = file.name.split('.').pop();
const fileName = `banner-${Math.random().toString(36).substring(7)}.${fileExt}`;
const filePath = `banners/${fileName}`;
const { error: uploadError } = await supabase.storage
.from('product-images')
.upload(filePath, file);
if (uploadError) throw uploadError;
const { data: { publicUrl } } = supabase.storage
.from('product-images')
.getPublicUrl(filePath);
setShopBanner(publicUrl);
(window as any).Telegram?.WebApp?.showAlert?.('Bannière téléchargée avec succès ! 🖼️');
// Auto-save after upload to ensure persistence
handleSaveShopSettings({ banner_url: publicUrl });
} catch (error: any) {
(window as any).Telegram?.WebApp?.showAlert?.(`Erreur d'upload: ${error.message}`);
} finally {
setUploadingBanner(false);
}
};
const handleSaveShopSettings = async (overrides: any = {}) => {
setSaving(true);
try {
const settingsToSave = {
name: shopName,
description: shopDescription,
logo_url: shopLogo,
banner_url: shopBanner,
manager_chat_id: managerChatId,
order_manager: orderManager,
channel_url: channelUrl,
welcome_message: welcomeMessage,
info_text: infoText,
is_open: isOpen,
is_meetup_enabled: isMeetupEnabled,
is_verification_enabled: isVerificationEnabled,
accent_color: accentColor,
is_auto_broadcast_enabled: isAutoBroadcastEnabled,
order_dispatch_mode: orderDispatchMode,
delivery_group_id: deliveryGroupId,
meetup_group_id: meetupGroupId,
...overrides
};
const tgUser = (window as any).Telegram?.WebApp?.initDataUnsafe?.user;
const response = await fetch('/api/admin/settings', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
userId: tgUser?.id?.toString(),
username: tgUser?.username,
settings: settingsToSave
})
});
const result = await response.json();
if (!result.success) throw new Error(result.error);
// Re-fetch config to update global state
const newConfig = await getAppConfig();
setConfig(newConfig);
(window as any).Telegram?.WebApp?.showAlert?.('Réglages enregistrés avec succès ! ✅');
} catch (error: any) {
(window as any).Telegram?.WebApp?.showAlert?.(`Erreur: ${error.message}`);
} finally {
setSaving(false);
}
};
const addTeamMember = async (type: 'driver' | 'worker') => {
const tgId = prompt(`Entrez l'ID Telegram du ${type === 'driver' ? 'livreur' : 'bosseur'} :`);
if (!tgId) return;
const name = prompt(`Entrez le prénom du ${type === 'driver' ? 'livreur' : 'bosseur'} :`);
if (!name) return;
try {
const tgUser = (window as any).Telegram?.WebApp?.initDataUnsafe?.user;
const response = await fetch('/api/admin/team', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
userId: tgUser?.id?.toString(),
username: tgUser?.username,
type,
tgId,
name
})
});
const result = await response.json();
if (result.success) {
if (type === 'driver') setDrivers(prev => [result.data, ...prev]);
else setWorkers(prev => [result.data, ...prev]);
(window as any).Telegram?.WebApp?.showAlert?.('Membre ajouté avec succès ! ✅');
} else {
throw new Error(result.error);
}
} catch (error: any) {
(window as any).Telegram?.WebApp?.showAlert?.(`Erreur: ${error.message}`);
}
};
const deleteTeamMember = async (id: string, type: 'driver' | 'worker') => {
if (!confirm('Voulez-vous vraiment supprimer ce membre ?')) return;
try {
const tgUser = (window as any).Telegram?.WebApp?.initDataUnsafe?.user;
const response = await fetch('/api/admin/team', {
method: 'DELETE',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
userId: tgUser?.id?.toString(),
username: tgUser?.username,
type,
id
})
});
const result = await response.json();
if (result.success) {
if (type === 'driver') setDrivers(prev => prev.filter(d => d.id !== id));
else setWorkers(prev => prev.filter(w => w.id !== id));
(window as any).Telegram?.WebApp?.showAlert?.('Membre supprimé ! 🗑️');
} else {
throw new Error(result.error);
}
} catch (error: any) {
(window as any).Telegram?.WebApp?.showAlert?.(`Erreur: ${error.message}`);
}
};
const downloadClientList = async () => {
try {
const headers = ['ID Telegram', 'Username', 'Nom', 'Téléphone', 'Vérifié'];
const rows = botUsers.map(u => [
u.telegram_id,
u.username || '',
u.first_name || '',
u.phone || '',
u.is_verified ? 'Oui' : 'Non'
]);
const csvContent = [
headers.join(','),
...rows.map(r => r.join(','))
].join('\n');
const tgUser = (window as any).Telegram?.WebApp?.initDataUnsafe?.user;
const response = await fetch('/api/admin/send-document', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
userId: tgUser?.id?.toString(),
username: tgUser?.username,
content: csvContent,
filename: `clients_${new Date().toISOString().split('T')[0]}.csv`,
caption: `📋 Liste des clients (${botUsers.length} contacts)`
})
});
const result = await response.json();
if (result.success) {
(window as any).Telegram?.WebApp?.showAlert?.("Fichier CSV envoyé par message Telegram ! ✅");
} else {
throw new Error(result.error);
}
} catch (err: any) {
(window as any).Telegram?.WebApp?.showAlert?.("Erreur: " + err.message);
}
};
const toggleVerification = async (userId: string, currentStatus: boolean) => {
try {
const tgUser = (window as any).Telegram?.WebApp?.initDataUnsafe?.user;
const response = await fetch('/api/admin/verify-user', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
userId: tgUser?.id?.toString(),
username: tgUser?.username,
targetUserId: userId,
isVerified: !currentStatus
})
});
const result = await response.json();
if (result.success) {
setBotUsers(prev => prev.map(u => u.id === userId ? { ...u, is_verified: !currentStatus } : u));
} else {
throw new Error(result.error);
}
} catch (error: any) {
(window as any).Telegram?.WebApp?.showAlert?.(`Erreur: ${error.message}`);
}
};
const toggleStock = async (productId: string, currentStock: boolean) => {
try {
const tgUser = (window as any).Telegram?.WebApp?.initDataUnsafe?.user;
const response = await fetch('/api/admin/products', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
userId: tgUser?.id?.toString(),
username: tgUser?.username,
action: 'update',
productId,
updates: { is_in_stock: !currentStock }
})
});
const result = await response.json();
if (result.success) {
setProducts(prev => prev.map(p => p.id === productId ? { ...p, is_in_stock: !currentStock } : p));
} else {
throw new Error(result.error);
}
} catch (error: any) {
(window as any).Telegram?.WebApp?.showAlert?.(`Erreur: ${error.message}`);
}
};
const handleAddCategory = async (forcedType?: 'delivery' | 'meetup') => {
const name = prompt('Nom de la catégorie :');
if (!name) return;
const type = forcedType || prompt('Type (delivery ou meetup) :', 'delivery');
if (!type || (type !== 'delivery' && type !== 'meetup')) return;
const maxOrder = categories.length > 0 ? Math.max(...categories.map(c => c.display_order || 0)) : 0;
try {
const tgUser = (window as any).Telegram?.WebApp?.initDataUnsafe?.user;
const response = await fetch('/api/admin/categories', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
userId: tgUser?.id?.toString(),
username: tgUser?.username,
action: 'insert',
category: { name, type, display_order: maxOrder + 1 }
})
});
const result = await response.json();
if (result.success) {
setCategories(prev => [...prev, result.data]);
} else {
throw new Error(result.error);
}
} catch (error: any) {
(window as any).Telegram?.WebApp?.showAlert?.(`Erreur: ${error.message}`);
}
};
const handleReorderCategories = async (newFilteredOrder: Category[], type: 'delivery' | 'meetup') => {
const otherTypeCategories = categories.filter(c => c.type !== type);
const updatedCategories = [...newFilteredOrder, ...otherTypeCategories];
setCategories(updatedCategories);
try {
const tgUser = (window as any).Telegram?.WebApp?.initDataUnsafe?.user;
for (let i = 0; i < updatedCategories.length; i++) {
const cat = updatedCategories[i];
await fetch('/api/admin/categories', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
userId: tgUser?.id?.toString(),
username: tgUser?.username,
action: 'update',
categoryId: cat.id,
updates: { display_order: i }
})
});
}
} catch (error: any) {
console.error('Reorder Categories Error:', error);
}
};
const handleReorderProducts = async (newFilteredOrder: (Product & { prices?: ProductPrice[] })[], type: 'delivery' | 'meetup') => {
const otherTypeProducts = products.filter(p => p.type !== type);
const updatedProducts = [...newFilteredOrder, ...otherTypeProducts];
setProducts(updatedProducts);
try {
const tgUser = (window as any).Telegram?.WebApp?.initDataUnsafe?.user;
for (let i = 0; i < updatedProducts.length; i++) {
const prod = updatedProducts[i];
await fetch('/api/admin/products', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
userId: tgUser?.id?.toString(),
username: tgUser?.username,
action: 'update',
productId: prod.id,
updates: { display_order: i }
})
});
}
} catch (error: any) {
console.error('Reorder Products Error:', error);
}
};
const handleDeleteCategory = async (id: string) => {
if (!confirm('Supprimer cette catégorie ? Les produits liés seront orphelins.')) return;
try {
const tgUser = (window as any).Telegram?.WebApp?.initDataUnsafe?.user;
const response = await fetch('/api/admin/categories', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
userId: tgUser?.id?.toString(),
username: tgUser?.username,
action: 'delete',
categoryId: id
})
});
const result = await response.json();
if (result.success) {
setCategories(prev => prev.filter(c => c.id !== id));
setProducts(prev => prev.filter(p => p.category_id !== id));
} else {
throw new Error(result.error);
}
} catch (error: any) {
(window as any).Telegram?.WebApp?.showAlert?.(`Erreur: ${error.message}`);
}
};
const handleAddProduct = async (forcedType?: 'delivery' | 'meetup') => {
const name = prompt('Nom du produit :');
if (!name) return;
const type = forcedType || prompt('Type (delivery ou meetup) :', 'delivery') as 'delivery' | 'meetup';
if (!type) return;
const availableCats = categories.filter(c => c.type === type);
if (availableCats.length === 0) {
(window as any).Telegram?.WebApp?.showAlert?.(`Aucune catégorie de type "${type}" disponible. Créez-en une d'abord.`);
return;
}
const catList = availableCats.map((c, i) => `${i + 1}. ${c.name}`).join('\n');
const choice = prompt(`Sélectionnez la catégorie (entrez le chiffre) :\n${catList}`);
if (!choice) return;
const index = parseInt(choice) - 1;
const selectedCat = availableCats[index];
if (!selectedCat) {
(window as any).Telegram?.WebApp?.showAlert?.("Choix invalide.");
return;
}
const maxOrder = products.length > 0 ? Math.max(...products.map(p => p.display_order || 0)) : 0;
try {
const tgUser = (window as any).Telegram?.WebApp?.initDataUnsafe?.user;
const response = await fetch('/api/admin/products', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
userId: tgUser?.id?.toString(),
username: tgUser?.username,
action: 'insert',
product: {
name,
category_id: selectedCat.id,
type,
is_in_stock: true,
display_order: maxOrder + 1
}
})
});
const result = await response.json();
if (result.success) {
setProducts(prev => [...prev, result.data]);
setEditingProduct(result.data);
} else {
throw new Error(result.error);
}
} catch (error: any) {
(window as any).Telegram?.WebApp?.showAlert?.(`Erreur: ${error.message}`);
}
};
const handleDeleteProduct = async (id: string) => {
if (!confirm('Supprimer ce produit ?')) return;
try {
const tgUser = (window as any).Telegram?.WebApp?.initDataUnsafe?.user;
const response = await fetch('/api/admin/products', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
userId: tgUser?.id?.toString(),
username: tgUser?.username,
action: 'delete',
productId: id
})
});
const result = await response.json();
if (result.success) {
setProducts(prev => prev.filter(p => p.id !== id));
setPrices(prev => prev.filter(pr => pr.product_id !== id));
} else {
throw new Error(result.error);
}
} catch (error: any) {
(window as any).Telegram?.WebApp?.showAlert?.(`Erreur: ${error.message}`);
}
};
const handleProductPhotoUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
const files = e.target.files;
if (!files || files.length === 0 || !editingProduct) return;
const getMedia = (url: string | null | undefined): { url: string, type: 'image' | 'video' }[] => {
if (!url) return [];
try {
const parsed = JSON.parse(url);
if (Array.isArray(parsed)) {
return parsed.map(item => typeof item === 'string' ? { url: item, type: item.match(/\.(mp4|webm|ogg|mov)$/i) ? 'video' : 'image' } : item);
}
} catch (e) {}
return url ? [{ url, type: url.match(/\.(mp4|webm|ogg|mov)$/i) ? 'video' : 'image' }] : [];
};
setUploadingProductMedia(true);
try {
const currentMedia = getMedia(editingProduct.image_url);
const newMediaItems: { url: string, type: 'image' | 'video' }[] = [...currentMedia];
for (let i = 0; i < files.length; i++) {
const file = files[i];
// Check file size (max 50MB for videos)
if (file.size > 50 * 1024 * 1024) {
(window as any).Telegram?.WebApp?.showAlert?.(`Le fichier "${file.name}" est trop volumineux (max 50Mo).`);
continue;
}
const fileExt = file.name.split('.').pop();
const isVideo = file.type.startsWith('video/') || ['mp4', 'webm', 'ogg', 'mov'].includes(fileExt?.toLowerCase() || '');
const fileName = `prod-${Math.random().toString(36).substring(7)}.${fileExt}`;
const filePath = `products/${fileName}`;
const { error: uploadError } = await supabase.storage.from('product-images').upload(filePath, file, {
contentType: file.type || (isVideo ? 'video/mp4' : 'image/jpeg'),
upsert: false
});
if (uploadError) throw uploadError;
const { data: { publicUrl } } = supabase.storage.from('product-images').getPublicUrl(filePath);
newMediaItems.push({ url: publicUrl, type: isVideo ? 'video' : 'image' });
}
const newImageUrl = JSON.stringify(newMediaItems);
const tgUser = (window as any).Telegram?.WebApp?.initDataUnsafe?.user;
const response = await fetch('/api/admin/products', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
userId: tgUser?.id?.toString(),
username: tgUser?.username,
action: 'update',
productId: editingProduct.id,
updates: { image_url: newImageUrl }
})
});
const result = await response.json();
if (!result.success) throw new Error(result.error);
setEditingProduct({ ...editingProduct, image_url: newImageUrl });
setProducts(prev => prev.map(p => p.id === editingProduct.id ? { ...p, image_url: newImageUrl } : p));
(window as any).Telegram?.WebApp?.showAlert?.('Média(s) ajouté(s) ! 📸');
} catch (error: any) {
(window as any).Telegram?.WebApp?.showAlert?.(`Erreur: ${error.message}`);
} finally {
setUploadingProductMedia(false);
}
};
const handleReorderMedia = async (index: number, direction: 'up' | 'down') => {
if (!editingProduct) return;
const getMedia = (url: string | null | undefined): { url: string, type: 'image' | 'video' }[] => {
if (!url) return [];
try {
const parsed = JSON.parse(url);
if (Array.isArray(parsed)) {
return parsed.map(item => typeof item === 'string' ? { url: item, type: item.match(/\.(mp4|webm|ogg|mov)$/i) ? 'video' : 'image' } : item);
}
} catch (e) {}
return url ? [{ url, type: url.match(/\.(mp4|webm|ogg|mov)$/i) ? 'video' : 'image' }] : [];
};
const media = getMedia(editingProduct.image_url);
if (direction === 'up' && index === 0) return;
if (direction === 'down' && index === media.length - 1) return;
const newMedia = [...media];
const targetIndex = direction === 'up' ? index - 1 : index + 1;
[newMedia[index], newMedia[targetIndex]] = [newMedia[targetIndex], newMedia[index]];
const newImageUrl = JSON.stringify(newMedia);
try {
const tgUser = (window as any).Telegram?.WebApp?.initDataUnsafe?.user;
const response = await fetch('/api/admin/products', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
userId: tgUser?.id?.toString(),
username: tgUser?.username,
action: 'update',
productId: editingProduct.id,
updates: { image_url: newImageUrl }
})
});
const result = await response.json();
if (result.success) {
setEditingProduct({ ...editingProduct, image_url: newImageUrl });
setProducts(prev => prev.map(p => p.id === editingProduct.id ? { ...p, image_url: newImageUrl } : p));
}
} catch (error) {
console.error('Reorder Media Error:', error);
}
};
const handleDeleteMedia = async (index: number) => {
if (!editingProduct || !confirm('Supprimer ce média ?')) return;
const getMedia = (url: string | null | undefined): { url: string, type: 'image' | 'video' }[] => {
if (!url) return [];
try {
const parsed = JSON.parse(url);
if (Array.isArray(parsed)) {
return parsed.map(item => typeof item === 'string' ? { url: item, type: item.match(/\.(mp4|webm|ogg|mov)$/i) ? 'video' : 'image' } : item);
}
} catch (e) {}
return url ? [{ url, type: url.match(/\.(mp4|webm|ogg|mov)$/i) ? 'video' : 'image' }] : [];
};
const media = getMedia(editingProduct.image_url);
const newMedia = media.filter((_, i) => i !== index);
const newImageUrl = JSON.stringify(newMedia);
try {
const tgUser = (window as any).Telegram?.WebApp?.initDataUnsafe?.user;
const response = await fetch('/api/admin/products', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
userId: tgUser?.id?.toString(),
username: tgUser?.username,
action: 'update',
productId: editingProduct.id,
updates: { image_url: newImageUrl }
})
});
const result = await response.json();
if (result.success) {
setEditingProduct({ ...editingProduct, image_url: newImageUrl });
setProducts(prev => prev.map(p => p.id === editingProduct.id ? { ...p, image_url: newImageUrl } : p));
}
} catch (error) {
console.error('Delete Media Error:', error);
}
};
const handleAddPrice = async (productId: string) => {
const quantity = prompt('Libellé (ex: 10g, 1 pièce) :');
if (!quantity) return;
const price = parseFloat(prompt('Prix (€) :') || '0');
if (isNaN(price)) return;
try {
const tgUser = (window as any).Telegram?.WebApp?.initDataUnsafe?.user;
const response = await fetch('/api/admin/prices', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
userId: tgUser?.id?.toString(),
username: tgUser?.username,
action: 'insert',
price: {
product_id: productId,
quantity,
price
}
})
});
const result = await response.json();
if (result.success) {
setPrices(prev => [...prev, result.data]);
} else {
throw new Error(result.error);
}
} catch (error: any) {
(window as any).Telegram?.WebApp?.showAlert?.(`Erreur: ${error.message}`);
}
};
const handleDeletePrice = async (priceId: string) => {
try {
const tgUser = (window as any).Telegram?.WebApp?.initDataUnsafe?.user;
const response = await fetch('/api/admin/prices', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
userId: tgUser?.id?.toString(),
username: tgUser?.username,
action: 'delete',
priceId
})
});
const result = await response.json();
if (result.success) {
setPrices(prev => prev.filter(p => p.id !== priceId));
} else {
throw new Error(result.error);
}
} catch (error: any) {
(window as any).Telegram?.WebApp?.showAlert?.(`Erreur: ${error.message}`);
}
};
const handleBroadcastPhotoUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
setUploadingBroadcastPhoto(true);
try {
const fileExt = file.name.split('.').pop();
const fileName = `bc-${Math.random().toString(36).substring(7)}.${fileExt}`;
const filePath = `broadcasts/${fileName}`;
const { error: uploadError } = await supabase.storage.from('product-images').upload(filePath, file);
if (uploadError) throw uploadError;
const { data: { publicUrl } } = supabase.storage.from('product-images').getPublicUrl(filePath);
setBroadcastPhoto(publicUrl);
} catch (error: any) {
(window as any).Telegram?.WebApp?.showAlert?.(`Erreur: ${error.message}`);
} finally {
setUploadingBroadcastPhoto(false);
}
};
const generateSessionReport = async () => {
try {
const tgUser = (window as any).Telegram?.WebApp?.initDataUnsafe?.user;
const response = await fetch(`/api/admin/stats?userId=${tgUser?.id?.toString()}&username=${tgUser?.username || ''}`);
const stats = await response.json();
if (stats.error) throw new Error(stats.error);
let report = `📊 RAPPORT DE SESSION\n\n` +
`📦 TOTAL COMMANDES: ${stats.ordersCount}\n` +
`✅ EFFECTUÉES: ${stats.statusStats?.completed || 0}\n` +
`🚚 EN COURS: ${stats.statusStats?.taken || 0}\n` +
`❌ ANNULÉES: ${stats.statusStats?.cancelled || 0}\n` +
`⏳ EN ATTENTE: ${stats.statusStats?.pending || 0}\n` +
`💰 CA TOTAL: ${stats.totalRevenue}€\n\n`;
if (stats.driverStats?.length > 0) {
report += `🚚 LIVREURS:\n`;
stats.driverStats.forEach((d: any) => {
if (d.count > 0) {
report += `- ${d.name || d.username || d.id}: ${d.count} livr. (${d.revenue}€)\n`;
}
});
report += `\n`;
}
if (stats.workerStats?.length > 0) {
report += `🤝 MEETUP:\n`;
stats.workerStats.forEach((w: any) => {
if (w.count > 0) {
report += `- ${w.name || w.username || w.id}: ${w.count} rdv (${w.revenue}€)\n`;
}
});
report += `\n`;
}
if (stats.productStats) {
const productEntries = Object.entries(stats.productStats as Record<string, any>);
if (productEntries.length > 0) {
report += `📦 DÉTAIL DES VENTES :\n`;
productEntries.sort((a, b) => b[1].revenue - a[1].revenue).forEach(([name, data]) => {
report += `• ${name}\n └ Qté : x${data.qty} | Total : ${data.revenue}€\n`;
const formats = Object.entries(data.formats as Record<string, number>);
if (formats.length > 0) {
report += ` Formats : ${formats.map(([f, q]) => `${f} (x${q})`).join(', ')}\n`;
}
});
report += `\n`;
}
}
report += `Généré le ${new Date().toLocaleString()}`;
const sendResponse = await fetch('/api/admin/send-message', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
userId: tgUser?.id?.toString(),
username: tgUser?.username,
message: report
})
});
const result = await sendResponse.json();
if (result.success) {
(window as any).Telegram?.WebApp?.showAlert?.("Rapport envoyé par message Telegram ! ✅");
} else {
throw new Error(result.error);
}
} catch (err: any) {
(window as any).Telegram?.WebApp?.showAlert?.("Erreur lors de la génération du rapport: " + err.message);
}
};
const handleBroadcast = async (target: 'clients' | 'channels' | 'both') => {
if (!broadcastMessage.trim()) return;
try {
const tgUser = (window as any).Telegram?.WebApp?.initDataUnsafe?.user;
const response = await fetch('/api/admin/broadcast', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
userId: tgUser?.id?.toString(),
username: tgUser?.username,
message: broadcastMessage,
target,
photoUrl: broadcastPhoto || undefined
})
});
const result = await response.json();
if (result.success) {
(window as any).Telegram?.WebApp?.showAlert?.("Diffusion envoyée avec succès ! ✅");
setBroadcastMessage('');
setBroadcastPhoto('');
} else {
throw new Error(result.error);
}
} catch (err: any) {
(window as any).Telegram?.WebApp?.showAlert?.("Erreur lors de la diffusion: " + err.message);
}
};
const tabs = [
{ id: 'status', label: 'Statut', icon: Power },
{ id: 'orders', label: 'Gestion Commandes', icon: Package },
{ id: 'shop', label: 'Boutique', icon: Layout },
{ id: 'meetup', label: 'Meet-up', icon: Users },
{ id: 'team', label: 'Livreurs', icon: Truck },
{ id: 'clients', label: 'Clients', icon: Users },
{ id: 'categories', label: 'Catégories (Livr.)', icon: LayoutGrid },
{ id: 'products', label: 'Produits (Livr.)', icon: Package },
{ id: 'reports', label: 'Rapports', icon: FileText },
];
if (loading) return (
<div className="flex flex-col items-center justify-center h-screen gap-4">
<Loader2 className="w-10 h-10 text-accent animate-spin" />
<p className="text-text-muted font-display uppercase tracking-widest text-xs">Chargement du panneau...</p>
</div>
);
return (
<div className="pb-40 pt-6 px-6 min-h-screen">
<div className="flex items-center justify-between mb-8">
<div className="flex items-center gap-4">
{activeTab !== 'dashboard' && (
<button
onClick={() => setActiveTab('dashboard')}
className="w-10 h-10 rounded-full glass flex items-center justify-center text-white active:scale-90 transition-transform"
>
<ArrowLeft className="w-5 h-5" />
</button>
)}
<div>
<h1 className="text-2xl font-black text-white tracking-tighter uppercase italic">
{activeTab === 'dashboard' ? 'Tableau de bord' : tabs.find(t => t.id === activeTab)?.label || 'Réglages'}
</h1>
<p className="text-[10px] text-accent font-bold tracking-[0.3em] uppercase">Panneau d'administration</p>
</div>
</div>
<button
onClick={() => navigate('/')}
className="w-10 h-10 rounded-full glass flex items-center justify-center text-white"
>
<CloseIcon className="w-5 h-5" />
</button>
</div>
<AnimatePresence mode="wait">
{activeTab === 'dashboard' && (
<motion.div
key="dashboard"
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, scale: 0.95 }}
className="grid grid-cols-2 gap-4"
>
{tabs.map((tab) => (
<button
key={tab.id}
onClick={() => setActiveTab(tab.id as any)}
className="glass p-6 rounded-[2.5rem] flex flex-col items-center gap-4 hover:border-accent/40 transition-all group active:scale-95 border border-white/5"
>
<div className="w-14 h-14 rounded-2xl bg-accent/10 flex items-center justify-center group-hover:bg-accent group-hover:text-white transition-all">
<tab.icon className={cn("w-7 h-7 text-accent group-hover:text-white transition-colors")} />
</div>
<span className="text-[10px] font-black text-white uppercase tracking-widest text-center leading-tight font-display">
{tab.label}
</span>
</button>
))}
</motion.div>
)}
{activeTab === 'orders' && (
<motion.div
key="orders-settings"
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: -20 }}
className="space-y-6"
>
<div className="glass rounded-[2rem] p-6 space-y-6">
<div className="flex items-center gap-4">
<div className="w-12 h-12 rounded-2xl bg-accent/10 flex items-center justify-center">
<Package className="w-6 h-6 text-accent" />
</div>
<div>
<h2 className="text-lg font-black text-white uppercase italic tracking-tight">Gestion des commandes</h2>
<p className="text-[10px] text-text-muted font-bold tracking-widest uppercase">Mode d'envoi des commandes</p>
</div>
</div>
<div className="grid grid-cols-2 gap-3">
<button
onClick={() => setOrderDispatchMode('private')}
className={cn(
"p-4 rounded-2xl border transition-all flex flex-col items-center gap-2",
orderDispatchMode === 'private'
? "bg-accent/20 border-accent text-accent"
: "bg-white/5 border-white/5 text-text-muted"
)}
>
<MessageSquare className="w-6 h-6" />
<span className="text-[10px] font-black uppercase tracking-widest">Bot (Privé)</span>
</button>
<button
disabled
className={cn(
"p-4 rounded-2xl border transition-all flex flex-col items-center gap-2 opacity-40 grayscale cursor-not-allowed",
"bg-white/5 border-white/5 text-text-muted"
)}
>
<Users className="w-6 h-6" />
<span className="text-[10px] font-black uppercase tracking-widest">Groupes</span>
<span className="text-[8px] font-black text-accent uppercase tracking-widest bg-accent/10 px-2 py-0.5 rounded-full">A VENIR</span>
</button>
</div>
{orderDispatchMode === 'group' && (
<div className="space-y-4 pt-4 border-t border-white/5 opacity-40 grayscale pointer-events-none relative">
<div className="absolute inset-0 z-10 flex items-center justify-center">
<span className="bg-accent text-white text-[10px] font-black uppercase tracking-widest px-4 py-2 rounded-full shadow-lg">A VENIR</span>
</div>
<div className="space-y-2">
<label className="text-[10px] font-black text-text-muted uppercase tracking-widest ml-4">ID Groupe Livraison</label>
<input
type="text"
readOnly
value={deliveryGroupId}
placeholder="-100..."
className="w-full bg-white/5 border border-white/5 rounded-2xl px-4 py-3 text-white text-sm outline-none transition-all"
/>
</div>
<div className="space-y-2">
<label className="text-[10px] font-black text-text-muted uppercase tracking-widest ml-4">ID Groupe Meet-up</label>
<input
type="text"
readOnly
value={meetupGroupId}
placeholder="-100..."
className="w-full bg-white/5 border border-white/5 rounded-2xl px-4 py-3 text-white text-sm outline-none transition-all"
/>
</div>
<p className="text-[10px] text-text-muted italic px-4">
💡 Tapez <b>/groupe</b> dans vos groupes pour obtenir leurs IDs.
</p>
</div>
)}
<button
onClick={() => handleSaveShopSettings()}
data-save-settings="true"
disabled={saving}
className="w-full bg-accent text-white font-black py-4 rounded-2xl shadow-[0_0_20px_rgba(16,185,129,0.3)] flex items-center justify-center gap-3 active:scale-95 transition-all disabled:opacity-50"
>
{saving ? <Loader2 className="w-5 h-5 animate-spin" /> : <Save className="w-5 h-5" />}
<span className="text-sm uppercase tracking-widest">Enregistrer les réglages</span>
</button>
<div className="pt-6 border-t border-white/5">
<button
onClick={() => setShowOrderTracking(!showOrderTracking)}
className={cn(
"w-full py-4 rounded-2xl flex items-center justify-center gap-3 active:scale-95 transition-all border",
showOrderTracking
? "bg-accent/10 border-accent text-accent"
: "bg-white/5 border-white/10 text-white"
)}
>
<Clock className="w-5 h-5" />
<span className="text-sm uppercase tracking-widest font-black">
{showOrderTracking ? "Masquer le suivi" : "Suivi des commandes en temps réel"}
</span>
</button>
</div>
<AnimatePresence>
{showOrderTracking && (
<motion.div
initial={{ opacity: 0, height: 0 }}
animate={{ opacity: 1, height: 'auto' }}
exit={{ opacity: 0, height: 0 }}
className="space-y-6 overflow-hidden"
>
{[
{ id: 'pending', label: 'En attente', icon: Clock, color: 'text-yellow-500', bg: 'bg-yellow-500/10', list: groupedOrders.pending },
{ id: 'taken', label: 'En cours', icon: Truck, color: 'text-blue-500', bg: 'bg-blue-500/10', list: groupedOrders.taken },
{ id: 'completed', label: 'Encaissées', icon: CheckCircle2, color: 'text-accent', bg: 'bg-accent/10', list: groupedOrders.completed },
{ id: 'cancelled', label: 'Annulées', icon: XCircle, color: 'text-red-500', bg: 'bg-red-500/10', list: groupedOrders.cancelled }
].map((section) => (
<div key={section.id} className="space-y-4">
<div className="flex items-center justify-between px-2">
<div className="flex items-center gap-2">
<div className={cn("w-8 h-8 rounded-lg flex items-center justify-center", section.bg)}>
<section.icon className={cn("w-4 h-4", section.color)} />
</div>
<h3 className="text-[10px] font-black text-white uppercase tracking-widest">{section.label}</h3>
</div>
<span className="bg-white/5 text-white text-[10px] font-black px-2 py-1 rounded-lg">{section.list.length}</span>
</div>
<div className="space-y-3">
{section.list.length === 0 ? (
<p className="text-[10px] text-text-muted italic text-center py-4">Aucune commande {section.label.toLowerCase()}</p>
) : (
section.list.map((order) => (
<div key={order.id} className="bg-white/5 border border-white/5 rounded-2xl p-4 space-y-3">
<div className="flex justify-between items-start">
<div className="flex items-center gap-2">
<div className={cn(
"w-8 h-8 rounded-lg flex items-center justify-center",
order.type === 'meetup' ? "bg-blue-500/10 text-blue-500" : "bg-purple-500/10 text-purple-500"
)}>
{order.type === 'meetup' ? <Users className="w-4 h-4" /> : <Truck className="w-4 h-4" />}
</div>
<div>
<p className="text-[10px] font-black text-white uppercase tracking-widest">{order.type === 'meetup' ? 'Meet-up' : 'Livraison'}</p>
<p className="text-[8px] text-text-muted font-bold uppercase tracking-widest">{new Date(order.created_at).toLocaleString('fr-FR')}</p>
</div>
</div>
<div className="text-right">
<p className="text-sm font-black text-accent">{order.total}€</p>
<p className="text-[8px] text-text-muted font-bold uppercase tracking-widest">ID: {order.id.slice(0, 8)}</p>
</div>
</div>
<div className="space-y-1">
{order.items?.map((item: any, idx: number) => (
<div key={idx} className="flex justify-between text-[10px]">
<span className="text-white font-bold">{item.productName} ({item.quantityLabel}) x{item.count}</span>
<span className="text-text-muted">{item.price * item.count}€</span>
</div>
))}
</div>
<div className="pt-2 border-t border-white/5 space-y-2">
<div className="flex items-center gap-2">
<UserCheck className="w-3 h-3 text-text-muted" />
<span className="text-[10px] text-white">Client: <b>{order.client_name}</b></span>
</div>
{order.driver_id && (
<div className="flex items-center gap-2">
<Truck className="w-3 h-3 text-accent" />
<span className="text-[10px] text-white">
Pris par: <b>{
[...drivers, ...workers].find(d => d.telegram_id === order.driver_id)?.first_name || "Inconnu"
}</b>
</span>
</div>
)}
{order.status === 'completed' && order.completed_by_name && (
<div className="flex items-center gap-2">
<CheckCircle2 className="w-3 h-3 text-accent" />
<span className="text-[10px] text-white">Encaissé par: <b>{order.completed_by_name}</b></span>
</div>
)}
<div className="flex items-center gap-2">
<MapPin className="w-3 h-3 text-text-muted" />
<span className="text-[10px] text-white line-clamp-1">Lieu: <b>{order.address}</b></span>
</div>
</div>
</div>
))
)}
</div>
</div>
))}
</motion.div>
)}
</AnimatePresence>
</div>
</motion.div>
)}
{activeTab === 'status' && (
<motion.div
key="status-settings"
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: -20 }}
className="space-y-6"
>
<div className="glass rounded-[2rem] p-6 space-y-6">
<div className="flex items-center justify-between">
<div>
<p className="text-sm font-bold text-white uppercase tracking-tight">État du Shop</p>
<p className="text-[10px] text-text-muted uppercase font-bold tracking-wider">{isOpen ? 'Ouvert aux commandes' : 'Fermé temporairement'}</p>
</div>
<button
onClick={() => handleToggleShop(!isOpen)}
disabled={saving}
className={cn(
"w-14 h-7 rounded-full relative transition-all duration-300",
isOpen ? "bg-accent" : "bg-white/10",
saving && "opacity-50"
)}
>
<div className={cn(
"absolute top-1 w-5 h-5 rounded-full bg-white transition-all duration-300 shadow-lg",
isOpen ? "left-8" : "left-1"
)} />
</button>
</div>
<div className="h-px bg-white/5 mx-2" />
<div className="flex items-center justify-between">
<div>
<p className="text-sm font-bold text-white uppercase tracking-tight">Message d'ouverture</p>
<p className="text-[10px] text-text-muted uppercase font-bold tracking-wider">{isAutoBroadcastEnabled ? 'Envoi automatique activé' : 'Envoi automatique désactivé'}</p>
</div>
<button
onClick={() => handleToggleBroadcast(!isAutoBroadcastEnabled)}
disabled={saving}
className={cn(
"w-14 h-7 rounded-full relative transition-all duration-300",
isAutoBroadcastEnabled ? "bg-accent" : "bg-white/10",
saving && "opacity-50"
)}
>
<div className={cn(
"absolute top-1 w-5 h-5 rounded-full bg-white transition-all duration-300 shadow-lg",
isAutoBroadcastEnabled ? "left-8" : "left-1"
)} />
</button>
</div>
</div>
{/* Broadcast Section */}
<div className="glass rounded-[2rem] p-6 space-y-6">
<div className="flex items-center gap-4">
<div className="w-12 h-12 rounded-2xl bg-blue-500/10 flex items-center justify-center">
<Send className="w-6 h-6 text-blue-500" />
</div>
<div>
<h2 className="text-lg font-black text-white uppercase italic tracking-tight">Diffusion (Broadcast)</h2>
<p className="text-[10px] text-text-muted font-bold tracking-widest uppercase">Envoyer un message groupé</p>
</div>
</div>
{/* Photo Upload for Broadcast */}
<div className="flex flex-col items-center gap-4 py-2">
<div className="relative w-full h-32 rounded-2xl overflow-hidden bg-white/5 border border-white/5 flex items-center justify-center group">
{broadcastPhoto ? (
<img src={broadcastPhoto} alt="Broadcast" className="w-full h-full object-cover" />
) : (
<div className="flex flex-col items-center gap-2 text-white/20">
<ImagePlus className="w-8 h-8" />
<span className="text-[8px] font-black uppercase tracking-widest">Ajouter une photo</span>
</div>
)}
<button
onClick={() => broadcastPhotoInputRef.current?.click()}
disabled={uploadingBroadcastPhoto}
className="absolute inset-0 bg-black/40 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity"
>
{uploadingBroadcastPhoto ? <Loader2 className="w-6 h-6 animate-spin text-white" /> : <Plus className="w-6 h-6 text-white" />}
</button>
<input type="file" ref={broadcastPhotoInputRef} onChange={handleBroadcastPhotoUpload} className="hidden" accept="image/*" />
{broadcastPhoto && (
<button
onClick={() => setBroadcastPhoto('')}
className="absolute top-2 right-2 p-1.5 bg-red-500 text-white rounded-lg shadow-lg"
>
<Trash2 className="w-3 h-3" />
</button>
)}
</div>
</div>
<div className="space-y-4">
<div className="space-y-2">
<label className="text-[10px] font-black text-accent uppercase tracking-widest ml-2">Cible de diffusion</label>
<div className="grid grid-cols-3 gap-2">
<button
onClick={() => setBroadcastTarget('clients')}
className={cn(
"flex flex-col items-center gap-2 p-3 rounded-2xl border transition-all active:scale-95",
broadcastTarget === 'clients' ? "bg-accent/20 border-accent text-accent" : "bg-white/5 border-white/5 text-white/40"
)}
>
<Users className="w-5 h-5" />
<span className="text-[8px] font-black uppercase tracking-widest">Privé</span>
</button>
<button
onClick={() => setBroadcastTarget('channels')}
className={cn(
"flex flex-col items-center gap-2 p-3 rounded-2xl border transition-all active:scale-95",
broadcastTarget === 'channels' ? "bg-accent/20 border-accent text-accent" : "bg-white/5 border-white/5 text-white/40"
)}
>
<LayoutGrid className="w-5 h-5" />
<span className="text-[8px] font-black uppercase tracking-widest">Canaux</span>
</button>
<button
onClick={() => setBroadcastTarget('both')}
className={cn(
"flex flex-col items-center gap-2 p-3 rounded-2xl border transition-all active:scale-95",
broadcastTarget === 'both' ? "bg-accent/20 border-accent text-accent" : "bg-white/5 border-white/5 text-white/40"
)}
>
<Send className="w-5 h-5" />
<span className="text-[8px] font-black uppercase tracking-widest">Les deux</span>
</button>
</div>
</div>
<div className="space-y-2">
<label className="text-[10px] font-black text-accent uppercase tracking-widest ml-2">Message à diffuser</label>
<textarea
value={broadcastMessage}
onChange={(e) => setBroadcastMessage(e.target.value)}
placeholder="Écrivez votre message ici..."
className="w-full bg-bg-dark/50 border border-white/5 rounded-2xl px-4 py-3 text-white text-sm focus:border-accent/50 outline-none transition-all min-h-[120px]"
/>
</div>
<button
onClick={() => handleBroadcast(broadcastTarget)}
disabled={!broadcastMessage.trim()}
className="w-full bg-accent text-white font-black py-4 rounded-2xl shadow-[0_10px_30px_rgba(16,185,129,0.3)] flex items-center justify-center gap-3 active:scale-95 transition-all disabled:opacity-50"
>
<Send className="w-5 h-5" />
<span className="text-sm uppercase tracking-[0.2em]">DIFFUSER</span>
</button>
</div>
</div>
</motion.div>
)}
{activeTab === 'shop' && (
<motion.div
key="shop-settings"
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: -20 }}
className="space-y-6"
>
<div className="glass rounded-[2rem] p-6 space-y-6">
{/* Logo Section */}
<div className="flex flex-col items-center gap-4 py-4">
<div className="relative group">
<div className="w-24 h-24 rounded-3xl overflow-hidden border-2 border-accent/30 shadow-[0_0_20px_rgba(16,185,129,0.2)]">
<ImageWithFallback src={shopLogo} alt="Logo" className="w-full h-full object-cover" />
</div>
<button
onClick={() => fileInputRef.current?.click()}
disabled={uploadingLogo}
className="absolute -bottom-2 -right-2 w-10 h-10 rounded-xl bg-accent text-white flex items-center justify-center shadow-lg active:scale-90 transition-all disabled:opacity-50"
>
{uploadingLogo ? <Loader2 className="w-5 h-5 animate-spin" /> : <ImagePlus className="w-5 h-5" />}
</button>
<input
type="file"
ref={fileInputRef}
onChange={handleLogoUpload}
accept="image/*"
className="hidden"
/>
</div>
<p className="text-[10px] font-black text-accent uppercase tracking-widest">Logo du Shop</p>
</div>
{/* Banner Section */}
<div className="glass rounded-3xl p-6 space-y-4">
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<div className="w-10 h-10 rounded-xl bg-accent/10 flex items-center justify-center">
<Layout className="w-5 h-5 text-accent" />
</div>
<div>
<h3 className="text-xs font-black text-white uppercase italic tracking-tight">Bannière d'accueil</h3>
<p className="text-[8px] text-text-muted font-bold uppercase tracking-widest">Image d'en-tête du site</p>
</div>
</div>
<button
onClick={() => bannerInputRef.current?.click()}
disabled={uploadingBanner}
className="w-10 h-10 rounded-xl bg-white/5 border border-white/5 flex items-center justify-center text-white active:scale-95 transition-all"
>
{uploadingBanner ? <Loader2 className="w-4 h-4 animate-spin" /> : <ImagePlus className="w-4 h-4" />}
</button>
<input
type="file"
ref={bannerInputRef}
onChange={handleBannerUpload}
accept="image/*"
className="hidden"
/>
</div>
<div className="relative w-full h-32 rounded-2xl overflow-hidden bg-white/5 border border-white/5 group">
{shopBanner ? (
<img src={shopBanner} alt="Banner" className="w-full h-full object-cover" />
) : (
<div className="w-full h-full flex flex-col items-center justify-center gap-2 text-white/20">
<ImagePlus className="w-8 h-8" />
<span className="text-[8px] font-black uppercase tracking-widest">Aucune bannière</span>
</div>
)}
{shopBanner && (
<button
onClick={() => setShopBanner('')}
className="absolute top-2 right-2 p-1.5 bg-red-500 text-white rounded-lg shadow-lg opacity-0 group-hover:opacity-100 transition-opacity"
>
<Trash2 className="w-3 h-3" />
</button>
)}
</div>
</div>
<div className="space-y-4">
<div className="space-y-2">
<label className="text-[10px] font-black text-accent uppercase tracking-widest ml-2">Nom du Shop</label>
<input
type="text"
value={shopName}
onChange={(e) => setShopName(e.target.value)}
className="w-full bg-bg-dark/50 border border-white/5 rounded-2xl px-4 py-3 text-white text-sm focus:border-accent/50 outline-none transition-all"
/>
</div>
<div className="space-y-2">
<label className="text-[10px] font-black text-accent uppercase tracking-widest ml-2">Description</label>
<textarea
value={shopDescription}
onChange={(e) => setShopDescription(e.target.value)}
className="w-full bg-bg-dark/50 border border-white/5 rounded-2xl px-4 py-3 text-white text-sm focus:border-accent/50 outline-none transition-all min-h-[100px]"
/>
</div>
<div className="space-y-2">
<label className="text-[10px] font-black text-accent uppercase tracking-widest ml-2">Page d'informations (Client)</label>
<textarea
value={infoText}
onChange={(e) => setInfoText(e.target.value)}
placeholder="Expliquez ici comment utiliser l'application, vos règles, etc."
className="w-full bg-bg-dark/50 border border-white/5 rounded-2xl px-4 py-3 text-white text-sm focus:border-accent/50 outline-none transition-all min-h-[150px]"
/>
</div>
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<label className="text-[10px] font-black text-accent uppercase tracking-widest ml-2">Manager ID</label>
<input
type="text"
value={managerChatId}
onChange={(e) => setManagerChatId(e.target.value)}
placeholder="Ex: 123456789"
className="w-full bg-bg-dark/50 border border-white/5 rounded-2xl px-4 py-3 text-white text-sm focus:border-accent/50 outline-none transition-all"
/>
</div>
<div className="space-y-2">
<label className="text-[10px] font-black text-accent uppercase tracking-widest ml-2">Contact Manager (@)</label>
<input
type="text"
value={orderManager}
onChange={(e) => setOrderManager(e.target.value)}
placeholder="Ex: MonManager"
className="w-full bg-bg-dark/50 border border-white/5 rounded-2xl px-4 py-3 text-white text-sm focus:border-accent/50 outline-none transition-all"
/>
</div>
</div>
<div className="space-y-2">
<label className="text-[10px] font-black text-accent uppercase tracking-widest ml-2">Canal Telegram</label>
<input
type="text"
value={channelUrl}
onChange={(e) => setChannelUrl(e.target.value)}
className="w-full bg-bg-dark/50 border border-white/5 rounded-2xl px-4 py-3 text-white text-sm focus:border-accent/50 outline-none transition-all"
/>
</div>
<div className="space-y-3">
<label className="text-[10px] font-black text-accent uppercase tracking-widest ml-2">Couleur Dominante</label>
<div className="flex flex-wrap gap-3 p-4 bg-bg-dark/50 border border-white/5 rounded-2xl">
{['#10B981', '#3B82F6', '#8B5CF6', '#EC4899', '#F59E0B', '#EF4444', '#06B6D4', '#F97316'].map(color => (
<button
key={color}
onClick={() => setAccentColor(color)}
className={cn(
"w-8 h-8 rounded-lg border-2 transition-all active:scale-90",
accentColor === color ? "border-white scale-110 shadow-[0_0_15px_rgba(255,255,255,0.3)]" : "border-transparent opacity-50 hover:opacity-100"
)}
style={{ backgroundColor: color }}
/>
))}
<div className="relative w-8 h-8 rounded-lg overflow-hidden border-2 border-white/10 group">
<input
type="color"
value={accentColor}
onChange={(e) => setAccentColor(e.target.value)}
className="absolute inset-0 w-[200%] h-[200%] -translate-x-1/4 -translate-y-1/4 cursor-pointer"
/>
<div className="absolute inset-0 flex items-center justify-center pointer-events-none opacity-0 group-hover:opacity-100 bg-black/20 transition-opacity">
<Plus className="w-4 h-4 text-white" />
</div>
</div>
</div>
</div>
</div>
</div>
<div className="glass rounded-[2rem] p-6 space-y-6">
<div className="flex items-center justify-between">
<div>
<p className="text-sm font-bold text-white uppercase tracking-tight">Vérification Client</p>
<p className="text-[10px] text-text-muted uppercase font-bold tracking-wider">{isVerificationEnabled ? 'Obligatoire' : 'Désactivée'}</p>
</div>
<button
onClick={() => setIsVerificationEnabled(!isVerificationEnabled)}
className={cn(
"w-14 h-7 rounded-full relative transition-all duration-300",
isVerificationEnabled ? "bg-accent" : "bg-white/10"
)}
>
<div className={cn(
"absolute top-1 w-5 h-5 rounded-full bg-white transition-all duration-300 shadow-lg",
isVerificationEnabled ? "left-8" : "left-1"
)} />
</button>
</div>
</div>
<button
onClick={() => handleSaveShopSettings()}
disabled={saving}
className="w-full bg-accent text-white font-black py-4 rounded-2xl shadow-[0_10px_30px_rgba(16,185,129,0.3)] flex items-center justify-center gap-3 disabled:opacity-50"
>
{saving ? <Loader2 className="w-5 h-5 animate-spin" /> : <Save className="w-5 h-5" />}
<span className="text-sm uppercase tracking-[0.2em]">Enregistrer les modifications</span>
</button>
</motion.div>
)}
{activeTab === 'meetup' && (
<motion.div
key="meetup-settings"
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: -20 }}
className="space-y-6"
>
{editingProduct ? (
<div className="glass rounded-[2rem] p-6 space-y-6">
<div className="flex items-center justify-between">
<h2 className="text-lg font-black text-white uppercase italic tracking-tight">Modifier Produit Meet-up</h2>
<button onClick={() => setEditingProduct(null)} className="p-2 text-white/40"><CloseIcon className="w-5 h-5" /></button>
</div>
<div className="space-y-4">
<div className="flex items-center justify-between">
<label className="text-[10px] font-black text-accent uppercase tracking-widest ml-2">Médias (Photos/Vidéos)</label>
<button
onClick={() => productPhotoInputRef.current?.click()}
disabled={uploadingProductMedia}
className="p-2 bg-accent/20 text-accent rounded-xl flex items-center gap-2 disabled:opacity-50"
>
{uploadingProductMedia ? <Loader2 className="w-4 h-4 animate-spin" /> : <Plus className="w-4 h-4" />}
<span className="text-[10px] font-black uppercase tracking-widest">
{uploadingProductMedia ? 'Envoi...' : 'Ajouter'}
</span>
</button>
<input type="file" ref={productPhotoInputRef} onChange={handleProductPhotoUpload} className="hidden" accept="image/*,video/*" multiple />
</div>
<div className="grid grid-cols-2 gap-3">
{(() => {
const getMedia = (url: string | null | undefined): { url: string, type: 'image' | 'video' }[] => {
if (!url) return [];
try {
const parsed = JSON.parse(url);
if (Array.isArray(parsed)) {
return parsed.map(item => typeof item === 'string' ? { url: item, type: item.match(/\.(mp4|webm|ogg|mov)$/i) ? 'video' : 'image' } : item);
}
} catch (e) {}
return url ? [{ url, type: url.match(/\.(mp4|webm|ogg|mov)$/i) ? 'video' : 'image' }] : [];
};
const media = getMedia(editingProduct.image_url);
return media.map((item, idx) => (
<div key={idx} className="relative aspect-square rounded-2xl overflow-hidden border border-white/10 group">
<ImageWithFallback src={JSON.stringify([item])} alt="" className="w-full h-full object-cover" />
<div className="absolute inset-0 bg-black/60 opacity-0 group-hover:opacity-100 transition-opacity flex flex-col items-center justify-center gap-2">
<div className="flex gap-2">
<button
onClick={() => handleReorderMedia(idx, 'up')}
disabled={idx === 0}
className="p-1.5 bg-white/10 rounded-lg text-white disabled:opacity-20"
>
<ChevronLeft className="w-4 h-4 rotate-90" />
</button>
<button
onClick={() => handleReorderMedia(idx, 'down')}
disabled={idx === media.length - 1}
className="p-1.5 bg-white/10 rounded-lg text-white disabled:opacity-20"
>
<ChevronLeft className="w-4 h-4 -rotate-90" />
</button>
</div>
<button
onClick={() => handleDeleteMedia(idx)}
className="p-1.5 bg-red-500/20 rounded-lg text-red-500"
>
<Trash2 className="w-4 h-4" />
</button>
</div>
<div className="absolute top-2 left-2 bg-black/50 backdrop-blur-md px-2 py-0.5 rounded-md border border-white/10">
<span className="text-[8px] font-black text-white">{idx + 1}</span>
</div>
{item.type === 'video' && (
<div className="absolute top-2 right-2 bg-accent/80 backdrop-blur-md p-1 rounded-md">
<Eye className="w-3 h-3 text-white" />
</div>
)}
</div>
));
})()}
</div>
</div>
<div className="space-y-4">
<div className="space-y-2">
<label className="text-[10px] font-black text-accent uppercase tracking-widest ml-2">Nom</label>
<input
type="text"
value={editingProduct.name}
onChange={async (e) => {
const newName = e.target.value;
setEditingProduct({ ...editingProduct, name: newName });
try {
const tgUser = (window as any).Telegram?.WebApp?.initDataUnsafe?.user;
await fetch('/api/admin/products', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
userId: tgUser?.id?.toString(),
username: tgUser?.username,
action: 'update',
productId: editingProduct.id,
updates: { name: newName }
})
});
setProducts(prev => prev.map(p => p.id === editingProduct.id ? { ...p, name: newName } : p));
} catch (error) {
console.error('Update Product Name Error:', error);
}
}}
className="w-full bg-bg-dark/50 border border-white/5 rounded-2xl px-4 py-3 text-white text-sm"
/>
</div>
<div className="space-y-2">
<label className="text-[10px] font-black text-accent uppercase tracking-widest ml-2">Description</label>
<textarea
value={editingProduct.description || ''}
onChange={async (e) => {
const newDesc = e.target.value;
setEditingProduct({ ...editingProduct, description: newDesc });
try {
const tgUser = (window as any).Telegram?.WebApp?.initDataUnsafe?.user;
await fetch('/api/admin/products', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
userId: tgUser?.id?.toString(),
username: tgUser?.username,
action: 'update',
productId: editingProduct.id,
updates: { description: newDesc }
})
});
setProducts(prev => prev.map(p => p.id === editingProduct.id ? { ...p, description: newDesc } : p));
} catch (error) {
console.error('Update Product Description Error:', error);
}
}}
className="w-full bg-bg-dark/50 border border-white/5 rounded-2xl px-4 py-3 text-white text-sm min-h-[100px]"
/>
</div>
<div className="space-y-2">
<label className="text-[10px] font-black text-accent uppercase tracking-widest ml-2">J'aime Fictifs</label>
<input
type="number"
value={editingProduct.fictitious_likes || 0}
onChange={async (e) => {
const newLikes = parseInt(e.target.value) || 0;
setEditingProduct({ ...editingProduct, fictitious_likes: newLikes });
try {
const tgUser = (window as any).Telegram?.WebApp?.initDataUnsafe?.user;
await fetch('/api/admin/products', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
userId: tgUser?.id?.toString(),
username: tgUser?.username,
action: 'update',
productId: editingProduct.id,
updates: { fictitious_likes: newLikes }
})
});
setProducts(prev => prev.map(p => p.id === editingProduct.id ? { ...p, fictitious_likes: newLikes } : p));
} catch (error) {
console.error('Update Product Likes Error:', error);
}
}}
className="w-full bg-bg-dark/50 border border-white/5 rounded-2xl px-4 py-3 text-white text-sm"
/>
</div>
<div className="space-y-4">
<div className="flex justify-between items-center">
<label className="text-[10px] font-black text-accent uppercase tracking-widest ml-2">Prix & Quantités</label>
<button onClick={() => handleAddPrice(editingProduct.id)} className="p-1 bg-accent/20 text-accent rounded-lg"><Plus className="w-4 h-4" /></button>
</div>
<div className="grid gap-2">
{prices.filter(p => p.product_id === editingProduct.id).map(price => (
<div key={price.id} className="flex items-center justify-between bg-white/5 p-3 rounded-xl border border-white/5">
<span className="text-xs text-white font-bold">{price.quantity} - {price.price}€</span>
<button onClick={() => handleDeletePrice(price.id)} className="text-red-500/40 hover:text-red-500"><Trash2 className="w-4 h-4" /></button>
</div>
))}
</div>
</div>
</div>
</div>
) : (
<>
<div className="glass rounded-[2rem] p-6 space-y-6">
<div className="flex items-center justify-between">
<div>
<p className="text-sm font-bold text-white uppercase tracking-tight">Meet-up</p>
<p className="text-[10px] text-text-muted uppercase font-bold tracking-wider">{isMeetupEnabled ? 'Activé' : 'Désactivé'}</p>
</div>
<button
onClick={() => {
const newValue = !isMeetupEnabled;
setIsMeetupEnabled(newValue);
handleSaveShopSettings({ is_meetup_enabled: newValue });
}}
className={cn(
"w-14 h-7 rounded-full relative transition-all duration-300",
isMeetupEnabled ? "bg-accent" : "bg-white/10"
)}
>
<div className={cn(
"absolute top-1 w-5 h-5 rounded-full bg-white transition-all duration-300 shadow-lg",
isMeetupEnabled ? "left-8" : "left-1"
)} />
</button>
</div>
</div>
<div className="space-y-4">
<div className="flex justify-between items-center">
<h2 className="text-lg font-black text-white uppercase italic tracking-tight">Bosseurs Meet-up ({workers.length})</h2>
<button
onClick={() => addTeamMember('worker')}
className="p-2 bg-accent/20 text-accent rounded-xl"
>
<Plus className="w-5 h-5" />
</button>
</div>
<div className="grid gap-3">
{workers.map(worker => (
<div key={worker.id} className="glass rounded-2xl p-4 flex items-center justify-between">
<div className="flex items-center gap-4">
<div className="w-10 h-10 rounded-xl bg-blue-500/10 flex items-center justify-center">
<Users className="w-5 h-5 text-blue-500" />
</div>
<div>
<p className="text-sm font-bold text-white">{worker.first_name || worker.username || 'Sans nom'}</p>
<p className="text-[10px] text-text-muted font-bold tracking-widest">ID: {worker.telegram_id}</p>
</div>
</div>
<button
onClick={() => deleteTeamMember(worker.id, 'worker')}
className="p-2 text-white/20 hover:text-red-500 transition-colors"
>
<Trash2 className="w-4 h-4" />
</button>
</div>
))}
</div>
</div>
{/* Meetup Categories & Products */}
<div className="space-y-6 pt-6 border-t border-white/5">
<div className="flex justify-between items-center">
<h2 className="text-lg font-black text-white uppercase italic tracking-tight">Catégories Meet-up</h2>
<button
onClick={() => handleAddCategory('meetup')}
className="p-2 bg-accent/20 text-accent rounded-xl"
>
<Plus className="w-5 h-5" />
</button>
</div>
<Reorder.Group
axis="y"
values={categories.filter(c => c.type === 'meetup')}
onReorder={(newOrder) => handleReorderCategories(newOrder, 'meetup')}
className="grid gap-3"
>
{categories.filter(c => c.type === 'meetup').map(cat => (
<Reorder.Item
key={cat.id}
value={cat}
className="glass rounded-2xl p-4 flex items-center justify-between cursor-grab active:cursor-grabbing"
>
<div className="flex items-center gap-4">
<LayoutGrid className="w-5 h-5 text-accent" />
<p className="text-sm font-bold text-white">{cat.name}</p>
</div>
<button onClick={() => handleDeleteCategory(cat.id)} className="p-2 text-white/20"><Trash2 className="w-4 h-4" /></button>
</Reorder.Item>
))}
</Reorder.Group>
<div className="flex justify-between items-center">
<h2 className="text-lg font-black text-white uppercase italic tracking-tight">Produits Meet-up</h2>
<button
onClick={() => handleAddProduct('meetup')}
className="p-2 bg-accent/20 text-accent rounded-xl"
>
<Plus className="w-5 h-5" />
</button>
</div>
<Reorder.Group
axis="y"
values={products.filter(p => p.type === 'meetup')}
onReorder={(newOrder) => handleReorderProducts(newOrder, 'meetup')}
className="grid gap-3"
>
{products.filter(p => p.type === 'meetup').map(product => (
<Reorder.Item
key={product.id}
value={product}
className="glass rounded-2xl p-4 flex items-center justify-between cursor-grab active:cursor-grabbing"
>
<div className="flex items-center gap-4">
<Package className="w-5 h-5 text-accent" />
<p className="text-sm font-bold text-white">{product.name}</p>
</div>
<div className="flex items-center gap-2">
<button
onClick={() => toggleStock(product.id, product.is_in_stock)}
className={cn(
"p-2 rounded-xl transition-colors",
product.is_in_stock ? "text-accent bg-accent/10" : "text-red-500 bg-red-500/10"
)}
>
<Power className="w-4 h-4" />
</button>
<button onClick={() => setEditingProduct(product)} className="p-2 text-white/20"><Edit className="w-4 h-4" /></button>
<button onClick={() => handleDeleteProduct(product.id)} className="p-2 text-white/20"><Trash2 className="w-4 h-4" /></button>
</div>
</Reorder.Item>
))}
</Reorder.Group>
</div>
<button
onClick={() => handleSaveShopSettings()}
data-save-settings="true"
disabled={saving}
className="w-full bg-accent text-white font-black py-4 rounded-2xl shadow-[0_10px_30px_rgba(16,185,129,0.3)] flex items-center justify-center gap-3 disabled:opacity-50 mt-8"
>
{saving ? <Loader2 className="w-5 h-5 animate-spin" /> : <Save className="w-5 h-5" />}
<span className="text-sm uppercase tracking-[0.2em]">Enregistrer les modifications</span>
</button>
</>
)}
</motion.div>
)}
{activeTab === 'team' && (
<motion.div
key="team-settings"
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: -20 }}
className="space-y-8"
>
{/* Drivers */}
<div className="space-y-4">
<div className="flex justify-between items-center">
<h2 className="text-lg font-black text-white uppercase italic tracking-tight">Livreurs ({drivers.length})</h2>
<button
onClick={() => addTeamMember('driver')}
className="p-2 bg-accent/20 text-accent rounded-xl"
>
<Plus className="w-5 h-5" />
</button>
</div>
<div className="grid gap-3">
{drivers.map(driver => (
<div key={driver.id} className="glass rounded-2xl p-4 flex items-center justify-between">
<div className="flex items-center gap-4">
<div className="w-10 h-10 rounded-xl bg-accent/10 flex items-center justify-center">
<Truck className="w-5 h-5 text-accent" />
</div>
<div>
<p className="text-sm font-bold text-white">{driver.first_name || driver.username || 'Sans nom'}</p>
<p className="text-[10px] text-text-muted font-bold tracking-widest">ID: {driver.telegram_id}</p>
</div>
</div>
<button
onClick={() => deleteTeamMember(driver.id, 'driver')}
className="p-2 text-white/20 hover:text-red-500 transition-colors"
>
<Trash2 className="w-4 h-4" />
</button>
</div>
))}
</div>
</div>
</motion.div>
)}
{activeTab === 'clients' && (
<motion.div
key="clients-settings"
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: -20 }}
className="space-y-4"
>
<div className="flex justify-between items-center mb-4">
<h2 className="text-lg font-black text-white uppercase italic tracking-tight">Clients ({botUsers.length})</h2>
<button
onClick={downloadClientList}
className="p-2 bg-accent/20 text-accent rounded-xl flex items-center gap-2"
>
<Download className="w-4 h-4" />
<span className="text-[10px] font-black uppercase tracking-widest">Télécharger</span>
</button>
</div>
<div className="relative">
<Search className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-text-muted" />
<input
type="text"
placeholder="Rechercher un client..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="w-full bg-glass border border-white/5 rounded-2xl pl-12 pr-4 py-3 text-white text-sm outline-none focus:border-accent/50 transition-all"
/>
</div>
<div className="grid gap-3">
{botUsers
.filter(u => u.username?.toLowerCase().includes(searchQuery.toLowerCase()) || u.telegram_id?.includes(searchQuery))
.map(user => (
<div key={user.id} className="glass rounded-2xl p-4 flex items-center justify-between">
<div className="flex items-center gap-4">
<div className="w-10 h-10 rounded-xl bg-white/5 flex items-center justify-center overflow-hidden">
{user.photo_url ? (
<img src={user.photo_url} alt="" className="w-full h-full object-cover" />
) : (
<Users className="w-5 h-5 text-text-muted" />
)}
</div>
<div>
<p className="text-sm font-bold text-white">
{user.first_name ? `${user.first_name} ` : ''}
<span className="text-accent/60 font-medium">@{user.username || 'Anonyme'}</span>
</p>
<div className="flex items-center gap-2">
<p className="text-[10px] text-text-muted font-bold tracking-widest">{user.telegram_id}</p>
{user.phone && <span className="text-[10px] text-accent/40 font-bold">• {user.phone}</span>}
{user.is_verified && <ShieldCheck className="w-3 h-3 text-accent" />}
</div>
</div>
</div>
<button
onClick={() => toggleVerification(user.id, user.is_verified)}
className={cn(
"p-2 rounded-xl transition-all",
user.is_verified ? "bg-accent/10 text-accent" : "bg-white/5 text-text-muted"
)}
>
{user.is_verified ? <ShieldCheck className="w-5 h-5" /> : <ShieldAlert className="w-5 h-5" />}
</button>
</div>
))}
</div>
</motion.div>
)}
{activeTab === 'categories' && (
<motion.div
key="categories-settings"
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: -20 }}
className="space-y-4"
>
<div className="flex justify-between items-center mb-4">
<h2 className="text-lg font-black text-white uppercase italic tracking-tight">Catégories ({categories.length})</h2>
<button
onClick={() => handleAddCategory('delivery')}
className="p-2 bg-accent/20 text-accent rounded-xl"
>
<Plus className="w-5 h-5" />
</button>
</div>
<Reorder.Group
axis="y"
values={categories.filter(c => c.type === 'delivery')}
onReorder={(newOrder) => handleReorderCategories(newOrder, 'delivery')}
className="grid gap-3"
>
{categories.filter(c => c.type === 'delivery').map(cat => (
<Reorder.Item
key={cat.id}
value={cat}
className="glass rounded-2xl p-4 flex items-center justify-between group cursor-grab active:cursor-grabbing"
>
<div className="flex items-center gap-4">
<div className="w-10 h-10 rounded-xl bg-white/5 flex items-center justify-center">
<LayoutGrid className="w-5 h-5 text-accent" />
</div>
<div>
<p className="text-sm font-bold text-white">{cat.name}</p>
<p className="text-[10px] text-text-muted uppercase font-bold tracking-widest">{cat.type} | ID: {cat.id}</p>
</div>
</div>
<button
onClick={() => handleDeleteCategory(cat.id)}
className="p-2 text-white/20 hover:text-red-500 transition-colors"
>
<Trash2 className="w-4 h-4" />
</button>
</Reorder.Item>
))}
</Reorder.Group>
</motion.div>
)}
{activeTab === 'products' && (
<motion.div
key="products-settings"
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: -20 }}
className="space-y-4"
>
{editingProduct ? (
<div className="glass rounded-[2rem] p-6 space-y-6">
<div className="flex items-center justify-between">
<h2 className="text-lg font-black text-white uppercase italic tracking-tight">Modifier Produit</h2>
<button onClick={() => setEditingProduct(null)} className="p-2 text-white/40"><CloseIcon className="w-5 h-5" /></button>
</div>
<div className="space-y-4">
<div className="flex items-center justify-between">
<label className="text-[10px] font-black text-accent uppercase tracking-widest ml-2">Médias (Photos/Vidéos)</label>
<button
onClick={() => productPhotoInputRef.current?.click()}
disabled={uploadingProductMedia}
className="p-2 bg-accent/20 text-accent rounded-xl flex items-center gap-2 disabled:opacity-50"
>
{uploadingProductMedia ? <Loader2 className="w-4 h-4 animate-spin" /> : <Plus className="w-4 h-4" />}
<span className="text-[10px] font-black uppercase tracking-widest">
{uploadingProductMedia ? 'Envoi...' : 'Ajouter'}
</span>
</button>
<input type="file" ref={productPhotoInputRef} onChange={handleProductPhotoUpload} className="hidden" accept="image/*,video/*" multiple />
</div>
<div className="grid grid-cols-2 gap-3">
{(() => {
const getMedia = (url: string | null | undefined): { url: string, type: 'image' | 'video' }[] => {
if (!url) return [];
try {
const parsed = JSON.parse(url);
if (Array.isArray(parsed)) {
return parsed.map(item => typeof item === 'string' ? { url: item, type: item.match(/\.(mp4|webm|ogg|mov)$/i) ? 'video' : 'image' } : item);
}
} catch (e) {}
return url ? [{ url, type: url.match(/\.(mp4|webm|ogg|mov)$/i) ? 'video' : 'image' }] : [];
};
const media = getMedia(editingProduct.image_url);
return media.map((item, idx) => (
<div key={idx} className="relative aspect-square rounded-2xl overflow-hidden border border-white/10 group">
<ImageWithFallback src={JSON.stringify([item])} alt="" className="w-full h-full object-cover" />
<div className="absolute inset-0 bg-black/60 opacity-0 group-hover:opacity-100 transition-opacity flex flex-col items-center justify-center gap-2">
<div className="flex gap-2">
<button
onClick={() => handleReorderMedia(idx, 'up')}
disabled={idx === 0}
className="p-1.5 bg-white/10 rounded-lg text-white disabled:opacity-20"
>
<ChevronLeft className="w-4 h-4 rotate-90" />
</button>
<button
onClick={() => handleReorderMedia(idx, 'down')}
disabled={idx === media.length - 1}
className="p-1.5 bg-white/10 rounded-lg text-white disabled:opacity-20"
>
<ChevronLeft className="w-4 h-4 -rotate-90" />
</button>
</div>
<button
onClick={() => handleDeleteMedia(idx)}
className="p-1.5 bg-red-500/20 rounded-lg text-red-500"
>
<Trash2 className="w-4 h-4" />
</button>
</div>
<div className="absolute top-2 left-2 bg-black/50 backdrop-blur-md px-2 py-0.5 rounded-md border border-white/10">
<span className="text-[8px] font-black text-white">{idx + 1}</span>
</div>
{item.type === 'video' && (
<div className="absolute top-2 right-2 bg-accent/80 backdrop-blur-md p-1 rounded-md">
<Eye className="w-3 h-3 text-white" />
</div>
)}
</div>
));
})()}
</div>
</div>
<div className="space-y-4">
<div className="space-y-2">
<label className="text-[10px] font-black text-accent uppercase tracking-widest ml-2">Nom</label>
<input
type="text"
value={editingProduct.name}
onChange={async (e) => {
const newName = e.target.value;
setEditingProduct({ ...editingProduct, name: newName });
try {
const tgUser = (window as any).Telegram?.WebApp?.initDataUnsafe?.user;
await fetch('/api/admin/products', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
userId: tgUser?.id?.toString(),
username: tgUser?.username,
action: 'update',
productId: editingProduct.id,
updates: { name: newName }
})
});
setProducts(prev => prev.map(p => p.id === editingProduct.id ? { ...p, name: newName } : p));
} catch (error) {
console.error('Update Product Name Error:', error);
}
}}
className="w-full bg-bg-dark/50 border border-white/5 rounded-2xl px-4 py-3 text-white text-sm"
/>
</div>
<div className="space-y-2">
<label className="text-[10px] font-black text-accent uppercase tracking-widest ml-2">Description</label>
<textarea
value={editingProduct.description || ''}
onChange={async (e) => {
const newDesc = e.target.value;
setEditingProduct({ ...editingProduct, description: newDesc });
try {
const tgUser = (window as any).Telegram?.WebApp?.initDataUnsafe?.user;
await fetch('/api/admin/products', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
userId: tgUser?.id?.toString(),
username: tgUser?.username,
action: 'update',
productId: editingProduct.id,
updates: { description: newDesc }
})
});
setProducts(prev => prev.map(p => p.id === editingProduct.id ? { ...p, description: newDesc } : p));
} catch (error) {
console.error('Update Product Description Error:', error);
}
}}
className="w-full bg-bg-dark/50 border border-white/5 rounded-2xl px-4 py-3 text-white text-sm min-h-[100px]"
/>
</div>
<div className="space-y-2">
<label className="text-[10px] font-black text-accent uppercase tracking-widest ml-2">J'aime Fictifs</label>
<input
type="number"
value={editingProduct.fictitious_likes || 0}
onChange={async (e) => {
const newLikes = parseInt(e.target.value) || 0;
setEditingProduct({ ...editingProduct, fictitious_likes: newLikes });
try {
const tgUser = (window as any).Telegram?.WebApp?.initDataUnsafe?.user;
await fetch('/api/admin/products', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
userId: tgUser?.id?.toString(),
username: tgUser?.username,
action: 'update',
productId: editingProduct.id,
updates: { fictitious_likes: newLikes }
})
});
setProducts(prev => prev.map(p => p.id === editingProduct.id ? { ...p, fictitious_likes: newLikes } : p));
} catch (error) {
console.error('Update Product Likes Error:', error);
}
}}
className="w-full bg-bg-dark/50 border border-white/5 rounded-2xl px-4 py-3 text-white text-sm"
/>
</div>
<div className="space-y-4">
<div className="flex justify-between items-center">
<label className="text-[10px] font-black text-accent uppercase tracking-widest ml-2">Prix & Quantités</label>
<button onClick={() => handleAddPrice(editingProduct.id)} className="p-1 bg-accent/20 text-accent rounded-lg"><Plus className="w-4 h-4" /></button>
</div>
<div className="grid gap-2">
{prices.filter(p => p.product_id === editingProduct.id).map(price => (
<div key={price.id} className="flex items-center justify-between bg-white/5 p-3 rounded-xl border border-white/5">
<span className="text-xs text-white font-bold">{price.quantity} - {price.price}€</span>
<button onClick={() => handleDeletePrice(price.id)} className="text-red-500/40 hover:text-red-500"><Trash2 className="w-4 h-4" /></button>
</div>
))}
</div>
</div>
</div>
</div>
) : (
<>
<div className="flex justify-between items-center mb-4">
<h2 className="text-lg font-black text-white uppercase italic tracking-tight">Produits ({products.length})</h2>
<button
onClick={() => handleAddProduct('delivery')}
className="p-2 bg-accent/20 text-accent rounded-xl"
>
<Plus className="w-5 h-5" />
</button>
</div>
<Reorder.Group
axis="y"
values={products.filter(p => p.type === 'delivery')}
onReorder={(newOrder) => handleReorderProducts(newOrder, 'delivery')}
className="grid gap-3"
>
{products.filter(p => p.type === 'delivery').map(prod => (
<Reorder.Item
key={prod.id}
value={prod}
className="glass rounded-2xl p-4 flex items-center justify-between cursor-grab active:cursor-grabbing"
>
<div className="flex items-center gap-4">
<div className="w-12 h-12 rounded-xl overflow-hidden bg-white/5">
<ImageWithFallback src={prod.image_url || ''} alt={prod.name} className="w-full h-full" />
</div>
<div>
<p className="text-sm font-bold text-white">{prod.name}</p>
<p className="text-[10px] text-text-muted uppercase font-bold tracking-widest">
{categories.find(c => c.id === prod.category_id)?.name || 'Sans catégorie'}
</p>
</div>
</div>
<div className="flex items-center gap-2">
<button
onClick={() => toggleStock(prod.id, prod.is_in_stock)}
className={cn(
"p-2 rounded-xl transition-colors",
prod.is_in_stock ? "text-accent bg-accent/10" : "text-red-500 bg-red-500/10"
)}
>
<Power className="w-4 h-4" />
</button>
<button
onClick={() => setEditingProduct(prod)}
className="p-2 text-white/40 hover:text-white"
>
<ChevronRight className="w-4 h-4" />
</button>
<button
onClick={() => handleDeleteProduct(prod.id)}
className="p-2 text-white/20 hover:text-red-500"
>
<Trash2 className="w-4 h-4" />
</button>
</div>
</Reorder.Item>
))}
</Reorder.Group>
</>
)}
</motion.div>
)}
{activeTab === 'reports' && (
<motion.div
key="reports-settings"
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: -20 }}
className="space-y-8"
>
{/* Session Report */}
<div className="glass rounded-[2rem] p-6 space-y-6">
<div className="flex items-center gap-4">
<div className="w-12 h-12 rounded-2xl bg-accent/10 flex items-center justify-center">
<FileText className="w-6 h-6 text-accent" />
</div>
<div>
<h2 className="text-lg font-black text-white uppercase italic tracking-tight">Rapports de session</h2>
<p className="text-[10px] text-text-muted font-bold tracking-widest uppercase">Statistiques des dernières 24h</p>
</div>
</div>
<button
onClick={generateSessionReport}
className="w-full bg-accent/10 text-accent font-black py-4 rounded-2xl border border-accent/20 flex items-center justify-center gap-3 active:scale-95 transition-all"
>
<BarChart3 className="w-5 h-5" />
<span className="text-sm uppercase tracking-widest">Générer le rapport 24h</span>
</button>
</div>
{/* Broadcast Section (Moved to Status Tab) */}
{/* Maintenance */}
<div className="glass rounded-[2rem] p-6 space-y-6">
<div className="flex items-center gap-4">
<div className="w-12 h-12 rounded-2xl bg-red-500/10 flex items-center justify-center">
<ShieldAlert className="w-6 h-6 text-red-500" />
</div>
<div>
<h2 className="text-lg font-black text-white uppercase italic tracking-tight">Maintenance</h2>
<p className="text-[10px] text-text-muted font-bold tracking-widest uppercase">Outils système</p>
</div>
</div>
<button
onClick={() => (window as any).Telegram?.WebApp?.showAlert?.("Vérification de l'intégrité de la base de données en cours... ✅")}
className="w-full bg-white/5 text-white/60 font-black py-4 rounded-2xl border border-white/5 flex items-center justify-center gap-3 active:scale-95 transition-all"
>
<ShieldCheck className="w-5 h-5" />
<span className="text-sm uppercase tracking-widest">Vérifier l'intégrité</span>
</button>
</div>
</motion.div>
)}
</AnimatePresence>
</div>
);
};
const MainAppContent = ({
config,
setConfig,
cart,
updateQuantity,
removeFromCart,
fulfillmentType,
setFulfillmentType,
addToCart,
setCart,
clearCart,
modifyingOrderId,
setModifyingOrderId,
modifyingOrderAddress,
setModifyingOrderAddress,
showSplash,
favorites,
toggleFavorite,
isAdmin,
isManager
}: {
config: ShopConfig | null,
setConfig: (c: ShopConfig) => void,
cart: CartItem[],
updateQuantity: (priceId: string, delta: number) => void,
removeFromCart: (priceId: string) => void,
fulfillmentType: 'delivery' | 'meetup' | null,
setFulfillmentType: (type: 'delivery' | 'meetup' | null) => void,
addToCart: (item: CartItem) => void,
setCart: React.Dispatch<React.SetStateAction<CartItem[]>>,
clearCart: () => void,
modifyingOrderId: string | null,
setModifyingOrderId: (id: string | null) => void,
modifyingOrderAddress: any | null,
setModifyingOrderAddress: (address: any | null) => void,
showSplash: boolean,
favorites: string[],
toggleFavorite: (productId: string) => void,
isAdmin: boolean,
isManager: boolean
}) => {
const location = useLocation();
const navigate = useNavigate();
return (
<>
<AnimatePresence>
{showSplash && <SplashScreen config={config} />}
</AnimatePresence>
{!showSplash && (
<>
{(isAdmin || isManager) && location.pathname !== '/settings' && (
<div className="fixed top-6 right-6 z-[70]">
<motion.button
whileHover={{ scale: 1.05 }}
whileTap={{ scale: 0.95 }}
onClick={() => navigate('/settings')}
className="glass p-3 rounded-2xl border-accent/30 text-accent premium-shadow flex items-center gap-2"
>
<Settings className="w-5 h-5" />
<span className="text-[10px] font-black uppercase tracking-widest hidden sm:block">Admin</span>
</motion.button>
</div>
)}
{modifyingOrderId && location.pathname !== '/cart' && (
<div className="fixed top-6 left-1/2 -translate-x-1/2 z-[70] w-[90%] max-w-md">
<motion.div
initial={{ y: -100, opacity: 0 }}
animate={{ y: 0, opacity: 1 }}
className="glass p-4 rounded-3xl border-accent/30 text-accent premium-shadow flex items-center justify-between gap-4"
>
<div className="flex items-center gap-3">
<div className="w-10 h-10 rounded-2xl bg-accent/10 flex items-center justify-center">
<Edit className="w-5 h-5 text-accent" />
</div>
<div>
<p className="text-[8px] font-black uppercase tracking-[0.3em] opacity-60">Modification en cours</p>
<p className="text-[10px] font-black text-white uppercase tracking-tight">Commande #{modifyingOrderId.slice(-6)}</p>
</div>
</div>
<div className="flex items-center gap-2">
<button
onClick={() => navigate('/cart')}
className="px-4 py-2 bg-accent text-white rounded-xl text-[9px] font-black uppercase tracking-widest active:scale-95 transition-all"
>
Voir Panier
</button>
<button
onClick={() => {
setModifyingOrderId(null);
clearCart();
}}
className="p-2 text-red-500/40 hover:text-red-500 transition-colors"
>
<XCircle className="w-5 h-5" />
</button>
</div>
</motion.div>
</div>
)}
{config && !config.isOpen && location.pathname !== '/settings' && !isAdmin && !isManager ? (
<ShopClosed config={config} />
) : (
<>
<Routes>
<Route path="/" element={<Home config={config} fulfillmentType={fulfillmentType} setFulfillmentType={setFulfillmentType} favorites={favorites} toggleFavorite={toggleFavorite} />} />
<Route path="/product/:productId" element={!fulfillmentType && config?.isMeetupEnabled ? <Navigate to="/" /> : <ProductDetail config={config} addToCart={addToCart} favorites={favorites} toggleFavorite={toggleFavorite} />} />
<Route path="/infos" element={<Infos config={config} />} />
<Route path="/orders" element={<MyOrders config={config} addToCart={addToCart} clearCart={clearCart} setCart={setCart} setModifyingOrderId={setModifyingOrderId} setModifyingOrderAddress={setModifyingOrderAddress} setFulfillmentType={setFulfillmentType} />} />
<Route path="/cart" element={!fulfillmentType && config?.isMeetupEnabled ? <Navigate to="/" /> : <Cart config={config} cart={cart} updateQuantity={updateQuantity} removeFromCart={removeFromCart} fulfillmentType={fulfillmentType} modifyingOrderId={modifyingOrderId} modifyingOrderAddress={modifyingOrderAddress} clearCart={clearCart} />} />
<Route path="/settings" element={<AdminSettings config={config} setConfig={setConfig} isAdmin={isAdmin} isManager={isManager} />} />
</Routes>
</>
)}
{(config?.isOpen || isAdmin || isManager) && <BottomNav cartCount={cart.reduce((acc, i) => acc + i.count, 0)} config={config} />}
</>
)}
</>
);
};
const RestrictedAccess = () => {
const [logs, setLogs] = useState<string[]>([]);
const systemData = useMemo(() => {
const data = [
`[SYSTEM] INITIALIZING FORENSIC PROTOCOL...`,
`[AUTH] UNAUTHORIZED ACCESS DETECTED`,
`[CLIENT] USER_AGENT: ${navigator.userAgent}`,
`[CLIENT] PLATFORM: ${navigator.platform}`,
`[CLIENT] LANGUAGE: ${navigator.language}`,
`[CLIENT] SCREEN: ${window.screen.width}x${window.screen.height} (${window.devicePixelRatio}x)`,
`[CLIENT] CORES: ${navigator.hardwareConcurrency || 'N/A'}`,
`[CLIENT] MEMORY: ${((navigator as any).deviceMemory || 'N/A')} GB`,
`[CLIENT] COOKIES_ENABLED: ${navigator.cookieEnabled}`,
`[CLIENT] DO_NOT_TRACK: ${navigator.doNotTrack}`,
`[NETWORK] PROTOCOL: ${window.location.protocol}`,
`[NETWORK] HOST: ${window.location.host}`,
`[NETWORK] CONNECTION: ${(navigator as any).connection?.effectiveType || 'N/A'}`,
`[SECURITY] ENVIRONMENT_CHECK: FAILED (OUTSIDE_TELEGRAM)`,
`[SECURITY] DATA_COLLECTION: INITIATED BY ADMINISTRATOR`,
`[SECURITY] TRACE_ID: ${Math.random().toString(36).substring(2, 15).toUpperCase()}`,
`[SECURITY] TIMESTAMP: ${new Date().toISOString()}`,
];
return data;
}, []);
useEffect(() => {
let i = 0;
const interval = setInterval(() => {
if (i < systemData.length) {
setLogs(prev => [...prev, systemData[i]]);
i++;
} else {
clearInterval(interval);
}
}, 150);
return () => clearInterval(interval);
}, [systemData]);
return (
<div className="min-h-screen bg-black text-white font-mono flex flex-col items-center justify-center p-4 md:p-8">
<div className="max-w-2xl w-full border border-white/20 bg-black/50 backdrop-blur-xl p-8 rounded-lg space-y-8 shadow-[0_0_50px_rgba(255,255,255,0.05)]">
<div className="flex flex-col items-center space-y-6">
<div className="p-4 border-2 border-white rounded-full">
<ShieldAlert className="w-12 h-12 text-white" />
</div>
<div className="space-y-2 text-center">
<h1 className="text-2xl md:text-3xl font-black tracking-[0.4em] uppercase text-white">
Accès Restreint
</h1>
<div className="h-[1px] w-24 bg-white/20 mx-auto" />
</div>
<p className="text-[10px] md:text-xs text-white/60 uppercase tracking-[0.2em] leading-relaxed max-w-md text-center">
Cette application est strictement réservée à l'environnement Telegram.
Toutes les données de connexion ont été transmises à l'administrateur.
</p>
</div>
<div className="bg-white/5 border border-white/10 rounded-md p-4 h-64 overflow-hidden relative group">
<div className="absolute top-2 right-4 flex gap-1.5">
<div className="w-2 h-2 rounded-full bg-white/20" />
<div className="w-2 h-2 rounded-full bg-white/20" />
<div className="w-2 h-2 rounded-full bg-white/20" />
</div>
<div className="text-[9px] md:text-[10px] space-y-1 overflow-y-auto h-full scrollbar-hide text-left">
{logs.map((log, idx) => (
<div key={idx} className="flex gap-3">
<span className="text-white/20 shrink-0">[{idx.toString().padStart(2, '0')}]</span>
<span className={cn(
"break-all",
log.includes('[SECURITY]') ? "text-white font-bold" : "text-white/60"
)}>{log}</span>
</div>
))}
<motion.div
animate={{ opacity: [0, 1, 0] }}
transition={{ duration: 0.8, repeat: Infinity }}
className="w-2 h-4 bg-white inline-block ml-1"
/>
</div>
</div>
<div className="pt-4 flex flex-col items-center gap-4">
<div className="flex items-center gap-2 text-[8px] text-white/30 uppercase tracking-[0.3em]">
<Lock className="w-3 h-3" />
Encrypted Connection
</div>
</div>
</div>
</div>
);
};
export default function App() {
const [config, setConfig] = useState<ShopConfig | null>(null);
const [showSplash, setShowSplash] = useState(true);
const [cart, setCart] = useState<CartItem[]>([]);
const [modifyingOrderId, setModifyingOrderId] = useState<string | null>(null);
const [modifyingOrderAddress, setModifyingOrderAddress] = useState<any | null>(null);
const [fulfillmentType, setFulfillmentType] = useState<'delivery' | 'meetup' | null>(null);
const [isTelegram, setIsTelegram] = useState(true);
useEffect(() => {
// Verify if app is running inside Telegram
const tg = (window as any).Telegram?.WebApp;
if (!tg || !tg.initData) {
setIsTelegram(false);
}
}, []);
useEffect(() => {
if (config) {
if (!config.isMeetupEnabled) {
if (fulfillmentType !== null) {
setFulfillmentType(null);
}
}
}
}, [config, fulfillmentType]);
const [favorites, setFavorites] = useState<string[]>([]);
const [isAdmin, setIsAdmin] = useState(false);
const [isManager, setIsManager] = useState(false);
useEffect(() => {
if (config) {
const tgUser = (window as any).Telegram?.WebApp?.initDataUnsafe?.user;
const userId = tgUser?.id?.toString() || '';
const username = tgUser?.username || '';
// Check both ID and username for admin/manager status
const formatId = (id: string | number | undefined) => {
if (!id) return '';
const s = id.toString().trim();
return s.startsWith('@') ? s.substring(1) : s;
};
const cleanUserId = userId.trim();
const cleanUsername = username.trim().startsWith('@') ? username.trim().substring(1) : username.trim();
const adminIdStr = formatId(config.adminId);
const managerIdStr = formatId(config.managerChatId);
const isAdminUser = (cleanUserId && cleanUserId === adminIdStr) || (cleanUsername && cleanUsername === adminIdStr);
const isManagerUser = (cleanUserId && cleanUserId === managerIdStr) || (cleanUsername && cleanUsername === managerIdStr);
setIsAdmin(isAdminUser);
setIsManager(isManagerUser);
}
}, [config]);
useEffect(() => {
// Fetch user's likes from DB
const fetchUserLikes = async () => {
const tgUser = (window as any).Telegram?.WebApp?.initDataUnsafe?.user;
if (tgUser?.id) {
const { data: userLikes } = await supabase
.from('product_likes')
.select('product_id')
.eq('user_telegram_id', tgUser.id.toString());
if (userLikes) {
const likedIds = userLikes.map(l => l.product_id);
setFavorites(likedIds);
}
}
};
fetchUserLikes();
}, []);
const toggleFavorite = async (productId: string, onUpdate?: (isLiked: boolean) => void) => {
const tgUser = (window as any).Telegram?.WebApp?.initDataUnsafe?.user;
const isLiked = favorites.includes(productId);
const newFavs = isLiked
? favorites.filter(id => id !== productId)
: [...favorites, productId];
setFavorites(newFavs);
if (tgUser?.id) {
try {
await fetch('/api/likes', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
productId,
userId: tgUser.id,
action: isLiked ? 'remove' : 'add'
})
});
onUpdate?.(!isLiked);
} catch (error) {
console.error('Toggle Favorite Error:', error);
// Rollback state on error
setFavorites(favorites);
}
}
};
useEffect(() => {
if (window.Telegram?.WebApp) {
window.Telegram.WebApp.ready();
window.Telegram.WebApp.expand();
// Set header color to match the app
(window.Telegram.WebApp as any).setHeaderColor?.('#121212');
}
const loadConfig = async () => {
const data = await getAppConfig();
setConfig(data);
setTimeout(() => setShowSplash(false), 3000);
};
loadConfig();
// Real-time subscription to shop_settings to update config
const configSubscription = supabase
.channel('shop-settings-client')
.on('postgres_changes', { event: 'UPDATE', table: 'shop_settings', schema: 'public', filter: 'id=eq.1' }, async () => {
const data = await getAppConfig();
setConfig(data);
})
.subscribe();
return () => {
configSubscription.unsubscribe();
};
}, []);
useEffect(() => {
if (config?.accentColor) {
document.documentElement.style.setProperty('--accent-color', config.accentColor);
const hoverColor = darkenColor(config.accentColor, 10);
document.documentElement.style.setProperty('--accent-hover-color', hoverColor);
}
}, [config]);
const clearCart = () => {
setCart([]);
setModifyingOrderId(null);
setModifyingOrderAddress(null);
};
const addToCart = (item: CartItem) => {
setCart(prev => {
const existing = prev.find(i => i.priceId === item.priceId);
if (existing) {
return prev.map(i => i.priceId === item.priceId ? { ...i, count: i.count + 1 } : i);
}
return [...prev, item];
});
};
const removeFromCart = (priceId: string) => {
setCart(prev => prev.filter(i => i.priceId !== priceId));
};
const updateQuantity = (priceId: string, delta: number) => {
setCart(prev => prev.map(i => {
if (i.priceId === priceId) {
const newCount = Math.max(1, i.count + delta);
return { ...i, count: newCount };
}
return i;
}));
};
if (!isTelegram) {
return <RestrictedAccess />;
}
return (
<Router>
<div className="max-w-md mx-auto min-h-screen bg-[#0B101B] font-sans selection:bg-blue-500 selection:text-white relative">
<BackgroundParticles />
<MainAppContent
config={config}
setConfig={setConfig}
cart={cart}
updateQuantity={updateQuantity}
removeFromCart={removeFromCart}
fulfillmentType={fulfillmentType}
setFulfillmentType={setFulfillmentType}
addToCart={addToCart}
setCart={setCart}
clearCart={clearCart}
modifyingOrderId={modifyingOrderId}
setModifyingOrderId={setModifyingOrderId}
modifyingOrderAddress={modifyingOrderAddress}
setModifyingOrderAddress={setModifyingOrderAddress}
showSplash={showSplash}
favorites={favorites}
toggleFavorite={toggleFavorite}
isAdmin={isAdmin}
isManager={isManager}
/>
</div>
</Router>
);
}
import React, { useEffect, useState, useMemo, useRef } from 'react';
import { BrowserRouter as Router, Routes, Route, useNavigate, useParams, Link, useLocation, Navigate } from 'react-router-dom';
import { supabase, getAppConfig } from './lib/supabase';
import { Category, Product, ProductPrice, ShopConfig, CartItem } from './types';
import {
ShoppingCart,
ArrowLeft,
Package,
Info,
ChevronDown,
LayoutGrid,
MessageSquare,
ExternalLink,
Leaf,
Plus,
Minus,
Trash2,
MapPin,
Check,
Send,
Search,
Loader2,
Heart,
ShieldCheck,
ChevronRight,
Settings,
Save,
X as CloseIcon,
Eye,
EyeOff,
Power,
Bell,
Users,
FileText,
Layout,
RefreshCw,
Truck,
UserCheck,
ImagePlus,
ShieldAlert,
Skull,
Terminal,
AlertTriangle,
CheckCircle2,
XCircle,
BarChart3,
Download,
Edit,
ChevronLeft,
Clock,
Globe,
Cpu,
Activity,
Shield,
Lock,
ClipboardList,
User,
Calendar,
History,
Navigation
} from 'lucide-react';
import { motion, AnimatePresence, useScroll, useTransform, Reorder } from 'motion/react';
import { clsx, type ClassValue } from 'clsx';
import { twMerge } from 'tailwind-merge';
const cn = (...inputs: ClassValue[]) => {
return twMerge(clsx(inputs));
};
const darkenColor = (hex: string, percent: number) => {
const num = parseInt(hex.replace('#', ''), 16);
const amt = Math.round(2.55 * percent);
const R = (num >> 16) - amt;
const G = (num >> 8 & 0x00FF) - amt;
const B = (num & 0x0000FF) - amt;
return '#' + (0x1000000 + (R < 255 ? R < 0 ? 0 : R : 255) * 0x10000 + (G < 255 ? G < 0 ? 0 : G : 255) * 0x100 + (B < 255 ? B < 0 ? 0 : B : 255)).toString(16).slice(1);
};
// --- Components ---
const BackgroundParticles = () => {
return (
<div className="fixed inset-0 pointer-events-none overflow-hidden z-0">
{/* Nebula Glows */}
<motion.div
animate={{
scale: [1, 1.2, 1],
opacity: [0.1, 0.2, 0.1],
x: [-20, 20, -20],
y: [-20, 20, -20],
}}
transition={{ duration: 15, repeat: Infinity, ease: "easeInOut" }}
className="absolute top-[-10%] left-[-10%] w-[60%] h-[60%] bg-accent/10 rounded-full blur-[120px]"
/>
<motion.div
animate={{
scale: [1.2, 1, 1.2],
opacity: [0.05, 0.15, 0.05],
x: [20, -20, 20],
y: [20, -20, 20],