(function(wp) {
    const { registerBlockType } = wp.blocks;
    const { useBlockProps } = wp.blockEditor;
    const { useEffect, useState, useRef, createElement: el } = wp.element;
    
    registerBlockType("td/laboratoires-carousel", {
        title: "Carrousel Laboratoires",
        icon: "building",
        category: "widgets",
        description: "Affiche les laboratoires en carrousel",
        
        edit: function() {
            const blockProps = useBlockProps();
            const [laboratoires, setLaboratoires] = useState([]);
            const [loading, setLoading] = useState(true);
            const [currentIndex, setCurrentIndex] = useState(0);
            const intervalRef = useRef(null);
            
            useEffect(() => {
                wp.apiFetch({ path: "/wp/v2/td_laboratoire?per_page=100" })
                    .then((data) => {
                        if (!data || data.length === 0) {
                            setLaboratoires([]);
                            setLoading(false);
                            return;
                        }
                        
                        const labsWithMeta = data.map(lab => ({
                            id: lab.id,
                            title: lab.title.rendered,
                            ville: lab.laboratoire_meta?.ville || "",
                            logo: lab.featured_media
                        }));
                        
                        const logoPromises = labsWithMeta.map(lab => {
                            if (!lab.logo) return Promise.resolve(lab);
                            return wp.apiFetch({ path: `/wp/v2/media/${lab.logo}` })
                                .then(media => ({
                                    ...lab,
                                    logoUrl: media.media_details?.sizes?.medium?.source_url || media.source_url
                                }))
                                .catch(() => lab);
                        });
                        
                        return Promise.all(logoPromises);
                    })
                    .then((labs) => {
                        if (labs) {
                            setLaboratoires(labs);
                        }
                        setLoading(false);
                    })
                    .catch((error) => {
                        console.error("Erreur lors du chargement des laboratoires:", error);
                        setLoading(false);
                    });
            }, []);
            
            useEffect(() => {
                if (laboratoires.length > 3) {
                    intervalRef.current = setInterval(() => {
                        setCurrentIndex(prev => (prev + 1) % Math.max(1, laboratoires.length - 2));
                    }, 3000);
                    
                    return () => {
                        if (intervalRef.current) {
                            clearInterval(intervalRef.current);
                        }
                    };
                }
            }, [laboratoires]);
            
            const handlePrev = () => {
                if (intervalRef.current) {
                    clearInterval(intervalRef.current);
                }
                setCurrentIndex(prev => Math.max(0, prev - 1));
            };
            
            const handleNext = () => {
                if (intervalRef.current) {
                    clearInterval(intervalRef.current);
                }
                const maxIndex = Math.max(0, laboratoires.length - 3);
                setCurrentIndex(prev => Math.min(maxIndex, prev + 1));
            };
            
            if (loading) {
                return el(
                    "div",
                    blockProps,
                    el("p", { style: { textAlign: "center", padding: "20px" } }, "Chargement des laboratoires...")
                );
            }
            
            if (laboratoires.length === 0) {
                const adminUrl = window.location.origin + "/wp-admin/edit.php?post_type=td_laboratoire";
                return el(
                    "div",
                    blockProps,
                    el(
                        "div",
                        { style: { padding: "20px", background: "#f0f0f0", border: "2px dashed #ccc", textAlign: "center" } },
                        el("span", { className: "dashicons dashicons-building", style: { fontSize: "40px", color: "#666" } }),
                        el("p", { style: { margin: "10px 0 0 0", color: "#666" } }, "Aucun laboratoire ajouté"),
                        el("p", { style: { margin: "5px 0 0 0", fontSize: "12px", color: "#999" } }, "Ajoutez des laboratoires pour les voir ici"),
                        el(
                            "a",
                            { 
                                href: adminUrl,
                                style: { 
                                    display: "inline-block",
                                    marginTop: "10px",
                                    padding: "8px 16px",
                                    background: "#0073aa",
                                    color: "#fff",
                                    textDecoration: "none",
                                    borderRadius: "4px",
                                    fontSize: "13px"
                                }
                            },
                            "Gérer les laboratoires"
                        )
                    )
                );
            }
            
            const maxIndex = Math.max(0, laboratoires.length - 3);
            const visibleLabs = laboratoires.slice(currentIndex, currentIndex + 3);
            
            return el(
                "div",
                blockProps,
                el(
                    "div",
                    { 
                        className: "td-lab-carousel-editor", 
                        style: { 
                            position: "relative",
                            padding: "20px", 
                            background: "#f9f9f9", 
                            borderRadius: "8px",
                            overflow: "hidden"
                        } 
                    },
                    laboratoires.length > 3 ? el(
                        "button",
                        { 
                            onClick: handlePrev,
                            disabled: currentIndex === 0,
                            style: { 
                                position: "absolute",
                                left: "10px",
                                top: "50%",
                                transform: "translateY(-50%)",
                                background: currentIndex === 0 ? "rgba(0,0,0,0.3)" : "rgba(0,0,0,0.5)",
                                color: "#fff",
                                border: "none",
                                width: "40px",
                                height: "40px",
                                borderRadius: "50%",
                                fontSize: "1.5rem",
                                cursor: currentIndex === 0 ? "not-allowed" : "pointer",
                                zIndex: 10
                            }
                        },
                        "‹"
                    ) : null,
                    el(
                        "div",
                        { style: { display: "flex", gap: "1rem", padding: "10px 50px", transition: "transform 0.5s ease" } },
                        visibleLabs.map(lab => 
                            el(
                                "div",
                                { 
                                    key: lab.id, 
                                    className: "td-lab-slide", 
                                    style: { 
                                        flex: "0 0 calc(33.333% - 0.67rem)", 
                                        textAlign: "center", 
                                        padding: "1.5rem", 
                                        background: "#fff", 
                                        borderRadius: "8px", 
                                        boxShadow: "0 2px 8px rgba(0,0,0,0.1)" 
                                    } 
                                },
                                lab.logoUrl ? el("img", { src: lab.logoUrl, alt: lab.title, style: { maxWidth: "150px", height: "auto", margin: "0 auto 1rem", display: "block" } }) : null,
                                el("h3", { style: { fontSize: "1.2rem", margin: "0.5rem 0", color: "#333" } }, lab.title),
                                lab.ville ? el("p", { className: "td-lab-ville", style: { fontSize: "0.95rem", color: "#666", margin: "0.5rem 0 0" } }, lab.ville) : null
                            )
                        )
                    ),
                    laboratoires.length > 3 ? el(
                        "button",
                        { 
                            onClick: handleNext,
                            disabled: currentIndex >= maxIndex,
                            style: { 
                                position: "absolute",
                                right: "10px",
                                top: "50%",
                                transform: "translateY(-50%)",
                                background: currentIndex >= maxIndex ? "rgba(0,0,0,0.3)" : "rgba(0,0,0,0.5)",
                                color: "#fff",
                                border: "none",
                                width: "40px",
                                height: "40px",
                                borderRadius: "50%",
                                fontSize: "1.5rem",
                                cursor: currentIndex >= maxIndex ? "not-allowed" : "pointer",
                                zIndex: 10
                            }
                        },
                        "›"
                    ) : null,
                    el("p", { style: { textAlign: "center", fontSize: "11px", color: "#999", marginTop: "10px" } }, `Aperçu du carrousel (${laboratoires.length} laboratoires) - Défilement automatique actif`)
                )
            );
        },
        
        save: function() {
            return null;
        }
    });
})(window.wp);
