import React, { useState, useEffect, useRef } from 'react'; export default function MaterielCard({ materiel, onEdit, onDelete }) { const [index, setIndex] = useState(0); const imgContainerRef = useRef(null); const imgRef = useRef(null); const imgs = React.useMemo(() => { if (!materiel) return []; if (Array.isArray(materiel.images) && materiel.images.length > 0) return materiel.images; if (Array.isArray(materiel.image_url) && materiel.image_url.length > 0) return materiel.image_url; if (typeof materiel.image_url === 'string' && materiel.image_url) return [materiel.image_url]; return []; }, [materiel]); const [offsetX, setOffsetX] = useState(0); const [maxOffset, setMaxOffset] = useState(0); const recomputeSizes = () => { const c = imgContainerRef.current; const i = imgRef.current; const cw = c ? c.clientWidth : 0; const iw = (i && i.naturalWidth && i.naturalHeight && c) ? Math.round(i.naturalWidth * (c.clientHeight / i.naturalHeight)) : (i ? i.clientWidth : 0); const computedMaxOffset = Math.min(0, Math.floor(cw - iw)); setMaxOffset(computedMaxOffset); setOffsetX(prev => Math.max(computedMaxOffset, Math.min(0, prev))); }; useEffect(() => { recomputeSizes(); const onResize = () => recomputeSizes(); window.addEventListener('resize', onResize); return () => window.removeEventListener('resize', onResize); }, [index, imgs.length]); const next = (e) => { e && e.stopPropagation(); if (!imgs || imgs.length === 0) return; if (imgs.length > 1) { setIndex((i) => (i + 1) % imgs.length); } else { const c = imgContainerRef.current; if (!c) return; const step = Math.max(80, Math.floor(c.clientWidth / 2)); setOffsetX(prev => Math.max(maxOffset, prev - step)); } }; const prev = (e) => { e && e.stopPropagation(); if (!imgs || imgs.length === 0) return; if (imgs.length > 1) { setIndex((i) => (i - 1 + imgs.length) % imgs.length); } else { const c = imgContainerRef.current; if (!c) return; const step = Math.max(80, Math.floor(c.clientWidth / 2)); setOffsetX(prev => Math.min(0, prev + step)); } }; const current = imgs && imgs.length > 0 ? imgs[index] : null; return (