import React, { useState, useEffect, useRef } from 'react';

// --- Icons (using SVG for better performance and scalability) ---
const HeartIcon = ({ filled, className }) => (
    <svg xmlns="http://www.w3.org/2000/svg" className={`h-6 w-6 transition-colors duration-300 ${filled ? 'text-red-500' : 'text-gray-400'} ${className}`} fill={filled ? 'currentColor' : 'none'} viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
        <path strokeLinecap="round" strokeLinejoin="round" d="M4.318 6.318a4.5 4.5 0 016.364 0L12 7.636l1.318-1.318a4.5 4.5 0 016.364 6.364L12 20.364l-7.682-7.682a4.5 4.5 0 010-6.364z" />
    </svg>
);
const CartIcon = ({ className }) => (
    <svg xmlns="http://www.w3.org/2000/svg" className={`h-6 w-6 ${className}`} fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
        <path strokeLinecap="round" strokeLinejoin="round" d="M3 3h2l.4 2M7 13h10l4-8H5.4M7 13L5.4 5M7 13l-2.293 2.293c-.63.63-.184 1.707.707 1.707H17m0 0a2 2 0 100 4 2 2 0 000-4zm-8 2a2 2 0 11-4 0 2 2 0 014 0z" />
    </svg>
);
const HomeIcon = () => <svg xmlns="http://www.w3.org/2000/svg" className="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6" /></svg>;
const UserIcon = () => <svg xmlns="http://www.w3.org/2000/svg" className="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" /></svg>;
const BackIcon = () => <svg xmlns="http://www.w3.org/2000/svg" className="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" /></svg>;
const StarIcon = ({ className }) => <svg xmlns="http://www.w3.org/2000/svg" className={`h-5 w-5 ${className}`} viewBox="0 0 20 20" fill="currentColor"><path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z" /></svg>;
const FacebookIcon = ({ className }) => (
    <svg xmlns="http://www.w3.org/2000/svg" className={`h-6 w-6 ${className}`} fill="currentColor" viewBox="0 0 24 24">
        <path d="M9 8h-3v4h3v12h5v-12h3.642l.358-4h-4v-1.667c0-.955.192-1.333 1.115-1.333h2.885v-5h-3.808c-3.596 0-5.192 1.583-5.192 4.615v2.385z"/>
    </svg>
);
const WhatsAppIcon = ({ className }) => (
    <svg xmlns="http://www.w3.org/2000/svg" className={`h-6 w-6 ${className}`} fill="currentColor" viewBox="0 0 24 24">
        <path d="M.057 24l1.687-6.163c-1.041-1.804-1.588-3.849-1.587-5.946.003-6.556 5.338-11.891 11.893-11.891 3.181.001 6.167 1.24 8.413 3.488 2.245 2.248 3.487 5.235 3.487 8.413 0 6.557-5.338 11.892-11.894 11.892-1.99 0-3.903-.52-5.586-1.456l-6.162 1.688zm7.472-6.76c.227.006.454.013.682.02 1.806.05 3.572-.594 4.968-1.745 1.564-1.29 2.522-3.14 2.521-5.136.001-3.95-3.221-7.171-7.172-7.171-1.933 0-3.743.78-5.071 2.109-1.328 1.328-2.108 3.138-2.108 5.071.001 2.04.852 3.945 2.274 5.34l-.235.396-1.043 3.75 3.84-1.045.397-.234c1.438 1.18 3.284 1.83 5.212 1.83.001 0 .002 0 .003 0z"/>
    </svg>
);
const AssistantIcon = ({ className }) => (
    <svg xmlns="http://www.w3.org/2000/svg" className={`h-6 w-6 ${className}`} viewBox="0 0 24 24" fill="currentColor">
        <path d="M12 2a10 10 0 00-9.995 9.05C2.003 16.402 6.402 20.8 11.05 20.995A10 10 0 0022 12c0-5.523-4.477-10-10-10zm0 2a8 8 0 017.995 7.05C19.997 15.458 16.458 18.997 12.95 19.005A8 8 0 014 12c0-4.418 3.582-8 8-8zm-1 3a1 1 0 112 0v4a1 1 0 11-2 0V7zm0 8a1 1 0 112 0 1 1 0 01-2 0z"/>
        <path d="M12 16a4 4 0 100-8 4 4 0 000 8z" opacity="0.5"/>
    </svg>
);
const SendIcon = ({ className }) => (
    <svg xmlns="http://www.w3.org/2000/svg" className={`h-6 w-6 ${className}`} viewBox="0 0 24 24" fill="currentColor">
        <path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"/>
    </svg>
);
const CloseIcon = ({ className }) => (
    <svg xmlns="http://www.w3.org/2000/svg" className={`h-6 w-6 ${className}`} fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
        <path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
    </svg>
);
const TrashIcon = ({ className }) => (
    <svg xmlns="http://www.w3.org/2000/svg" className={`h-6 w-6 ${className}`} fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
        <path strokeLinecap="round" strokeLinejoin="round" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
    </svg>
);


// --- Translations Object ---
const translations = {
    ar: {
        parentCompany: "شركة الكراشي القابضة",
        slogan: "لـنـوم هـانـئ وعـمـيـق",
        reviews: "تقييم",
        addToCart: "أضف للسلة",
        currency: "أوقية جديدة",
        back: "رجوع",
        height: "الارتفاع (cm)",
        dimensions: "الأبعاد",
        selectOption: "اختر...",
        notAvailable: "غير متوفر",
        addNewDimension: "أضف بعد جديد",
        customDimensions: "أبعاد مخصصة",
        width: "العرض (cm)",
        length: "الطول (cm)",
        assistant: "Doctor Sleep",
        welcomeMessage: "مرحباً بك! أنا Dr. Sleep، خبير النوم في Maucit. كيف يمكنني مساعدتك في العثور على ماطلة أحلامك؟",
        typeMessage: "اسأل عن أفضل ماطلة...",
        comfort: "الراحة",
        technology: "التقنية",
        cart: "السلة",
        yourCart: "سلتك",
        total: "الإجمالي",
        removeItem: "إزالة",
        emptyCart: "سلتك فارغة.",
        payNow: "ادفع الآن", // Added translation for "Pay Now"
        sleepCarousel: {
            title: "أهمية النوم",
            slide1: {
                heading: "لماذا النوم مهم؟",
                text: "متوسط وقت النوم الموصى به هو 8 ساعات في الليلة. نقضي حوالي 1/3 من حياتنا في النوم.",
                image: "/images/products/dor.jpeg" // Placeholder image for sleep importance
            },
            slide2: {
                heading: "صحة العمود الفقري",
                text: "يدعم النوم الجيد صحة العمود الفقري ويمنع مشاكل الظهر. اختيار المرتبة الصحيحة أمر بالغ الأهمية.",
                image: "/images/products/sireno33.jpeg" // Placeholder image for spine health
            },
            slide3: {
                heading: "أوضاع النوم الشائعة",
                text: "78% ينامون على الجانب، 15% على الظهر، و 7% على البطن. المرتبة الجيدة تتكيف مع وضعيتك.",
                image: "/images/products/dor.jpeg" // Placeholder image for sleeping positions
            },
            slide4: {
                heading: "فوائد النوم الجيد",
                text: "يحسن المزاج، يزيد الإنتاجية والإبداع والتركيز، يقوي الذاكرة، ويقلل مخاطر الأمراض.",
                image: "/images/products/zenova22.jpeg" // Placeholder image for benefits of sleep
            }
        }
    },
    fr: {
        parentCompany: "El Karachi Holdings",
        slogan: "Pour un sommeil paisible et profond",
        reviews: "avis",
        addToCart: "Ajouter au panier",
        currency: "MRU",
        back: "Retour",
        height: "Hauteur (cm)",
        dimensions: "Dimensions",
        selectOption: "Choisir...",
        notAvailable: "Indisponible",
        addNewDimension: "Nouveau format",
        customDimensions: "Dimensions personnalisées",
        width: "Largeur (cm)",
        length: "Longueur (cm)",
        assistant: "Dr. Sleep",
        welcomeMessage: "Bienvenue ! Je suis Dr. Sleep, l'expert en sommeil de Mosit. Comment puis-je vous aider à trouver le matelas de vos rêves ?",
        typeMessage: "Demandez le meilleur matelas...",
        comfort: "Confort",
        technology: "Technologie",
        cart: "Panier",
        yourCart: "Votre panier",
        total: "Total",
        removeItem: "Supprimer",
        emptyCart: "Votre panier est vide.",
        payNow: "Payer maintenant", // Added translation for "Pay Now"
        sleepCarousel: {
            title: "L'importance du sommeil",
            slide1: {
                heading: "Pourquoi le sommeil est-il important ?",
                text: "Le temps de sommeil recommandé est de 8h par nuit en moyenne. Nous passons environ 1/3 de notre vie à dormir.",
                image: "/images/products/zenova22.jpeg" // Placeholder image for sleep importance
            },
            slide2: {
                heading: "Santé de la colonne vertébrale",
                text: "Un bon sommeil soutient la santé de la colonne vertébrale et prévient les problèmes de dos. Le bon matelas est crucial.",
                image: "/images/products/zenova22.jpeg" // Placeholder image for spine health
            },
            slide3: {
                heading: "Positions de sommeil courantes",
                text: "78% dorment sur le côté, 15% sur le dos et 7% sur le ventre. Un bon matelas s'adapte à votre position.",
                image: "/images/products/zenova33.jpeg" // Placeholder image for sleeping positions
            },
            slide4: {
                heading: "Bénéfices d'un bon sommeil",
                text: "Améliore l'humeur, augmente la productivité, la créativité, la concentration, renforce la mémoire et réduit les risques de maladies.",
                image: "/images/products/dor.jpeg" // Placeholder image for benefits of sleep
            }
        }
    }
};

// --- Data based on the provided table and PDF files ---
const productsData = {
    Dormito: {
        image: '/images/products/dor.jpeg',
        rating: 4.2,
        reviews: 150,
        comfort: "Standard",
        technology: "Mousse",
        prices: { "4": { "60x120": 714, "80x190": 857, "90x190": 929 } } },
    Kenza: {
        image: "/images/products/kenza.png",
        rating: 4.5,
        reviews: 320,
        comfort: "Firm",
        technology: "Matelas en mousse de polyuréthane de densité minimum de 19 kg/m3 (+/-5%)",
        prices: { "15": { "90x190": 2000 }, "20": { "140x190": 3714 } }
    },
    Zenova: {
        image: "/images/products/zenova33.jpeg",
        rating: 4.8,
        reviews: 850,
        // Zenova has multiple comfort/technology based on height (density)
        // This will be handled by the chatbot's logic based on user query
        prices: {
            "20": { // Zenova 22 in PDF, but 20 in data
                comfort: "Mid Firm",
                technology: "Matelas en mousse de polyuréthane de densité minimum de 22 kg/m3 (+/-5%)",
                "90x190": 3857, "140x190": 5143, "160x190": 5571, "160x200": 5714
            },
            "22": { // Zenova 27 in PDF, but 22 in data
                comfort: "Extra Firm",
                technology: "Matelas en mousse de polyuréthane de densité minimum de 27 kg/m3 (5%-10%)",
                "90x190": 4143, "140x190": 5429, "160x190": 6000, "160x200": 6143
            },
            "25": { // Zenova 33 in PDF, but 25 in data
                comfort: "Plush",
                technology: "Matelas en mousse de polyuréthane de densité minimum de 33 kg/m3 (+5%-10%)",
                "90x190": 4714, "140x190": 6143, "160x190": 6857, "160x200": 7143, "180x200": 7143
            }
        }
    },
    "Mauridorsal 22": { image: "/images/products/zenova22.jpeg", rating: 4.7, reviews: 600, comfort: "Standard", technology: "Unknown", prices: { "25": { "90x190": 5286, "140x190": 7143, "160x190": 7857, "160x200": 8143, "180x200": 8857 } } },
    "Mauridorsal 27": { image: "/images/products/zenova27.jpeg", rating: 4.9, reviews: 750, comfort: "Standard", technology: "Unknown", prices: { "20": { "90x190": 5000, "140x190": 6714, "160x190": 7429, "160x200": 7714, "180x200": 8429 }, "22": { "90x190": 5286, "140x190": 7143, "160x190": 7857, "160x200": 8143, "180x200": 8857 }, "25": { "90x190": 5571, "140x190": 7714, "160x190": 8429, "160x200": 8857, "180x200": 9714 } } },
    Luna: {
        image: "/images/products/sireno33.jpeg",
        rating: 4.6,
        reviews: 400,
        comfort: "Standard",
        technology: "Unknown",
        prices: { "25": { "160x200": 9000 }, "30": { "180x200": 12000 } } },
    Sereno: {
        image: "/images/products/sireno27.jpeg",
        rating: 4.9,
        reviews: 1100,
        // Sereno has multiple comfort/technology based on height (density)
        prices: {
            "25": { // Sereno 27 in PDF, but 25 in data
                comfort: "FIRM motion separation",
                technology: "Matelas à ressorts ensaché 256 spring/m2 entouré d'une bordure en mousse de dénsité 27 très ferme. Faces de couchage en mousse de densité 27 d'épaisseur 5cm.",
                "90x190": 5850, "140x190": 9100, "160x190": 10400, "160x200": 11050, "180x200": 12350, "200x200": 13780
            },
            "30": { // Sereno 33 in PDF, but 30 in data
                comfort: "Plush motion separation",
                technology: "Matelas à ressorts ensaché 256 spring/m2 entouré d'une bordure en mousse de dénsité 27 très ferme. Faces de couchage en mousse de densité 33 d'épaisseur 6cm.",
                "90x190": 7020, "140x190": 10920, "160x190": 12610, "160x200": 13260, "180x200": 14820, "200x200": 16510
            }
        }
    }
};
// --- Reusable Animated Component ---
const AnimatedItem = ({ children, delay = 0, y = 20, className }) => (
    <div className={`transition-all duration-700 ease-out ${className}`} style={{ transform: `translateY(${y}px)`, opacity: 0, transitionDelay: `${delay}ms` }}>
        {children}
    </div>
);


const CheckOptions = ({ label, options, selected, setSelected, delay, disabled = false }) => {
    return (
        <AnimatedItem delay={delay} className="detail-animated w-full">
            <div>
                <label className={`font-bold text-lg mb-3 text-blue-900 block ${disabled ? 'opacity-50' : ''}`}>{label}</label>
                <div className="flex flex-wrap gap-3">
                    {options.map(option => (
                        <button
                            key={option}
                            onClick={() => setSelected(option)}
                            disabled={disabled}
                            className={`px-5 py-2 rounded-full font-semibold transition-all duration-300 border-2 disabled:opacity-50 disabled:cursor-not-allowed ${
                                selected === option
                                    ? 'bg-blue-600 text-white border-transparent shadow-md'
                                    : 'bg-white text-blue-800 border-blue-200'
                            }`}
                        >
                            {option}
                        </button>
                    ))}
                </div>
            </div>
        </AnimatedItem>
    );
};

// --- Page Components ---
const ProductDetailPage = ({ product, onBack, isVisible, lang, t, onAddToCart }) => {
    const [selectedHeight, setSelectedHeight] = useState(null);
    const [selectedDimension, setSelectedDimension] = useState(null);
    const [currentPrice, setCurrentPrice] = useState(null);
    const [showCustomDimensions, setShowCustomDimensions] = useState(false);
    const [customInputs, setCustomInputs] = useState({ customLength: '', customWidth: '', customHeight: '' });

    const handleDimensionSelect = (value) => {
        if (value === t.addNewDimension) {
            setShowCustomDimensions(true);
            setSelectedDimension(value);
            setCurrentPrice(null);
        } else {
            setShowCustomDimensions(false);
            setSelectedDimension(value);
        }
    };

    useEffect(() => {
        if (isVisible && product && product.prices) {
            document.querySelectorAll('.detail-animated').forEach(item => {
                item.style.transform = 'translateY(0px)';
                item.style.opacity = '1';
            });
            const heights = Object.keys(product.prices);
            const initialHeight = heights.length > 0 ? heights[0] : null; // Ensure initialHeight is not undefined
            setSelectedHeight(initialHeight);
            setShowCustomDimensions(false);
        }
    }, [isVisible, product]);

    useEffect(() => {
        // Ensure selectedHeight is not null before trying to access product.prices[selectedHeight]
        // AND ensure product.prices[selectedHeight] is not null/undefined
        if(product && product.prices && selectedHeight && product.prices[selectedHeight]){ // Added product.prices[selectedHeight] check
            const dimensionsForHeight = Object.keys(product.prices[selectedHeight]).filter(key => key !== 'comfort' && key !== 'technology');
            if (!dimensionsForHeight.includes(selectedDimension) && dimensionsForHeight.length > 0) {
                setSelectedDimension(dimensionsForHeight[0]);
            } else if (dimensionsForHeight.length === 0 && selectedDimension !== t.addNewDimension) {
                setSelectedDimension(null);
            }
        } else {
            setSelectedDimension(null); // Reset if no product, prices, selectedHeight, or valid product.prices[selectedHeight]
        }
    }, [selectedHeight, product, selectedDimension, t.addNewDimension]);

    useEffect(() => {
        // Ensure selectedHeight and selectedDimension are not null before calculating price
        if (product && product.prices && selectedHeight && selectedDimension && !showCustomDimensions) {
            // Ensure product.prices[selectedHeight] exists before accessing
            if (product.prices[selectedHeight]) {
                const price = product.prices[selectedHeight][selectedDimension];
                setCurrentPrice(price || null);
            } else {
                setCurrentPrice(null);
            }
        } else {
            setCurrentPrice(null);
        }
    }, [product, selectedHeight, selectedDimension, showCustomDimensions]);

    const handleAddToCartClick = () => {
        if (product && selectedHeight && selectedDimension && currentPrice) {
            onAddToCart({
                id: `${product.id}-${selectedHeight}-${selectedDimension}`, // Unique ID for cart item
                name: product.name,
                image: product.image,
                height: selectedHeight,
                dimension: selectedDimension,
                price: currentPrice
            });
        }
        // Optionally, provide feedback to the user (e.g., a toast notification)
    };

    if (!product) return null;

    const availableHeights = product.prices ? Object.keys(product.prices) : [];
    const availableDimensions = (product.prices && selectedHeight && product.prices[selectedHeight]) ? [...Object.keys(product.prices[selectedHeight]).filter(key => key !== 'comfort' && key !== 'technology'), t.addNewDimension] : [t.addNewDimension];

    const isAddToCartDisabled = !currentPrice && !showCustomDimensions;

    return (
        <div className="absolute inset-0 bg-gray-50 z-20 flex flex-col overflow-hidden">
            <div className="absolute top-0 -right-1/4 w-1/2 h-full bg-yellow-200/40 rounded-full blur-3xl transform -translate-x-1/2 z-[-1]" />
            <header className="py-4 px-6 flex-shrink-0 flex justify-between items-center z-10">
                <AnimatedItem y={0} delay={0} className="detail-animated"><button onClick={onBack} className="p-2 text-blue-900 font-bold flex items-center gap-2"><BackIcon /><span>{t.back}</span></button></AnimatedItem>
                <AnimatedItem y={0} delay={100} className="detail-animated"><img src="/images/logo.jpg" alt="Mosit Logo" className="h-10 w-auto" onError={(e) => { e.target.onerror = null; e.target.src='/images/dr.png' }} /></AnimatedItem>
                <AnimatedItem y={0} delay={0} className="detail-animated"><HeartIcon className="text-gray-600 hover:text-red-500" /></AnimatedItem>
            </header>
            <div className="flex-grow overflow-y-auto pb-28">
                <div className="container mx-auto px-6 pt-4 flex flex-col md:flex-row items-center gap-8">
                    <div className="w-full md:w-1/2 relative h-64 md:h-80">
                        <AnimatedItem delay={200} className="detail-animated absolute w-full h-full"><div className="w-full h-full bg-yellow-300 rounded-tl-[50%] rounded-tr-[60%] rounded-bl-[70%] rounded-br-[40%] blur-xl opacity-70"></div></AnimatedItem>
                        <AnimatedItem delay={400} className="detail-animated relative z-10 w-full h-full"><img src={product.image} alt={product.name} className="w-full h-full object-contain transform -rotate-12" onError={(e) => { e.target.onerror = null; e.target.src='https://placehold.co/300x200/E2E8F0/4A5568?text=Product' }} /></AnimatedItem>
                    </div>
                    <div className="w-full md:w-1/2">
                        <AnimatedItem delay={500} className="detail-animated"><h2 className="text-4xl md::text-5xl font-extrabold text-blue-900 leading-tight text-center md:text-right">{product.name}</h2></AnimatedItem>
                        <AnimatedItem delay={600} className="detail-animated"><div className="mt-4 flex justify-center md:justify-start items-center"><div className="flex">{[...Array(5)].map((_, i) => <StarIcon key={i} className={i < Math.round(product.rating) ? "text-yellow-400" : "text-gray-300"} />)}</div><span className="text-gray-500 text-sm mx-2">({product.reviews} {t.reviews})</span></div></AnimatedItem>
                        {/* Display comfort and technology if available */}
                        {product.comfort && selectedHeight === null && (
                            <AnimatedItem delay={650} className="detail-animated mt-2 text-gray-700 text-center md:text-right">
                                <p className="font-semibold">{t.comfort}: {product.comfort}</p>
                            </AnimatedItem>
                        )}
                        {product.technology && selectedHeight === null && (
                            <AnimatedItem delay={700} className="detail-animated mt-1 text-gray-600 text-sm text-center md:text-right">
                                <p>{t.technology}: {product.technology}</p>
                            </AnimatedItem>
                        )}
                        {selectedHeight && product.prices[selectedHeight] && product.prices[selectedHeight].comfort && (
                            <AnimatedItem delay={650} className="detail-animated mt-2 text-gray-700 text-center md:text-right">
                                <p className="font-semibold">{t.comfort}: {product.prices[selectedHeight].comfort}</p>
                            </AnimatedItem>
                        )}
                        {selectedHeight && product.prices[selectedHeight] && product.prices[selectedHeight].technology && (
                            <AnimatedItem delay={700} className="detail-animated mt-1 text-gray-600 text-sm text-center md:text-right">
                                <p>{t.technology}: {product.prices[selectedHeight].technology}</p>
                            </AnimatedItem>
                        )}
                    </div>
                </div>
                <div className="container mx-auto px-6 mt-8">
                    <div className="w-full space-y-6">
                        <CheckOptions label={t.height} options={availableHeights} selected={selectedHeight} setSelected={setSelectedHeight} delay={700} />
                        <CheckOptions label={t.dimensions} options={availableDimensions} selected={selectedDimension} setSelected={handleDimensionSelect} delay={800} disabled={!selectedHeight}/>
                        <div className={`transition-all duration-500 ease-in-out overflow-hidden ${showCustomDimensions ? 'max-h-96 opacity-100 mt-4' : 'max-h-0 opacity-0'}`}>
                            <div className="bg-white p-4 rounded-lg shadow-inner space-y-4">
                                <h3 className="font-bold text-lg text-blue-900">{t.customDimensions}</h3>
                                <div className="grid grid-cols-3 gap-3">
                                    <input type="number" placeholder={t.length} value={customInputs.customLength} onChange={(e) => setCustomInputs({...customInputs, customLength: e.target.value})} className="p-2 border border-gray-300 rounded-md text-center" />
                                    <input type="number" placeholder={t.width} value={customInputs.customWidth} onChange={(e) => setCustomInputs({...customInputs, customWidth: e.target.value})} className="p-2 border border-gray-300 rounded-md text-center" />
                                    <input type="number" placeholder={t.height} value={customInputs.customHeight} onChange={(e) => setCustomInputs({...customInputs, customHeight: e.target.value})} className="p-2 border border-gray-300 rounded-md text-center" />
                                </div>
                            </div>
                        </div>
                    </div>
                    <AnimatedItem delay={900} className="detail-animated mt-8">
                        <button onClick={handleAddToCartClick} className="w-full bg-blue-600 text-white px-8 py-4 rounded-full font-bold text-lg shadow-lg hover:bg-blue-700 transition-all duration-300 transform hover:scale-105 disabled:bg-gray-400 disabled:cursor-not-allowed" disabled={isAddToCartDisabled}>
                            {showCustomDimensions ? t.addToCart : (currentPrice ? `${t.addToCart} - ${currentPrice} ${t.currency}` : t.selectOption)}
                        </button>
                    </AnimatedItem>
                </div>
            </div>
        </div>
    );
};

// New component for the parent company header
const ParentCompanyHeader = ({ lang, t }) => (
    <div className="bg-white py-2 shadow-sm text-center">
        <a href="https://elkarachiholdings.com/" target="_blank" rel="noopener noreferrer" className="flex flex-col items-center justify-center">
            <img
                src="https://elkarachiholdings.com/wp-content/uploads/2024/05/Elkarachi-Holdings-logo-black.png" // Updated to use the provided logo URL
                alt="El Karachi Holdings Logo"
                className="h-10 w-auto mb-1"
                onError={(e) => { e.target.onerror = null; e.target.src='https://placehold.co/150x40/000000/FFFFFF?text=El+Karachi+Holdings' }}
            />
            <p className="text-xs text-gray-600">{t.parentCompany}</p>
        </a>
    </div>
);

// New Carousel Component
const HeroCarousel = ({ slides, lang }) => {
    const [currentSlide, setCurrentSlide] = useState(0);
    const slideInterval = useRef(null);

    useEffect(() => {
        slideInterval.current = setInterval(() => {
            setCurrentSlide((prevSlide) => (prevSlide + 1) % slides.length);
        }, 5000); // Change slide every 5 seconds

        return () => clearInterval(slideInterval.current);
    }, [slides.length]);

    const goToSlide = (index) => {
        setCurrentSlide(index);
        clearInterval(slideInterval.current); // Reset interval on manual navigation
        slideInterval.current = setInterval(() => {
            setCurrentSlide((prevSlide) => (prevSlide + 1) % slides.length);
        }, 5000);
    };

    return (
        <div className="relative w-full h-64 md:h-80 overflow-hidden rounded-b-3xl shadow-lg mb-8">
            {slides.map((slide, index) => (
                <div
                    key={index}
                    className={`absolute inset-0 transition-opacity duration-1000 ease-in-out flex flex-col items-center justify-center p-4 text-center ${
                        index === currentSlide ? 'opacity-100 z-10' : 'opacity-0 z-0'
                    }`}
                    style={{
                        backgroundImage: `url(${slide.image})`,
                        backgroundSize: 'cover',
                        backgroundPosition: 'center',
                        filter: 'brightness(60%)' // Darken image for text readability
                    }}
                >
                    <div className="absolute inset-0 bg-black opacity-40"></div> {/* Overlay for better text contrast */}
                    <div className="relative z-20 text-white">
                        <h3 className="text-2xl md:text-3xl font-bold mb-2">{slide.heading}</h3>
                        <p className="text-sm md:text-base px-4">{slide.text}</p>
                    </div>
                </div>
            ))}
            <div className="absolute bottom-4 left-0 right-0 z-20 flex justify-center space-x-2">
                {slides.map((_, index) => (
                    <button
                        key={index}
                        onClick={() => goToSlide(index)}
                        className={`h-2 w-2 rounded-full transition-all duration-300 ${
                            index === currentSlide ? 'bg-white w-6' : 'bg-gray-400'
                        }`}
                        aria-label={`Go to slide ${index + 1}`}
                    ></button>
                ))}
            </div>
        </div>
    );
};


const HomePage = ({ onProductSelect, isVisible, lang, t }) => {
    const productList = Object.keys(productsData).map(key => {
        const product = productsData[key];
        // If Zenova or Sereno, use the first available comfort/technology for display on the home page
        const comfort = product.comfort || (product.prices && Object.values(product.prices)[0]?.comfort);
        const technology = product.technology || (product.prices && Object.values(product.prices)[0]?.technology);

        return {
            id: key,
            name: key,
            ...product,
            comfort: comfort,
            technology: technology
        };
    });

    return (
        <div className={`transition-opacity duration-300 ${isVisible ? 'opacity-100' : 'opacity-0'} pb-28`}>
            <header className="p-4 flex justify-between items-center">
                <img src="/images/logo.jpg" alt="Mosit Logo" className="h-12 w-auto" onError={(e) => { e.target.onerror = null; e.target.src='https://placehold.co/100x50/E2E8F0/4A5568?text=Logo' }} />
            </header>
            <main className="p-4 mt-4">
                <h2 className="text-2xl font-bold text-gray-800 mb-4">{t.slogan}</h2>
                <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
                    {productList.map((product, index) => (
                        <div key={product.id} onClick={() => onProductSelect(product)} className="cursor-pointer group">
                            <div className="transform transition-all duration-500 opacity-100 translate-y-0">
                                <div className="bg-white rounded-2xl shadow-lg overflow-hidden h-full flex flex-col">
                                    <div className="relative"><img src={product.image} alt={product.name} className="w-full h-40 object-cover transition-transform duration-500 group-hover:scale-110" onError={(e) => { e.target.onerror = null; e.target.src='https://placehold.co/300x200/E2E8F0/4A5568?text=Product' }} /></div>
                                    <div className="p-4 flex-grow flex flex-col">
                                        <h3 className="text-md font-bold text-gray-800 truncate">{product.name}</h3>
                                        <div className="flex justify-between items-center mt-3">
                                            <div className="flex items-center gap-1 text-sm text-yellow-600"><span>{product.rating}</span><StarIcon /></div>
                                        </div>
                                        {product.comfort && (
                                            <p className="text-xs text-gray-500 mt-1">{t.comfort}: {product.comfort}</p>
                                        )}
                                    </div>
                                </div>
                            </div>
                        </div>
                    ))}
                </div>
            </main>
        </div>
    );
}

const Chatbot = ({ isChatOpen, closeChat, lang, t }) => {
    const [messages, setMessages] = useState([]);
    const [inputValue, setInputValue] = useState('');
    const [isLoading, setIsLoading] = useState(false);
    const [position, setPosition] = useState({ x: 0, y: 0 });
    const [isDragging, setIsDragging] = useState(false);
    const [dragStart, setDragStart] = useState({ x: 0, y: 0 });

    const chatHistory = useRef([]);
    const messagesEndRef = useRef(null);
    const chatWindowRef = useRef(null);

    const handleMouseDown = (e) => {
        setIsDragging(true);
        setDragStart({
            x: e.clientX - position.x,
            y: e.clientY - position.y,
        });
    };

    const handleMouseMove = (e) => {
        if (isDragging) {
            setPosition({
                x: e.clientX - dragStart.x,
                y: e.clientY - dragStart.y,
            });
        }
    };

    const handleMouseUp = () => {
        setIsDragging(false);
    };

    useEffect(() => {
        if (isDragging) {
            window.addEventListener('mousemove', handleMouseMove);
            window.addEventListener('mouseup', handleMouseUp);
        } else {
            window.removeEventListener('mousemove', handleMouseMove);
            window.removeEventListener('mouseup', handleMouseUp);
        }
        return () => {
            window.removeEventListener('mousemove', handleMouseMove);
            window.removeEventListener('mouseup', handleMouseUp);
        };
    }, [isDragging]);

    const scrollToBottom = () => {
        messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
    };

    useEffect(scrollToBottom, [messages]);

    useEffect(() => {
        if(isChatOpen){
            const welcomeMsg = { text: t.welcomeMessage, sender: 'bot' };
            setMessages([welcomeMsg]);
            // The system instruction for the AI model, updated with comfort and technology details
            const systemInstruction = `You are Doctor Sleep, a friendly and knowledgeable sleep expert from Mosit. Your ONLY job is to help users choose a mattress from the provided list. Keep your answers very short and concise. If the user asks about anything other than mattresses or sleep, politely decline to answer. Here is the list of available products with their comfort levels, technologies, and prices in '${t.currency}': ${JSON.stringify(productsData)}. When recommending, consider factors like comfort preference (e.g., firm, plush), specific technologies (e.g., memory foam, pocket springs), and dimensions. Always communicate in the language the user is writing in (${lang}).`;
            chatHistory.current = [{ role: "user", parts: [{ text: systemInstruction }] }]; // Initialize with system instruction as a user message to guide the model
        }
    }, [isChatOpen, t, lang]);

    const handleSend = async () => {
        if (inputValue.trim() && !isLoading) {
            const userMessage = { text: inputValue, sender: 'user' };
            setMessages(prev => [...prev, userMessage]);
            setInputValue('');
            setIsLoading(true);

            // Add user message to chat history for the API call
            chatHistory.current.push({ role: "user", parts: [{ text: inputValue }] });

            const payload = { contents: chatHistory.current };
            const apiKey = "AIzaSyAYADv7fa2RWP0iomlgDX9lkRsBejk5oiw"; // API key will be provided by the Canvas environment
            const apiUrl = `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=${apiKey}`; // Directly call Gemini API

            try {
                const response = await fetch(apiUrl, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(payload)
                });
                const result = await response.json();

                if (result.candidates && result.candidates.length > 0 &&
                    result.candidates[0].content && result.candidates[0].content.parts &&
                    result.candidates[0].content.parts.length > 0) {
                    const botResponseText = result.candidates[0].content.parts[0].text;
                    const botResponse = { text: botResponseText, sender: 'bot' };
                    setMessages(prev => [...prev, botResponse]);
                    // Add bot response to chat history for subsequent API calls
                    chatHistory.current.push({ role: "model", parts: [{ text: botResponse.text }] });
                } else {
                    setMessages(prev => [...prev, { text: "Sorry, I couldn't process that. Please try again.", sender: 'bot' }]);
                }
            } catch (error) {
                console.error("Error fetching Gemini API response:", error);
                setMessages(prev => [...prev, { text: "Sorry, something went wrong.", sender: 'bot' }]);
            } finally {
                setIsLoading(false);
            }
        }
    };

    return (
        <div
            ref={chatWindowRef}
            className={`fixed bottom-24 z-50 transition-opacity duration-500 ease-in-out ${isChatOpen ? 'opacity-100' : 'opacity-0 pointer-events-none'}`}
            style={{ transform: `translate(${position.x}px, ${position.y}px)`, ...(lang === 'ar' ? { right: '1rem' } : { left: '1rem' }) }}
        >
            <div className="w-80 h-[28rem] bg-white rounded-2xl shadow-2xl flex flex-col">
                <header
                    className="bg-blue-600 text-white p-3 rounded-t-2xl flex justify-between items-center cursor-move"
                    onMouseDown={handleMouseDown}
                >
                    <h3 className="font-bold">{t.assistant}</h3>
                    <button onClick={closeChat} className="p-1 hover:bg-blue-700 rounded-full cursor-pointer"><CloseIcon className="h-5 w-5"/></button>
                </header>
                <div className="flex-grow p-3 overflow-y-auto">
                    {messages.map((msg, index) => (
                        <div key={index} className={`my-2 p-2 rounded-lg max-w-[80%] ${msg.sender === 'bot' ? 'bg-gray-200 text-gray-800 self-start text-left' : 'bg-blue-500 text-white self-end'}`} style={lang === 'ar' ? (msg.sender === 'bot' ? {textAlign: 'right', marginRight: 'auto'} : {textAlign: 'left', marginLeft: 'auto'}) : {}}>
                            {msg.text}
                        </div>
                    ))}
                    {isLoading && <div className="my-2 p-2 self-start"><span className="animate-pulse">...</span></div>}
                    <div ref={messagesEndRef} />
                </div>
                <div className="p-3 border-t border-gray-200 flex gap-2">
                    <input
                        type="text"
                        value={inputValue}
                        onChange={(e) => setInputValue(e.target.value)}
                        onKeyPress={(e) => e.key === 'Enter' && handleSend()}
                        placeholder={t.typeMessage}
                        className="flex-grow p-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                        disabled={isLoading}
                    />
                    <button onClick={handleSend} className="bg-blue-600 text-white p-2 rounded-lg hover:bg-blue-700 disabled:bg-blue-400" disabled={isLoading}>
                        <SendIcon />
                    </button>
                </div>
            </div>
        </div>
    );
};

// New CartView Component
const CartView = ({ cartItems, onRemoveItem, onClose, lang, t }) => {
    const total = cartItems.reduce((sum, item) => sum + item.price, 0);

    return (
        <div className="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4">
            <div className="bg-white rounded-2xl shadow-2xl w-full max-w-md h-full max-h-[80vh] flex flex-col">
                <header className="bg-blue-600 text-white p-4 rounded-t-2xl flex justify-between items-center">
                    <h3 className="font-bold text-xl">{t.yourCart} ({cartItems.length})</h3>
                    <button onClick={onClose} className="p-1 hover:bg-blue-700 rounded-full cursor-pointer"><CloseIcon className="h-6 w-6"/></button>
                </header>
                <div className="flex-grow p-4 overflow-y-auto">
                    {cartItems.length === 0 ? (
                        <p className="text-center text-gray-600 mt-8">{t.emptyCart}</p>
                    ) : (
                        <ul className="space-y-4">
                            {cartItems.map((item, index) => (
                                <li key={index} className="flex items-center bg-gray-50 p-3 rounded-lg shadow-sm">
                                    <img src={item.image} alt={item.name} className="w-16 h-16 object-cover rounded-md mr-4" onError={(e) => { e.target.onerror = null; e.target.src='https://placehold.co/64x64/E2E8F0/4A5568?text=Item' }} />
                                    <div className="flex-grow">
                                        <h4 className="font-semibold text-gray-800">{item.name}</h4>
                                        <p className="text-sm text-gray-600">{t.height}: {item.height}cm, {t.dimensions}: {item.dimension}</p>
                                        <p className="text-md font-bold text-blue-700">{item.price} {t.currency}</p>
                                    </div>
                                    <button onClick={() => onRemoveItem(index)} className="p-2 text-red-500 hover:text-red-700 transition-colors">
                                        <TrashIcon />
                                    </button>
                                </li>
                            ))}
                        </ul>
                    )}
                </div>
                <footer className="p-4 border-t border-gray-200">
                    <div className="flex justify-between items-center font-bold text-lg text-gray-800">
                        <span>{t.total}:</span>
                        <span>{total} {t.currency}</span>
                    </div>
                    {/* Pay Now Button */}
                    {cartItems.length > 0 && (
                        <button className="mt-4 w-full bg-green-600 text-white px-8 py-3 rounded-full font-bold text-lg shadow-lg hover:bg-green-700 transition-all duration-300">
                            {t.payNow}
                        </button>
                    )}
                    {/* Original "Add to Cart" button, now only visible if cart is empty or for other purposes */}
                    {cartItems.length === 0 && (
                        <button className="mt-4 w-full bg-blue-600 text-white px-8 py-3 rounded-full font-bold text-lg shadow-lg hover:bg-blue-700 transition-all duration-300">
                            {t.addToCart} {/* Re-using add to cart for simplicity, could be "Checkout" */}
                        </button>
                    )}
                </footer>
            </div>
        </div>
    );
};


const BottomNavBar = ({ toggleChat, toggleCart, cartItemCount }) => (
    <nav className="fixed bottom-0 left-0 right-0 bg-white/80 backdrop-blur-lg shadow-[0_-5px_20px_-5px_rgba(0,0,0,0.1)] rounded-t-3xl px-8 py-4 z-30">
        <div className="flex justify-around items-center">
            <button className="text-blue-600"><HomeIcon /></button>
            <button className="text-gray-400 hover:text-blue-600 transition-colors"><HeartIcon filled={false} /></button>
            <button onClick={toggleCart} className="text-gray-400 hover:text-blue-600 transition-colors relative">
                <CartIcon />
                {cartItemCount > 0 && (
                    <span className="absolute -top-2 -right-2 bg-red-500 text-white text-xs font-bold rounded-full h-5 w-5 flex items-center justify-center">
                        {cartItemCount}
                    </span>
                )}
            </button>
            <button className="text-gray-400 hover:text-blue-600 transition-colors"><UserIcon /></button>
        </div>
    </nav>
);

const TopControls = ({ lang, toggleLang, isVisible }) => (
    <div className={`fixed top-4 z-50 transition-opacity duration-300 flex items-center gap-4 ${isVisible ? 'opacity-100' : 'opacity-0 pointer-events-none'}`} style={lang === 'ar' ? { left: '1rem' } : { right: '1rem' }}>
        <div className="flex gap-2">
            <a href="https://www.facebook.com/MositOfficial" target="_blank" rel="noopener noreferrer" className="w-10 h-10 bg-blue-600 text-white rounded-full flex items-center justify-center shadow-lg hover:bg-blue-700 hover:scale-110 transition-transform duration-200">
                <FacebookIcon className="h-6 w-6" />
            </a>
            <a href="https://wa.me/22226262619" target="_blank" rel="noopener noreferrer" className="w-10 h-10 bg-green-500 text-white rounded-full flex items-center justify-center shadow-lg hover:bg-green-600 hover:scale-110 transition-transform duration-200">
                <WhatsAppIcon className="h-6 w-6" />
            </a>
        </div>
        <button onClick={toggleLang} className="bg-white px-4 py-2 rounded-full shadow-lg font-semibold text-blue-900">
            {lang === 'ar' ? 'Français' : 'العربية'}
        </button>
    </div>
);

const DoctorSleepButton = ({ toggleChat, isVisible, lang }) => (
    <div
        className={`fixed bottom-24 z-40 transition-all duration-500 ease-in-out ${isVisible ? 'opacity-100 scale-100' : 'opacity-0 scale-0 pointer-events-none'}`}
        style={lang === 'ar' ? { right: '1rem' } : { left: '1rem' }}
    >
        <button onClick={toggleChat} className="w-24 h-24 rounded-full shadow-3xl hover:scale-150 transition-transform duration-500 focus:outline-none bg-white">
            <img
                src="/images/dr.png" // Placeholder for the image
                alt="Doctor Sleep Assistant"
                className="w-full h-full object-cover rounded-full"
                onError={(e) => { e.target.onerror = null; e.target.src='https://placehold.co/100x100/E2E8F0/4A5568?text=Dr.S' }}
            />
        </button>
    </div>
);


export default function App() {
    const [selectedProduct, setSelectedProduct] = useState(null);
    const [lang, setLang] = useState('ar');
    const [isChatOpen, setIsChatOpen] = useState(false);
    const [cartItems, setCartItems] = useState([]); // New state for cart items
    const [isCartOpen, setIsCartOpen] = useState(false); // New state for cart visibility
    const t = translations[lang];

    useEffect(() => {
        if (selectedProduct || isCartOpen) { document.body.style.overflow = 'hidden'; }
        else { document.body.style.overflow = 'auto'; }
        return () => { document.body.style.overflow = 'auto'; };
    }, [selectedProduct, isCartOpen]);

    const toggleLang = () => { setLang(currentLang => (currentLang === 'ar' ? 'fr' : 'ar')); };

    const toggleChat = () => setIsChatOpen(!isChatOpen);
    const toggleCart = () => setIsCartOpen(!isCartOpen); // Function to toggle cart visibility

    const handleAddToCart = (item) => {
        setCartItems(prevItems => [...prevItems, item]);
        setIsCartOpen(true); // Open cart automatically after adding an item
    };

    const handleRemoveFromCart = (indexToRemove) => {
        setCartItems(prevItems => prevItems.filter((_, index) => index !== indexToRemove));
    };

    const carouselSlides = [
        t.sleepCarousel.slide1,
        t.sleepCarousel.slide2,
        t.sleepCarousel.slide3,
        t.sleepCarousel.slide4,
    ];

    return (
        <div className="bg-gray-50 min-h-screen font-sans" dir={lang === 'ar' ? 'rtl' : 'ltr'}>
            <ParentCompanyHeader lang={lang} t={t} />
            <TopControls lang={lang} toggleLang={toggleLang} isVisible={!selectedProduct && !isCartOpen} />
            {/* Hero Carousel added here */}
            <HeroCarousel slides={carouselSlides} lang={lang} />
            <div className="relative container mx-auto px-4">
                <HomePage onProductSelect={setSelectedProduct} isVisible={!selectedProduct && !isCartOpen} lang={lang} t={t} />
                <div className={`fixed inset-0 z-40 transition-transform duration-500 ease-in-out ${selectedProduct ? 'translate-y-0' : 'translate-y-full'}`}>
                    <ProductDetailPage product={selectedProduct} onBack={() => setSelectedProduct(null)} isVisible={!!selectedProduct} lang={lang} t={t} onAddToCart={handleAddToCart} />
                </div>
            </div>
            <BottomNavBar toggleChat={toggleChat} toggleCart={toggleCart} cartItemCount={cartItems.length} />
            <DoctorSleepButton toggleChat={toggleChat} isVisible={!isChatOpen && !selectedProduct && !isCartOpen} lang={lang} />
            <Chatbot isChatOpen={isChatOpen} closeChat={() => setIsChatOpen(false)} lang={lang} t={t} />
            {isCartOpen && (
                <CartView
                    cartItems={cartItems}
                    onRemoveItem={handleRemoveFromCart}
                    onClose={() => setIsCartOpen(false)}
                    lang={lang}
                    t={t}
                />
            )}
        </div>
    );
}
