Improve the productmodal to work like productdetail...
because currently it is not handling the colors correctly! a product may look like this:
{"products":[{"id":6016,"name":"test","description":"test","brand_id":86,"has_color":true,"has_size":false,"product_type":"color","price":0,"qty":0,"sold":0,"created_at":"2024-10-05T21:55:18.485Z","updated_at":"2024-10-05T21:55:18.485Z","categories":[{"id":178,"name":"Body Cleansers","main_category_id":2,"main_category_name":"Body Care"}],"colors":[{"id":12,"name":"red","price":30000,"qty":30,"sold":0,"has_size":false,"sizes":[],"images":[]}],"sizes":[],"images":[]}.
or like this:
{"product":{"id":6017,"name":"test","description":"test","brand_id":73,"has_color":true,"has_size":false,"product_type":"color_size","price":0,"qty":0,"sold":0,"created_at":"2024-10-05T22:04:30.971Z","updated_at":"2024-10-05T22:04:30.971Z","categories":[{"id":178,"name":"Body Cleansers","main_category_id":2,"main_category_name":"Body Care"}],"colors":[{"id":13,"name":"red","price":0,"qty":0,"sold":0,"has_size":true,"sizes":[{"id":6044,"name":"30ml","price":30000,"qty":30,"sold":0,"color_id":13,"images":[]}],"images":[]},{"id":14,"name":"green","price":50000,"qty":50,"sold":0,"has_size":false,"sizes":[],"images":[]}],"sizes":[],"images":[]}}
or like this:
{"product":{"id":6000,"name":"‏Shea Moisture Manuka Honey & Mafura Oil Intensive Hydration Hair Masque ","description":"ماسك الترطيب المكثف من شيا مويسجر.\nبخلاصة عسل المانوكا وزيت المافورا مع مستخلص التين الافريقي.\nماسك مليء بالمواد التي تغذي الشعر وترطبه بعمق لتجعل بصيلات الشعر اكثر صحةً و نعومة.\n-يمتلك عسل المانوكا خواص مهدئة ومرطبة لفروة الرأس.\n-اما زيت المافورا فهو يزود الشعر ب oleic acid الذي يعزز ترطيب الشعر.\n-والتين الافريقي يحتوي على فيتامين C و مضادات الاكسدة مما يمنح الشعر مظهراً حيوياً.","brand_id":248,"has_color":false,"has_size":true,"product_type":"size","price":0,"qty":0,"sold":0,"created_at":"2024-10-02T13:46:33.443Z","updated_at":"2024-10-05T17:18:49.183Z","categories":[{"id":5,"name":"Masks","main_category_id":3,"main_category_name":"Hair Care"}],"colors":[],"sizes":[{"id":6003,"name":"283 g","price":20000,"qty":34,"sold":0,"color_id":null,"images":[]}],"images":[{"id":6328,"url":"5033.jpeg","color_id":null,"size_id":null},{"id":6329,"url":"5034.jpeg","color_id":null,"size_id":null}]}}
ProductDetail.jsx:
'use client';

import React, {
    useState,
    useEffect,
    useCallback,
    useMemo,
    Suspense
} from 'react';
import { ArrowLeft, Minus, Plus } from 'lucide-react';
import 'slick-carousel/slick/slick.css';
import '@/components/NotificationStyles.css';
import 'slick-carousel/slick/slick-theme.css';

const Slider = React.lazy(() => import('react-slick'));
const Lightbox = React.lazy(() => import("yet-another-react-lightbox"));
import Zoom from "yet-another-react-lightbox/plugins/zoom";
import Fullscreen from "yet-another-react-lightbox/plugins/fullscreen";
import "yet-another-react-lightbox/styles.css";
import Image from "next/image";
import { useRouter } from "next/navigation";
import { useNotification } from "@/components/NotificationContext";
import Link from "next/link";
import WishlistHeart from "@/components/WishlistHeart";

const formatPrice = (price) => {
    const formattedPrice = price >= 10000 ? price.toLocaleString() : price.toString();
    return `${formattedPrice} IQD`;
};

export default function ProductDetail({ product, isInWishlist }) {
    const [selectedColor, setSelectedColor] = useState(null);
    const [selectedSize, setSelectedSize] = useState(null);
    const [quantity, setQuantity] = useState(1);
    const [maxQuantity, setMaxQuantity] = useState(1); // New state for max quantity
    const [currentPrice, setCurrentPrice] = useState(product.price);
    const [lightboxOpen, setLightboxOpen] = useState(false);
    const [lightboxIndex, setLightboxIndex] = useState(0);
    const { addNotification } = useNotification();
    const [wishReady, setWishReady] = useState(false)
    const [cartItems, setCartItems] = useState([]);
    const router = useRouter();

    // New state for internal wishlist status
    const [internalIsInWishlist, setInternalIsInWishlist] = useState(false);

    // **New State for Color Images**
    const [colorImages, setColorImages] = useState({});

    // **Memoize unique images to prevent duplicates**
    const images = useMemo(() => {
        const uniqueUrls = new Set(product.images.map(img => img.url || img));
        return Array.from(uniqueUrls);
    }, [product.images]);

    // Memoize lightbox slides
    const lightboxSlides = useMemo(() => {
        return images.map(src => ({
            src: `https://storage.naayiq.com/resources/${src}`
        }));
    }, [images]);

    // **Fetch color images using the API**
    useEffect(() => {
        const fetchColorImages = async () => {
            const updatedColorImages = {};
            await Promise.all(product.colors.map(async (color) => {
                try {
                    const response = await fetch(`https://dev.naayiq.com/colors/${encodeURIComponent(color.name)}`);
                    const data = await response.json();
                    if (data.url) {
                        updatedColorImages[color.id] = `https://storage.naayiq.com/resources/${data.url}`;
                    } else {
                        updatedColorImages[color.id] = null; // Image not found
                    }
                } catch (error) {
                    console.error(`Error fetching image for color ${color.name}:`, error);
                    updatedColorImages[color.id] = null; // On error, treat as not found
                }
            }));
            setColorImages(updatedColorImages);
        };

        fetchColorImages();
    }, [product.colors]);

    // Determine the maximum available quantity based on selected attributes
    const determineMaxQuantity = useCallback(() => {
        if (selectedSize) {
            return selectedSize.qty;
        } else if (selectedColor) {
            return selectedColor.qty;
        } else {
            return product.qty;
        }
    }, [selectedSize, selectedColor, product.qty]);

    useEffect(() => {
        window.scrollTo(0, 0);
        const initializeSelections = () => {
            const cart = JSON.parse(localStorage.getItem('cart')) || [];
            setCartItems(cart);
            if (product.has_color && product.colors.length > 0) {
                const defaultColor = product.colors.find(color => color.qty > 0 || (color.has_size && color.sizes.some(size => size.qty > 0))) || product.colors[0];
                setSelectedColor(defaultColor);

                if (defaultColor.has_size && defaultColor.sizes.length > 0) {
                    const defaultSize = defaultColor.sizes.find(size => size.qty > 0) || defaultColor.sizes[0];
                    setSelectedSize(defaultSize);
                } else {
                    setSelectedSize(null);
                }
            } else if (product.has_size && product.sizes.length > 0) {
                const defaultSize = product.sizes.find(size => size.qty > 0) || product.sizes[0];
                setSelectedSize(defaultSize);
            } else {
                setSelectedSize(null);
            }
            updatePrice();
        };

        initializeSelections();
    }, [product]);

    const updatePrice = useCallback(() => {
        let price = product.price;

        if (selectedSize && selectedSize.price) {
            price = selectedSize.price;
        } else if (selectedColor && selectedColor.price) {
            price = selectedColor.price;
        }

        setCurrentPrice(parseFloat(price));
    }, [product, selectedColor, selectedSize]);

    useEffect(() => {
        setMaxQuantity(determineMaxQuantity());
        if (quantity > determineMaxQuantity()) {
            setQuantity(determineMaxQuantity() || 1);
        }
    }, [determineMaxQuantity, quantity]);

    useEffect(() => {
        updatePrice();
    }, [selectedColor, selectedSize, updatePrice]);

    const handleColorChange = (color) => {
        setSelectedColor(color);
        if (color.has_size && color.sizes.length > 0) {
            const availableSize = color.sizes.find(size => size.qty > 0) || color.sizes[0];
            setSelectedSize(availableSize);
        } else {
            setSelectedSize(null);
        }
    };

    const handleSizeChange = (e) => {
        const sizeId = parseInt(e.target.value);
        const availableSizes = selectedColor && selectedColor.has_size ? selectedColor.sizes : product.sizes;
        const newSize = availableSizes.find(size => size.id === sizeId);
        setSelectedSize(newSize);
    };

    const isInCart = useCallback(() => {
        return cartItems.some(item =>
            item.product_id === product.id &&
            item.color_id === selectedColor?.id &&
            item.size_id === selectedSize?.id
        );
    }, [cartItems, product.id, selectedColor, selectedSize]);

    const handleAddToCart = () => {
        const finalQuantity = Math.min(quantity, maxQuantity);
        const cartItem = {
            product_id: product.id,
            color_id: selectedColor?.id,
            size_id: selectedSize?.id,
            qty: finalQuantity
        };

        let updatedCart = [...cartItems];
        const existingItemIndex = updatedCart.findIndex(item =>
            item.product_id === cartItem.product_id &&
            item.color_id === cartItem.color_id &&
            item.size_id === cartItem.size_id
        );

        if (existingItemIndex > -1) {
            updatedCart[existingItemIndex].qty += finalQuantity;
            // Ensure it does not exceed maxQuantity
            updatedCart[existingItemIndex].qty = Math.min(updatedCart[existingItemIndex].qty, maxQuantity);
        } else {
            updatedCart.push(cartItem);
        }

        localStorage.setItem('cart', JSON.stringify(updatedCart));
        setCartItems(updatedCart);
        addNotification('success', 'Product Added To Cart');
    };

    const sliderSettings = useMemo(() => ({
        dots: images.length > 1,
        infinite: false,
        speed: 500,
        slidesToShow: 1,
        slidesToScroll: 1,
        customPaging: function (i) {
            return (
                <div
                    style={{
                        width: '12px',
                        height: '12px',
                        background: i === this.currentSlide ? '#695C5C' : '#D9D9D9',
                        borderRadius: '50%',
                        padding: 0,
                        margin: '0 4px'
                    }}
                />
            );
        },
    }), [images.length]);

    const isOutOfStock = useMemo(() => {
        if (product.has_color && selectedColor) {
            if (selectedColor.has_size) {
                return !selectedColor.sizes.some(size => size.qty > 0);
            }
            return selectedColor.qty === 0;
        } else if (product.has_size && selectedSize) {
            return selectedSize.qty === 0;
        } else {
            return product.qty === 0;
        }
    }, [product, selectedColor, selectedSize]);

    const fetchWishlist = useCallback(async () => {
        const token = localStorage.getItem("token");
        if (!token) return;

        try {
            const response = await fetch(`${process.env.NEXT_PUBLIC_API}/wishlist`, {
                headers: {
                    'Authorization': `Bearer ${token}`,
                },
            });
            if (response.ok) {
                const w = await response.json();
                const wishlistIds = w.wishlist.map(item => item.id);
                setInternalIsInWishlist(wishlistIds.includes(product.id));
            }
        } catch (error) {
            console.error('Error fetching wishlist:', error);
        }
        setWishReady(true)
    }, [product.id]);

    // Fetch wishlist if isInWishlist prop is undefined
    useEffect(() => {
        if (isInWishlist === undefined) {
            fetchWishlist();
        }
    }, [isInWishlist, fetchWishlist]);

    // Determine the final isInWishlist value;

    return (
        <div className="flex overflow-x-hidden font-serif relative z-50 font-medium flex-col -mt-4 -mx-4 bg-white">
            <Suspense fallback={<div>Loading images...</div>}>
                <Slider {...sliderSettings} className="w-full mb-2 h-[55vh]">
                    {images.map((image, index) => (
                        <div key={index} className="relative w-full h-[60vh]" onClick={() => {
                            setLightboxIndex(index);
                            setLightboxOpen(true);
                        }}>
                            <Image
                                src={`https://storage.naayiq.com/resources/${image}`}
                                alt={`Product image ${index + 1}`}
                                fill={true}
                                unoptimized={true}
                                className="w-full object-cover cursor-pointer"
                                priority={index === 0}
                            />
                        </div>
                    ))}
                </Slider>
            </Suspense>

            <Suspense fallback={<div>Loading lightbox...</div>}>
                <Lightbox
                    open={lightboxOpen}
                    close={() => setLightboxOpen(false)}
                    index={lightboxIndex}
                    slides={lightboxSlides}
                    plugins={[Zoom, Fullscreen]}
                    carousel={{
                        finite: images.length <= 1,
                        navigationDisabled: images.length <= 1
                    }}
                    animation={{ zoom: 500 }}
                    zoom={{
                        maxZoomPixelRatio: 5,
                        zoomInMultiplier: 2,
                        doubleTapDelay: 300,
                        doubleClickDelay: 300,
                        doubleClickMaxStops: 2,
                        keyboardMoveDistance: 50,
                        wheelZoomDistanceFactor: 100,
                        pinchZoomDistanceFactor: 100,
                        scrollToZoom: true,
                    }}
                />
            </Suspense>

            <button
                className="absolute h-12 rounded-[100%] w-12 bg-white-gradient flex justify-center items-center top-4 left-4 z-10"
                onClick={() => router.push("/products")}
            >
                <ArrowLeft width={30} height={30} strokeWidth={1} />
            </button>
            {wishReady && <button
                className="h-12 rounded-[100%] w-12 absolute top-4 right-4 z-10 bg-white-gradient flex justify-center items-center"
            >
                <WishlistHeart
                    id={product.id}
                    isInWishlist2={isInWishlist !== undefined ? isInWishlist : internalIsInWishlist}
                />
            </button>}


            <div
                className="flex-grow bg-white rounded-t-xl shadow-[0px_-4px_8px_3px_rgba(105,92,92,0.1)] p-6 mt-2 relative z-30">
                <div className="w-9 h-1 bg-black opacity-70 rounded-full mx-auto mb-6" />
                <h1 className="text-xl font-semibold mb-1 capitalize">{product.name}</h1>

                {isOutOfStock && (
                    <p className="text-red-500 mt-2 text-lg font-semibold">Out of Stock</p>
                )}

                {product.has_color && product.colors.length > 0 && (
                    <div className="mb-10 mt-6">
                        <h2 className="text-xl font-medium mb-2">Color</h2>
                        <div className="flex space-x-4 overflow-x-auto pb-2">
                            {product.colors.map((color) => (
                                <div key={color.id} className="flex flex-col items-center">
                                    <button
                                        className={`w-20 h-20 rounded-full border-2 ${selectedColor?.id === color.id ? 'border-[#3B5345]' : 'border-[#695C5C] border-opacity-50'} mb-2 overflow-hidden`}
                                        onClick={() => handleColorChange(color)}
                                        disabled={color.qty === 0 && !color.has_size}
                                        aria-label={`Select color ${color.name}`}
                                    >
                                        {/* **Render fetched color image or fallback to white circle** */}
                                        {colorImages[color.id] ? (
                                            <Image
                                                src={colorImages[color.id]}
                                                alt={color.name}
                                                width={80}
                                                height={80}
                                                className="object-cover"
                                            />
                                        ) : (
                                            <div className="w-full h-full bg-white flex items-center justify-center">
                                                <span className="text-sm text-gray-500 capitalize">{color.name.charAt(0)}</span>
                                            </div>
                                        )}
                                    </button>
                                    <span className="text-sm capitalize">{color.name}</span>
                                </div>
                            ))}
                        </div>
                    </div>
                )}

                {((product.has_size && product.sizes.length > 0) || (selectedColor && selectedColor.has_size && selectedColor.sizes.length > 0)) && (
                    <div className="mb-6 font-serif">
                        <select
                            value={selectedSize ? selectedSize.id : ''}
                            onChange={handleSizeChange}
                            className="w-32 p-2 border border-[#E5E7EB] rounded-lg font-serif bg-white"
                            aria-label="Select size"
                        >
                            <option value="" disabled>Select Size</option>
                            {(selectedColor && selectedColor.has_size ? selectedColor.sizes : product.sizes).map((size) => (
                                <option key={size.id} value={size.id} disabled={size.qty === 0}>
                                    Size: {size.name} {size.qty === 0 && '(Out of Stock)'}
                                </option>
                            ))}
                        </select>
                    </div>
                )}

                <div className="mb-6 pb-28">
                    <h2 className="text-xl font-semibold w-fit mb-2">Description</h2>
                    <div
                        style={{ direction: "rtl" }}
                        className="text-xl mr-2 font-normal text-right font-serif"
                        dangerouslySetInnerHTML={{
                            __html: product.description.split('\n').map((item, index) => {
                                if (index === 0) {
                                    return `<p class="text-xl font-semibold mb-2">${item}</p>`;
                                } else if (item.includes(':')) {
                                    return `<p class="text-lg font-semibold mt-4 mb-2">${item}</p>`;
                                } else if (item.trim().startsWith('-')) {
                                    return `<li>${item.trim().substring(1)}</li>`;
                                } else {
                                    return `<p>${item}</p>`;
                                }
                            }).join('').replace(/(<li>.?<\/li>)+/g, function (match) {
                                return `<ul class="list-disc pl-5 mb-2">${match}</ul>`;
                            })
                        }}
                    />
                </div>

                <footer
                    className="fixed mt-12 border-[#695C5C]/30 shadow-[0_-4px_6px_-1px_rgba(0,0,0,0.05),0_-2px_4px_-1px_rgba(0,0,0,0.06)] bottom-0 bg-white p-4 right-0 left-0 z-50">
                    <div className="flex justify-between items-center mb-6">
                        {!isOutOfStock &&
                            <>
                                <span
                                    className="text-xl font-serif font-medium">{formatPrice(currentPrice * quantity)}</span>
                                <div className="flex items-center space-x-4">
                                    <button
                                        onClick={() => setQuantity(prev => Math.max(1, prev - 1))}
                                        className="w-8 h-8 flex items-center justify-center border border-[#E5E7EB] rounded-full"
                                        disabled={isOutOfStock || quantity <= 1}
                                        aria-label="Decrease quantity"
                                    >
                                        <Minus className="w-4 h-4 text-[#3B5345]" />
                                    </button>
                                    <span className="text-lg font-medium">{quantity}</span>
                                    <button
                                        onClick={() => setQuantity(prev => Math.min(prev + 1, maxQuantity))}
                                        className="w-8 h-8 flex items-center justify-center border border-[#E5E7EB] rounded-full"
                                        disabled={isOutOfStock || quantity >= maxQuantity}
                                        aria-label="Increase quantity"
                                    >
                                        <Plus className="w-4 h-4 text-[#3B5345]" />
                                    </button>
                                </div>
                            </>}
                    </div>

                    {/* Conditionally render the Add to Cart or Buy Now button based on stock status */}
                    {!isOutOfStock && (
                        isInCart() ? (
                            <Link
                                href="/cart"
                                className="w-full font-serif bg-[rgba(59,83,69,0.05)] text-[#3B5345] py-3 rounded-lg font-medium text-lg flex items-center justify-center transition duration-300 border border-[#3B5345]"
                            >
                                <svg className="mr-2" width="29" height="28" viewBox="0 0 29 28" fill="none"
                                     xmlns="http://www.w3.org/2000/svg">
                                    <path
                                        d="M9.50391 8.94834V7.81668C9.50391 5.19168 11.6156 2.61334 14.2406 2.36834C17.3672 2.06501 20.0039 4.52668 20.0039 7.59501V9.20501"
                                        stroke="#3B5345" strokeWidth="1.5" strokeMiterlimit="10" strokeLinecap="round"
                                        strokeLinejoin="round" />
                                    <path
                                        d="M11.2542 25.6666H18.2542C22.9442 25.6666 23.7842 23.7883 24.0292 21.5016L24.9042 14.5016C25.2192 11.6549 24.4025 9.33325 19.4209 9.33325H10.0875C5.10586 9.33325 4.28919 11.6549 4.60419 14.5016L5.47919 21.5016C5.72419 23.7883 6.56419 25.6666 11.2542 25.6666Z"
                                        stroke="#3B5345" strokeWidth="1.5" strokeMiterlimit="10" strokeLinecap="round"
                                        strokeLinejoin="round" />
                                    <path d="M18.8318 14.0001H18.8423" stroke="#3B5345" strokeWidth="2"
                                          strokeLinecap="round" strokeLinejoin="round" />
                                    <path d="M10.6638 14.0001H10.6743" stroke="#3B5345" strokeWidth="2"
                                          strokeLinecap="round" strokeLinejoin="round" />
                                </svg>
                                Buy Now
                            </Link>
                        ) : (
                            <button
                                onClick={handleAddToCart}
                                className="w-full font-serif bg-[#3B5345] text-white py-3 rounded-lg font-medium text-lg flex items-center justify-center transition duration-300"
                            >
                                <svg className="mr-2" width="29" height="28" viewBox="0 0 29 28" fill="none"
                                     xmlns="http://www.w3.org/2000/svg">
                                    <path
                                        d="M9.50391 8.94834V7.81668C9.50391 5.19168 11.6156 2.61334 14.2406 2.36834C17.3672 2.06501 20.0039 4.52668 20.0039 7.59501V9.20501"
                                        stroke="white" strokeWidth="1.5" strokeMiterlimit="10" strokeLinecap="round"
                                        strokeLinejoin="round" />
                                    <path
                                        d="M11.2542 25.6666H18.2542C22.9442 25.6666 23.7842 23.7883 24.0292 21.5016L24.9042 14.5016C25.2192 11.6549 24.4025 9.33325 19.4209 9.33325H10.0875C5.10586 9.33325 4.28919 11.6549 4.60419 14.5016L5.47919 21.5016C5.72419 23.7883 6.56419 25.6666 11.2542 25.6666Z"
                                        stroke="white" strokeWidth="1.5" strokeMiterlimit="10" strokeLinecap="round"
                                        strokeLinejoin="round" />
                                    <path d="M18.8318 14.0001H18.8423" stroke="white" strokeWidth="2"
                                          strokeLinecap="round" strokeLinejoin="round" />
                                    <path d="M10.6638 14.0001H10.6743" stroke="white" strokeWidth="2"
                                          strokeLinecap="round" strokeLinejoin="round" />
                                </svg>
                                Add To Cart
                            </button>
                        )
                    )}
                </footer>
            </div>
        </div>
    );
}
ProductModal:
'use client';

import React, { useState, useEffect, useCallback, useMemo } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { Minus, Plus, ShoppingCart } from 'lucide-react';
import { useNotification } from '@/components/NotificationContext';
import '@/components/NotificationStyles.css';
import Link from 'next/link';

const formatPrice = (price) => {
    if (price == null || price === Infinity) return 'N/A';
    const formattedPrice = price >= 10000 ? price.toLocaleString() : price.toString();
    return `${formattedPrice} IQD`;
};

const ProductModal = ({ isOpen, onClose, productData }) => {
    const [selectedSize, setSelectedSize] = useState(null);
    const [selectedColor, setSelectedColor] = useState(null);
    const [quantity, setQuantity] = useState(1);
    const [isInCart, setIsInCart] = useState(false);
    const { addNotification } = useNotification();

    const product = productData.product;

    // Compute maxQty based on selected size and/or color
    const maxQty = useMemo(() => {
        let sizeQty = selectedSize ? selectedSize.qty : Infinity;
        let colorQty = selectedColor ? selectedColor.qty : Infinity;

        // If both size and color are selected, take the minimum of both
        return Math.min(sizeQty, colorQty);
    }, [selectedSize, selectedColor]);

    // Adjust quantity if it exceeds maxQty or handle out of stock
    useEffect(() => {
        if (quantity > maxQty) {
            setQuantity(maxQty);
        }
        if (maxQty === 0) {
            setQuantity(0);
        } else if (quantity < 1 && maxQty > 0) {
            setQuantity(1);
        }
    }, [maxQty, quantity]);

    // Compute total price dynamically
    const totalPrice = useMemo(() => {
        // Assuming that price is based on size; adjust if based on color or variant
        return selectedSize ? parseFloat(selectedSize.price) * quantity : 0;
    }, [selectedSize, quantity]);

    // Check if the product is in the cart
    const checkIfInCart = useCallback(() => {
        try {
            const cart = JSON.parse(localStorage.getItem('cart')) || [];
            const isItemInCart = cart.some(
                (item) =>
                    item.product_id === product.id &&
                    item.size_id === selectedSize?.id &&
                    item.color_id === selectedColor?.id
            );
            setIsInCart(isItemInCart);
        } catch (error) {
            console.error('Error accessing localStorage:', error);
            setIsInCart(false);
        }
    }, [product.id, selectedSize, selectedColor]);

    // Set default selected size and color on product change
    useEffect(() => {
        if (product?.sizes?.length > 0) {
            setSelectedSize(product.sizes[0]);
        } else {
            setSelectedSize(null);
        }

        if (product?.colors?.length > 0) {
            setSelectedColor(product.colors[0]);
        } else {
            setSelectedColor(null);
        }
    }, [product]);

    // Check if the product is in the cart whenever selectedSize or selectedColor changes
    useEffect(() => {
        checkIfInCart();
    }, [selectedSize, selectedColor, checkIfInCart]);

    // Handle adding product to cart
    const handleAddToCart = useCallback(() => {
        if ((!selectedSize && product.has_size) || (!selectedColor && product.has_color)) {
            addNotification('error', 'Please select the required options');
            return;
        }

        if (maxQty === 0) {
            addNotification('error', 'Selected option is out of stock');
            return;
        }

        const cartItem = {
            product_id: product.id,
            size_id: selectedSize ? selectedSize.id : null,
            color_id: selectedColor ? selectedColor.id : null,
            qty: quantity,
            price: selectedSize ? selectedSize.price : product.price,
        };

        try {
            const cart = JSON.parse(localStorage.getItem('cart')) || [];
            const existingItemIndex = cart.findIndex(
                (item) =>
                    item.product_id === cartItem.product_id &&
                    item.size_id === cartItem.size_id &&
                    item.color_id === cartItem.color_id
            );

            if (existingItemIndex > -1) {
                const newQty = cart[existingItemIndex].qty + quantity;
                if (newQty > maxQty) {
                    addNotification('error', `Cannot add more than ${maxQty} items`);
                    return;
                }
                cart[existingItemIndex].qty = newQty;
            } else {
                if (quantity > maxQty) {
                    addNotification('error', `Cannot add more than ${maxQty} items`);
                    return;
                }
                cart.push(cartItem);
            }

            localStorage.setItem('cart', JSON.stringify(cart));
            setIsInCart(true);
            addNotification('success', 'Added to cart successfully');
        } catch (error) {
            console.error('Error updating cart:', error);
            addNotification('error', 'Failed to add to cart');
        }
    }, [product, selectedSize, selectedColor, quantity, addNotification, maxQty]);

    if (!isOpen || !product) return null;

    // Determine button disabled states
    const isDecreaseDisabled = (maxQty > 0 && quantity <= 1) || (maxQty === 0 && quantity === 0);
    const isIncreaseDisabled = quantity >= maxQty;

    return (
        <AnimatePresence>
            <motion.div
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                exit={{ opacity: 0 }}
                className="fixed inset-0 bg-black bg-opacity-30 flex items-end justify-center z-50"
                onClick={onClose}
                aria-modal="true"
                role="dialog"
            >
                <motion.div
                    initial={{ y: '100%' }}
                    animate={{ y: 0 }}
                    exit={{ y: '100%' }}
                    transition={{ type: 'spring', damping: 25, stiffness: 500 }}
                    className="bg-white rounded-t-3xl w-full p-6 relative"
                    onClick={(e) => e.stopPropagation()}
                >
                    <div className="w-9 h-1 bg-[#00003C] opacity-70 rounded-full mx-auto mb-6" />

                    <h2 className="text-xl mb-4 font-sans">{product.name}</h2>

                    {product.has_size && (
                        <div className="mb-4">
                            <label htmlFor="size-select" className="sr-only">
                                Select Size
                            </label>
                            <select
                                id="size-select"
                                value={selectedSize ? selectedSize.id : ''}
                                onChange={(e) =>
                                    setSelectedSize(
                                        product.sizes.find(
                                            (size) => size.id.toString() === e.target.value
                                        )
                                    )
                                }
                                className="w-44 p-2 border border-[rgba(105,92,92,0.5)] rounded-lg font-serif text-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                            >
                                <option value="" disabled>
                                    Select a Size
                                </option>
                                {product.sizes.map((size) => (
                                    <option key={size.id} value={size.id}>
                                        {size.name}
                                    </option>
                                ))}
                            </select>
                            {!selectedSize && (
                                <p className="text-[#C91C1C] text-xs mt-2 font-sans">
                                    Please choose Size
                                </p>
                            )}
                        </div>
                    )}

                    {product.has_color && product.colors && product.colors.length > 0 && (
                        <div className="mb-6">
                            <h3 className="text-xl font-medium mb-2 font-sans">Color</h3>
                            <div className="flex space-x-5 mb-2">
                                {product.colors.map((color) => (
                                    <button
                                        key={color.id}
                                        className={`w-20 h-20 rounded-full border-2 ${
                                            selectedColor && selectedColor.id === color.id
                                                ? 'border-[rgba(105,92,92,0.5)]'
                                                : 'border-transparent'
                                        } flex items-center justify-center focus:outline-none focus:ring-2 focus:ring-blue-500`}
                                        aria-label={`Select color ${color.name}`}
                                        onClick={() => setSelectedColor(color)}
                                    >
                                        <div
                                            className="w-15 h-15 rounded-full"
                                            style={{ backgroundColor: color.hex }}
                                        />
                                    </button>
                                ))}
                            </div>
                            <div className="flex justify-between px-2">
                                {product.colors.map((color) => (
                                    <span key={color.id} className="text-sm font-serif">
                                        {color.name}
                                    </span>
                                ))}
                            </div>
                            {!selectedColor && (
                                <p className="text-[#C91C1C] text-xs mt-2 font-sans">
                                    Please choose Color
                                </p>
                            )}
                        </div>
                    )}

                    {/* Display Out of Stock message */}
                    {maxQty === 0 && (
                        <div className="mb-4">
                            <p className="text-red-600 font-semibold text-center">
                                Out of Stock
                            </p>
                        </div>
                    )}

                    <div className="flex font-serif justify-between items-center mb-6">
                        <p className="text-lg font-medium">{formatPrice(totalPrice)}</p>
                        <div className="flex items-center space-x-4">
                            {/* Decrease Quantity Button */}
                            <button
                                className={`w-8 h-8 rounded-full border border-gray-300 flex items-center justify-center focus:outline-none focus:ring-2 focus:ring-blue-500 transition-opacity duration-300 ${
                                    isDecreaseDisabled
                                        ? 'opacity-50 cursor-not-allowed'
                                        : 'hover:bg-gray-100'
                                }`}
                                onClick={() => setQuantity((prev) => Math.max(prev - 1, maxQty === 0 ? 0 : 1))}
                                disabled={isDecreaseDisabled}
                                aria-label="Decrease quantity"
                            >
                                <Minus
                                    className="w-4 h-4 text-[#3B5345]"
                                    strokeWidth={isDecreaseDisabled ? 1 : 2} // Increase stroke when active
                                />
                            </button>

                            <span className="text-lg">{quantity}</span>

                            {/* Increase Quantity Button */}
                            <button
                                className={`w-8 h-8 rounded-full border border-gray-300 flex items-center justify-center focus:outline-none focus:ring-2 focus:ring-blue-500 transition-opacity duration-300 ${
                                    isIncreaseDisabled
                                        ? 'opacity-50 cursor-not-allowed'
                                        : 'hover:bg-gray-100'
                                }`}
                                onClick={() => setQuantity((prev) => Math.min(prev + 1, maxQty))}
                                disabled={isIncreaseDisabled}
                                aria-label="Increase quantity"
                            >
                                <Plus
                                    className="w-4 h-4 text-[#3B5345]"
                                    strokeWidth={isIncreaseDisabled ? 1 : 2} // Increase stroke when active
                                />
                            </button>
                        </div>
                    </div>

                    <div className="flex font-serif space-x-4">
                        {isInCart ? (
                            <Link
                                href="/cart"
                                prefetch={false}
                                className="flex-1 font-serif bg-[rgba(59,83,69,0.05)] text-[#3B5345] py-3 rounded-lg font-medium text-base md:text-lg flex items-center justify-center transition duration-300 border border-[#3B5345] hover:bg-[rgba(59,83,69,0.1)]"
                            >
                                <ShoppingCart className="mr-2" />
                                Buy Now
                            </Link>
                        ) : (
                            <button
                                className={`flex-1 ${
                                    (selectedSize || selectedColor)
                                        ? 'bg-[#3B5345] text-white hover:bg-[#2d4233]'
                                        : 'bg-gray-300 text-gray-500 cursor-not-allowed'
                                } py-3 rounded-lg font-medium text-base md:text-lg flex items-center justify-center transition duration-300`}
                                onClick={handleAddToCart}
                                disabled={
                                    (!selectedSize && product.has_size) ||
                                    (!selectedColor && product.has_color) ||
                                    maxQty === 0
                                }
                                aria-label="Add to cart"
                            >
                                <ShoppingCart className="mr-2" />
                                Add To Cart
                            </button>
                        )}
                        <button
                            className="flex-1 bg-gray-200 text-gray-800 py-3 rounded-lg font-medium text-base md:text-lg hover:bg-gray-300 transition duration-300"
                            onClick={onClose}
                            aria-label="Close modal"
                        >
                            Close
                        </button>
                    </div>
                </motion.div>
            </motion.div>
        </AnimatePresence>
    );
};

export default React.memo(ProductModal);