"use client";
import { useState, useEffect, useRef, useCallback } from "react";
import { Edit } from "lucide-react";
import api from "@/api/axios";
import { toast } from "sonner";
import CropImageModal from "@/components/CropImageModal";
import { getGuestUuid } from "@/utils/guestUuid";

const MONTHS = [
  "January", "February", "March", "April", "May", "June",
  "July", "August", "September", "October", "November", "December",
];

type MonthItem = {
  id: string;
  monthIndex: number;
  image: string | null;
  cropped_image: string | null;
};

function buildMonthGrid(year: number, monthIndex: number) {
  const firstDay = new Date(year, monthIndex, 1).getDay();
  const daysCount = new Date(year, monthIndex + 1, 0).getDate();
  const cells: Array<number | null> = [];

  for (let i = 0; i < firstDay; i++) cells.push(null);
  for (let d = 1; d <= daysCount; d++) cells.push(d);
  while (cells.length < 42) cells.push(null);

  const weeks: (number | null)[][] = [];
  for (let w = 0; w < 6; w++) {
    weeks.push(cells.slice(w * 7, w * 7 + 7));
  }
  return weeks;
}

interface MonthlyCalendarProps {
  removeImage: (imageId: string) => void;
  monthImages: any[];
  setMonthImages: (images: any[]) => void;
  selectedEffect: string;
  selectedSize: any;
  backgroundColor: string;
  sizes: any[];
  id: string;
  effects: Record<string, string>;
  isNewCalendar?: boolean;

  // ✅ NEW: parent will tell us if this image is uploading
  isUploadingImage?: (img: any) => boolean;
}

export default function MonthlyCalendar({
  removeImage,
  monthImages,
  setMonthImages,
  selectedEffect,
  selectedSize,
  backgroundColor,
  sizes,
  id,
  effects,
  isNewCalendar = false,
  isUploadingImage, // ✅ take it from props
}: MonthlyCalendarProps) {
  const [monthFiles, setMonthFiles] = useState<(File | null)[]>(
    new Array(12).fill(null)
  );
  const [internalMonthImages, setInternalMonthImages] = useState<(any | null)[]>(
    new Array(12).fill(null)
  );
  const [draggedIndex, setDraggedIndex] = useState<number | null>(null);
  const [draggedOverIndex, setDraggedOverIndex] = useState<number | null>(null);
  const [forceUpdate, setForceUpdate] = useState(0);
  const currentYear = new Date().getFullYear();
  const internalMonthImagesRef = useRef<(any | null)[]>(internalMonthImages);
  const dragStartTimeRef = useRef<number>(0);
  const isDraggingRef = useRef<boolean>(false);
  const touchStartPosRef = useRef<{ x: number; y: number } | null>(null);
  const dragThreshold = 10; // الحد الأدنى لحركة السحب بالبكسل
  const [isCropOpen, setIsCropOpen] = useState(false);
  const [cropFile, setCropFile] = useState<File | null>(null);
  const [cropPreparing, setCropPreparing] = useState(false);
  const [cropImageId, setCropImageId] = useState<number | string | null>(null);
  const [calendarQty, setCalendarQty] = useState(1);
  const [isAddingToCart, setIsAddingToCart] = useState(false);

  // ✅ helper: is this image uploading?
  const isImgUploading = useCallback(
    (img: any) => {
      if (!img) return false;
      // if parent didn't pass handler, fallback to uploadStatus
      if (typeof isUploadingImage === "function") return !!isUploadingImage(img);
      return img?.uploadStatus === "uploading" || img?.uploadStatus === "pending";
    },
    [isUploadingImage]
  );
  const getImgSrc = (img: any) => {
    return img?.cropped_image || img?.selected_crop_image || img?.image;
  };

  /*const bust = (url: string) => `${url}${url.includes("?") ? "&" : "?"}t=${Date.now()}`;*/
  const getImageUrl = (img: any) => {
    if (!img) return "";

    const url = getImgSrc(img);
    if (!url) return "";

    // blob/local preview لا نضيف عليه أي query
    if (url.startsWith("blob:")) {
      return url;
    }

    // نستخدم updated_at أو id حتى الرابط يبقى ثابت ولا يتغير مع كل render
    const version = img.updated_at || img.updatedAt || img.id;

    return `${url}${url.includes("?") ? "&" : "?"}v=${encodeURIComponent(version)}`;
  };

const urlToFile = async (url: string) => {
  const res = await fetch(url, { cache: "no-store" });
  const blob = await res.blob();
  const type = blob.type || "image/jpeg";
  const ext = type.includes("png") ? "png" : "jpg";
  return new File([blob], `image.${ext}`, { type });
};
const openCropModal = async (img: any) => {
  if (!img) return;

  if (isImgUploading(img)) {
    toast.info("يرجى الانتظار حتى اكتمال رفع الصورة");
    return;
  }

  // ما نقص صور temp
  if (!img.id || img.id.toString().startsWith("temp-")) {
    toast.info("يرجى الانتظار حتى يتم حفظ الصورة على السيرفر أولاً");
    return;
  }

  try {
    setCropPreparing(true);
    setCropImageId(img.id);

    const file = await urlToFile(img.image);
    setCropFile(file);
    setIsCropOpen(true);
  } catch (e) {
    console.error(e);
    toast.error("فشل تجهيز الصورة للقص");
  } finally {
    setCropPreparing(false);
  }
};

  // Sync with parent prop and maintain 12-element structure - FIXED
  useEffect(() => {
    console.log("Month images from parent:", monthImages);
    console.log("Is new calendar:", isNewCalendar);

    const newArray = new Array(12).fill(null);

    if (isNewCalendar) {
      console.log("New calendar mode - keeping empty array");
      setInternalMonthImages(newArray);
      internalMonthImagesRef.current = newArray;
      //setForceUpdate((prev) => prev + 1);
      return;
    }

    if (monthImages && monthImages.length > 0) {
      const sortedImages = [...monthImages].sort((a, b) => {
        const indexA = a.monthIndex !== undefined ? a.monthIndex : 0;
        const indexB = b.monthIndex !== undefined ? b.monthIndex : 0;
        return indexA - indexB;
      });

      sortedImages.forEach((item: any) => {
        if (item && item.id) {
          let index = item.monthIndex !== undefined ? item.monthIndex : -1;

          if (index < 0 || index >= 12 || newArray[index] !== null) {
            index = newArray.findIndex((slot) => slot === null);
          }

          if (index >= 0 && index < 12) {
            newArray[index] = {
              ...item,
              monthIndex: index,
            };
          }
        }
      });
    }

    console.log("Processed array for calendar:", newArray);
    setInternalMonthImages(newArray);
    internalMonthImagesRef.current = newArray;
    //setForceUpdate((prev) => prev + 1);
  }, [monthImages, isNewCalendar]);

  // Improved drag start handler with mouse events
  const handleMouseDown = (e: React.MouseEvent, index: number) => {
    const img = internalMonthImages[index];
    if (!img) return;

    // ✅ منع crop إذا عم يرفع
    if (isImgUploading(img)) {
      toast.info("يرجى الانتظار حتى اكتمال رفع الصورة");
      return;
    }

    dragStartTimeRef.current = Date.now();
    touchStartPosRef.current = { x: e.clientX, y: e.clientY };
    isDraggingRef.current = false;

    const startDrag = () => {
      if (isDraggingRef.current) return;
      isDraggingRef.current = true;
      setDraggedIndex(index);

      if (e.target instanceof HTMLElement) {
        e.target.draggable = true;
        const dragEvent = new DragEvent("dragstart", {
          dataTransfer: new DataTransfer(),
          bubbles: true,
          cancelable: true,
        });

        dragEvent.dataTransfer?.setData("text/plain", index.toString());
        e.target.dispatchEvent(dragEvent);
      }
    };

    const dragTimer = setTimeout(startDrag, 150);

    const onMouseMove = (moveEvent: MouseEvent) => {
      if (!touchStartPosRef.current) return;

      const deltaX = Math.abs(moveEvent.clientX - touchStartPosRef.current.x);
      const deltaY = Math.abs(moveEvent.clientY - touchStartPosRef.current.y);

      if (deltaX > dragThreshold || deltaY > dragThreshold) {
        clearTimeout(dragTimer);
        startDrag();
        window.removeEventListener("mousemove", onMouseMove);
      }
    };

    const onMouseUp = () => {
      clearTimeout(dragTimer);
      window.removeEventListener("mousemove", onMouseMove);
      window.removeEventListener("mouseup", onMouseUp);

      if (!isDraggingRef.current && Date.now() - dragStartTimeRef.current < 200) {
        handleCrop(img, index);
      }

      isDraggingRef.current = false;
      touchStartPosRef.current = null;
    };

    window.addEventListener("mousemove", onMouseMove);
    window.addEventListener("mouseup", onMouseUp);
  };

  // Improved touch handlers for mobile
  const handleTouchStart = (e: React.TouchEvent, index: number) => {
    const img = internalMonthImages[index];
    if (!img) return;

    // ✅ منع crop/drag إذا عم يرفع
    if (isImgUploading(img)) {
      toast.info("يرجى الانتظار حتى اكتمال رفع الصورة");
      return;
    }

    const touch = e.touches[0];
    touchStartPosRef.current = { x: touch.clientX, y: touch.clientY };
    dragStartTimeRef.current = Date.now();
    isDraggingRef.current = false;
    setDraggedIndex(index);

    e.preventDefault();
  };

  const handleTouchMove = (e: React.TouchEvent, index: number) => {
    if (!touchStartPosRef.current || !isDraggingRef.current) return;

    const touch = e.touches[0];
    const deltaX = Math.abs(touch.clientX - touchStartPosRef.current.x);
    const deltaY = Math.abs(touch.clientY - touchStartPosRef.current.y);

    if (!isDraggingRef.current && (deltaX > dragThreshold || deltaY > dragThreshold)) {
      isDraggingRef.current = true;
    }

    if (isDraggingRef.current) {
      const element = document.elementFromPoint(touch.clientX, touch.clientY);

      if (element) {
        const card = element.closest("[data-month-index]");
        if (card) {
          const newIndex = parseInt(card.getAttribute("data-month-index") || "-1");
          if (newIndex !== -1 && newIndex !== draggedIndex) {
            setDraggedOverIndex(newIndex);
          }
        }
      }
    }
  };

  const handleTouchEnd = (e: React.TouchEvent, index: number) => {
    if (touchStartPosRef.current && !isDraggingRef.current) {
      const touch = e.changedTouches[0];
      const deltaX = Math.abs(touch.clientX - touchStartPosRef.current.x);
      const deltaY = Math.abs(touch.clientY - touchStartPosRef.current.y);

      if (
        deltaX < dragThreshold &&
        deltaY < dragThreshold &&
        Date.now() - dragStartTimeRef.current < 200
      ) {
        const img = internalMonthImages[index];
        if (img) handleCrop(img, index);
      }
    }

    if (isDraggingRef.current && draggedIndex !== null && draggedOverIndex !== null) {
      performDragDrop(draggedIndex, draggedOverIndex);
    }

    setDraggedIndex(null);
    setDraggedOverIndex(null);
    isDraggingRef.current = false;
    touchStartPosRef.current = null;
  };

  // Drag and drop handlers - IMPROVED
  const handleDragStart = (e: React.DragEvent, index: number) => {
    const img = internalMonthImages[index];
    if (!img) {
      e.preventDefault();
      return;
    }

    // ✅ منع drag إذا عم يرفع
    if (isImgUploading(img)) {
      e.preventDefault();
      toast.info("يرجى الانتظار حتى اكتمال رفع الصورة");
      return;
    }

    console.log("Drag started from index:", index, "Image:", img);
    setDraggedIndex(index);
    e.dataTransfer.effectAllowed = "move";
    e.dataTransfer.setData("text/plain", index.toString());

    if (img.cropped_image || img.image) {
      const dragImage = document.createElement("div");
      dragImage.style.width = "100px";
      dragImage.style.height = "100px";
      dragImage.style.backgroundImage = `url(${img.cropped_image || img.image})`;
      dragImage.style.backgroundSize = "cover";
      dragImage.style.position = "absolute";
      dragImage.style.top = "-1000px";
      document.body.appendChild(dragImage);

      e.dataTransfer.setDragImage(dragImage, 50, 50);

      setTimeout(() => document.body.removeChild(dragImage), 0);
    }
  };

  const handleDragOver = (e: React.DragEvent, index: number) => {
    e.preventDefault();
    e.dataTransfer.dropEffect = "move";

    if (draggedIndex !== null && draggedIndex !== index) {
      setDraggedOverIndex(index);
    }
  };

  const handleDragLeave = () => {
    setDraggedOverIndex(null);
  };

  const handleDrop = (e: React.DragEvent, targetIndex: number) => {
    e.preventDefault();
    setDraggedOverIndex(null);

    const sourceIndexStr = e.dataTransfer.getData("text/plain");
    if (!sourceIndexStr) return;

    const sourceIndex = parseInt(sourceIndexStr);

    if (
      isNaN(sourceIndex) ||
      sourceIndex === targetIndex ||
      !internalMonthImages[sourceIndex]
    ) {
      return;
    }

    performDragDrop(sourceIndex, targetIndex);
  };

  const performDragDrop = (sourceIndex: number, targetIndex: number) => {
    console.log("Dropping from", sourceIndex, "to", targetIndex);

    const newImages = [...internalMonthImages];
    const newFiles = [...monthFiles];

    [newImages[sourceIndex], newImages[targetIndex]] = [
      newImages[targetIndex],
      newImages[sourceIndex],
    ];

    [newFiles[sourceIndex], newFiles[targetIndex]] = [
      newFiles[targetIndex],
      newFiles[sourceIndex],
    ];

    const updatedImages = newImages.map((item, idx) => {
      if (item) return { ...item, monthIndex: idx };
      return null;
    });

    setInternalMonthImages(updatedImages);
    internalMonthImagesRef.current = updatedImages;
    setMonthFiles(newFiles);
    //setForceUpdate((prev) => prev + 1);

    const filteredForParent = updatedImages
      .filter((item) => item !== null)
      .map((item: any) => ({
        id: item.id,
        image: item.image,
        cropped_image: item.cropped_image,
        monthIndex: item.monthIndex,
        product_id: item.product_id || id,
      }));

    setMonthImages(filteredForParent);
    /*sendReOrderData(updatedImages);*/
    sendReOrderData([
      updatedImages[sourceIndex],
      updatedImages[targetIndex],
    ]);

    setDraggedIndex(null);

    toast.success(`تم نقل الصورة من ${MONTHS[sourceIndex]} إلى ${MONTHS[targetIndex]}`);
  };

  const handleDragEnd = () => {
    setDraggedIndex(null);
    setDraggedOverIndex(null);
    isDraggingRef.current = false;
  };

  const sendReOrderData = async (imagesToUpdate: (any | null)[]) => {
    try {
      const guestUuid = getGuestUuid();

      const reOrderData = imagesToUpdate
          .filter(
              (item) =>
                  item !== null &&
                  item.id &&
                  !item.id.toString().startsWith("temp-")
          )
          .map((item: any) => ({
            image_id: item.id,
            sort_order: (item.monthIndex ?? 0) + 1,
            calendar_slot: MONTHS[item.monthIndex ?? 0],
            calendar_type: "monthly",
          }));

      if (reOrderData.length > 0) {
        await api.post(
            "account-images/re-order",
            {
              guest_uuid: guestUuid,
              images: reOrderData,
            },
            {
              headers: {
                ...(guestUuid ? { "X-Guest-Uuid": guestUuid } : {}),
              },
            }
        );
      }
    } catch (error) {
      console.error("Error saving re-order:", error);
      toast.error("فشل في حفظ الترتيب");
    }
  };

  const getCurrentImageCount = useCallback(() => {
    return internalMonthImages.filter((item) => item !== null).length;
  }, [internalMonthImages]);

  const handleReplaceImage = async (index: number, file: File | null) => {
    if (!file) return;

    const currentCount = getCurrentImageCount();
    const hasExistingImage = internalMonthImages[index] !== null;

    if (!hasExistingImage && currentCount >= 12) {
      toast.error("وصلت للحد المطلوب! لا يمكن إضافة أكثر من 12 صورة");
      return;
    }

    const url = URL.createObjectURL(file);
    const currentImages = [...internalMonthImages];
    const currentFiles = [...monthFiles];

    const tempId = `temp-${Date.now()}-${index}`;
    const newImage = {
      id: tempId,
      image: url,
      cropped_image: null,
      monthIndex: index,
      product_id: id.toString(),
      sort_order: index + 1,
      isTemp: true,
      uploadStatus: "uploading", // ✅ so overlay works even without parent
    };

    currentImages[index] = newImage;
    currentFiles[index] = file;

    setInternalMonthImages(currentImages);
    setMonthFiles(currentFiles);
    internalMonthImagesRef.current = currentImages;
    //setForceUpdate((prev) => prev + 1);

    const filteredForParent = currentImages
      .filter((item) => item !== null)
      .map((item: any) => ({ ...item }));
    setMonthImages(filteredForParent);

    const formData = new FormData();
    formData.append("image", file);
    formData.append("product_id", id.toString());
    formData.append("sort_order", (index + 1).toString());
    formData.append("month_index", index.toString());

// مهم لمنتج الرزنامة الشهرية
    formData.append("calendar_slot", MONTHS[index]);
    formData.append("calendar_type", "monthly");
    // ✅ Guest UUID للزائر
    const guestUuid = getGuestUuid();

    if (guestUuid) {
      formData.append("guest_uuid", guestUuid);
    }

    try {
      const response = await api.post("account-images/upload", formData, {
        headers: {
          "Content-Type": "multipart/form-data",
          "X-Guest-Uuid": guestUuid,
        },
      });

      if (response.data?.success) {
        const serverImg = response.data.data;

        const updatedImages = [...internalMonthImages];
        updatedImages[index] = {
          ...serverImg,
          monthIndex: index,
        };

        setInternalMonthImages(updatedImages);
        internalMonthImagesRef.current = updatedImages;
        //setForceUpdate((prev) => prev + 1);

        const updatedForParent = updatedImages
          .filter((item) => item !== null)
          .map((item: any) => ({ ...item }));
        setMonthImages(updatedForParent);

        toast.success("تم رفع الصورة بنجاح");
      }
    } catch (err: any) {
      console.error("Upload failed:", err);

      // ✅ mark failed (optional)
      const updatedImages = [...internalMonthImages];
      if (updatedImages[index]) updatedImages[index] = { ...updatedImages[index], uploadStatus: "failed" };
      setInternalMonthImages(updatedImages);
      internalMonthImagesRef.current = updatedImages;

      toast.error("فشل في رفع الصورة");
    }
  };

  const handleDeleteImage = async (index: number) => {
    const imgToDelete = internalMonthImages[index];
    if (!imgToDelete) return;

    // ✅ إذا عم يرفع، امنعي الحذف
    if (isImgUploading(imgToDelete)) {
      toast.info("يرجى الانتظار حتى اكتمال رفع الصورة");
      return;
    }
    // ✅ Guest UUID للزائر
    const guestUuid = getGuestUuid();
    if (imgToDelete.id && !imgToDelete.id.toString().startsWith("temp-")) {
      try {
        await api.post("account-images/delete", {
          product_id: id,
          images_ids: [imgToDelete.id],
          guest_uuid: guestUuid, // ✅ إرسال UUID مع طلب الحذف
        });
      } catch (error) {
        console.error("Failed to delete image from server:", error);
        toast.error("فشل في حذف الصورة من السيرفر");
        return;
      }
    }

    const newImgs = [...internalMonthImages];
    const newFiles = [...monthFiles];

    newImgs[index] = null;
    newFiles[index] = null;

    setInternalMonthImages(newImgs);
    setMonthFiles(newFiles);
    internalMonthImagesRef.current = newImgs;
    //setForceUpdate((prev) => prev + 1);

    const filteredForParent = newImgs
      .map((item, idx) => (item ? { ...item, monthIndex: idx } : null))
      .filter((item) => item !== null);

    setMonthImages(filteredForParent);

    /*if (imgToDelete.id && !imgToDelete.id.toString().startsWith("temp-") && removeImage) {
      removeImage(imgToDelete.id);
    }*/

    toast.success("تم حذف الصورة بنجاح");
  };

  const handleCrop = (img: any, index: number) => {
    if (!img) return;

    // ✅ منع crop أثناء الرفع
    if (isImgUploading(img)) {
      toast.info("يرجى الانتظار حتى اكتمال رفع الصورة");
      return;
    }
    openCropModal(img);
  };

  const handleAddToCart = async () => {
    const uploadedImages = internalMonthImages.filter((item) => item !== null);

    if (uploadedImages.length !== 12) {
      toast.error("يجب إضافة 12 صورة قبل الإضافة للسلة");
      return;
    }

    const hasUploading = internalMonthImages.some((img) => img && isImgUploading(img));

    if (hasUploading) {
      toast.info("يرجى الانتظار حتى اكتمال رفع جميع الصور");
      return;
    }

    const hasTempImages = internalMonthImages.some(
        (img) => img && (!img.id || img.id.toString().startsWith("temp-"))
    );

    if (hasTempImages) {
      toast.info("يرجى الانتظار حتى يتم حفظ جميع الصور على السيرفر");
      return;
    }

    try {
      setIsAddingToCart(true);

      const items = internalMonthImages
          .map((img: any, index) => {
            if (!img) return null;

            return {
              image_id: img.id,
              qty: calendarQty,
              calendar_slot: MONTHS[index],
              calendar_type: "monthly",
            };
          })
          .filter(Boolean);

      await api.post("cart/add", {
        product_id: Number(id),
        items,
      });

      toast.success("تمت إضافة الرزنامة إلى السلة");
    } catch (error: any) {
      console.error("Add to cart failed:", error);

      const message =
          error?.response?.data?.message ||
          error?.response?.data?.errors?.cart?.[0] ||
          "فشل إضافة الرزنامة إلى السلة";

      toast.error(message);
    } finally {
      setIsAddingToCart(false);
    }
  };

  const MonthCard = ({ month, index, img }: any) => {
    const weeks = buildMonthGrid(currentYear, index);
    const isDraggedOver = draggedOverIndex === index;
    const isBeingDragged = draggedIndex === index;
    /*const imageUrl = img ? bust(getImgSrc(img)) : "";*/
    const imageUrl = getImageUrl(img);
    const isUploading = isImgUploading(img);

    return (
      <div
        data-month-index={index}
        className={`relative bg-white border border-[#E2E2E2] shadow-sm p-3 flex flex-col transition-all overflow-hidden ${
          isDraggedOver ? "ring-2 ring-blue-400 ring-opacity-50 scale-105" : ""
        } ${isBeingDragged ? "opacity-50 scale-95" : ""}`}
        style={{
          backgroundColor,
          color: "#222",
          width: 245,
          transition: "transform 0.2s, opacity 0.2s",
        }}
        onDragOver={(e) => handleDragOver(e, index)}
        onDragLeave={handleDragLeave}
        onDrop={(e) => handleDrop(e, index)}
      >
        {/* زر الحذف */}
        {img && (
          <button
            onClick={(e) => {
              e.preventDefault();
              e.stopPropagation();
              handleDeleteImage(index);
            }}
            className="absolute top-2 right-2 z-20 w-8 h-8 bg-white/90 hover:bg-white rounded-full flex items-center justify-center text-gray-600 hover:text-red-500 transition-colors shadow-lg hover:shadow-xl"
            aria-label="Delete image"
          >
            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
            </svg>
          </button>
        )}

        <div className="w-full h-[160px] bg-gray-200 overflow-hidden relative p-0 border-0">
          {img ? (
            <div
              className="w-full h-full relative"
              draggable="true"
              onMouseDown={(e) => handleMouseDown(e, index)}
              onDragStart={(e) => handleDragStart(e, index)}
              onDragEnd={handleDragEnd}
              onTouchStart={(e) => handleTouchStart(e, index)}
              onTouchMove={(e) => handleTouchMove(e, index)}
              onTouchEnd={(e) => handleTouchEnd(e, index)}
              style={{ cursor: isUploading ? "not-allowed" : "grab" }}
            >
              <img
                src={imageUrl}
                alt={`${month}-${currentYear}`}
                className="w-full h-full object-cover select-none"
                style={{
                  filter: effects[selectedEffect as keyof typeof effects],
                  pointerEvents: "none",
                  userSelect: "none",
                }}
              />

              {/* ✅ LOADING OVERLAY */}
              {isUploading && (
                <div className="absolute inset-0 z-30 flex items-center justify-center rounded-lg">
                  <div className="bg-black/35 backdrop-blur-[1px] w-full h-full absolute inset-0 rounded-lg" />
                  <div className="relative z-40 text-center">
                    <div className="w-8 h-8 border-2 border-white border-t-transparent rounded-full animate-spin mx-auto"></div>
                    <p className="text-sm text-white mt-2">جاري التحميل...</p>
                  </div>
                </div>
              )}

              {/* Drag indicator */}
              <div className="absolute top-2 left-2 bg-black/50 text-white text-xs px-2 py-1 rounded select-none">
                اسحبني 🖱️
              </div>

              {/* زر التعديل */}
              <div className="absolute bottom-2 right-2 flex gap-2">
                <button
                  onClick={(e) => {
                    e.preventDefault();
                    e.stopPropagation();
                    handleCrop(img, index);
                  }}
                  className="p-1 bg-white/80 hover:bg-white rounded text-gray-800 hover:text-blue-500 transition-colors shadow-sm select-none"
                  aria-label="Edit image"
                >
                  <Edit size={16} />
                </button>
              </div>
            </div>
          ) : (
            <div
              className="w-full h-full flex items-center justify-center text-gray-400 cursor-pointer hover:bg-gray-300 transition-colors select-none"
              onClick={() => {
                const currentCount = getCurrentImageCount();
                if (currentCount >= 12) {
                  toast.error("وصلت للحد المطلوب! لا يمكن إضافة أكثر من 12 صورة");
                  return;
                }

                const fileInput = document.createElement("input");
                fileInput.type = "file";
                fileInput.accept = "image/*";
                fileInput.onchange = (e) => {
                  const file = (e.target as HTMLInputElement).files?.[0];
                  if (file) handleReplaceImage(index, file);
                };
                fileInput.click();
              }}
            >
              + إضافة صورة
            </div>
          )}
        </div>

        {/* العنوان */}
        <div className="px-4 pt-4 flex flex-col gap-2 self-end">
          <div className="flex">
            <h3 className="text-lg font-medium mt-0.5 ml-1">{month}</h3>
            <h2 className="text-2xl font-semibold leading-none">
              {String(index + 1).padStart(2, "0")}
            </h2>
          </div>
          <div className="w-18 h-[2px] bg-gray-800 mx-auto -mt-2 ml-3 mb-3" />
        </div>

        {/* جدول الأيام */}
        <div className="px-4 pb-3">
          <div className="grid grid-cols-7 gap-1 text-[11px] text-center text-gray-600 mb-2 font-semibold">
            {["SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT"].map((d) => (
              <div key={d} className={`uppercase ${d === "FRI" ? "text-[#3EB489]" : ""}`}>
                {d}
              </div>
            ))}
          </div>

          <div className="grid grid-cols-7 gap-1 text-center text-sm">
            {weeks.flat().map((day, i) => {
              const col = i % 7;
              const isFri = col === 5;
              return (
                <div
                  key={i}
                  className={`flex items-center justify-center text-xs ${
                    day ? (isFri ? "text-[#3EB489]" : "text-gray-800") : "text-gray-300"
                  }`}
                >
                  {day ?? ""}
                </div>
              );
            })}
          </div>
        </div>

        {/* أسفل البطاقة */}
        <div className="absolute bottom-2 left-3 right-3 flex items-center justify-between text-xs text-gray-500">
          <span className="font-semibold text-[16px] text-black">{currentYear}</span>
        </div>
      </div>
    );
  };

  return (
      <section>
      {cropPreparing && (
  <div className="fixed inset-0 z-[60] bg-black/50 flex items-center justify-center">
    <div className="bg-white rounded-xl p-4">
      <p className="text-sm">جاري تجهيز الصورة...</p>
    </div>
  </div>
)}

<CropImageModal
  isOpen={isCropOpen}
  file={cropFile}
  imageId={cropImageId}
  productId={id}
  onCancel={() => {
    setIsCropOpen(false);
    setCropFile(null);
    setCropImageId(null);
  }}
  onClose={() => {
    setIsCropOpen(false);
    setCropFile(null);
    setCropImageId(null);
  }}
  onSaved={(serverImg: any) => {
    // ✅ تحديث فوري للكروت بعد crop/save
    const sid = Number(serverImg?.id);

    const updated = internalMonthImagesRef.current.map((it: any | null) => {
      if (!it) return null;
      if (Number(it.id) === sid) return { ...it, ...serverImg };
      return it;
    });

    setInternalMonthImages(updated);
    internalMonthImagesRef.current = updated;
    setForceUpdate((p) => p + 1);

    const updatedForParent = updated
      .filter((x) => x !== null)
      .map((x: any) => ({ ...x }));
    setMonthImages(updatedForParent);

    setIsCropOpen(false);
    setCropFile(null);
    setCropImageId(null);

    toast.success("تم حفظ القص بنجاح");
  }}
/>
      {/* عداد الصور */}
      <div className="text-center mb-4 p-3 bg-green-50 rounded-lg max-w-2xl mx-auto">
        <p className="text-sm text-green-800">
          📸 عدد الصور: <strong>{getCurrentImageCount()}</strong> / 12
          {getCurrentImageCount() === 12 && (
            <span className="text-green-600 mr-2">✓ اكتمل التقويم!</span>
          )}
        </p>
      </div>

      {/* تعليمات السحب */}
      <div className="text-center mb-4 p-3 bg-blue-50 rounded-lg max-w-2xl mx-auto">
        <p className="text-sm text-blue-800">
          💡 <strong>تعليمات:</strong> اضغط مطولاً على الصورة واسحبها لوضعها في شهر مختلف
          <br />
          <span className="text-xs">(يعمل على الهواتف وأجهزة الكمبيوتر)</span>
        </p>
      </div>

      {/* شبكة الأشهر */}
      <div className="max-w-6xl w-full mx-auto mb-8">
        <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-6">
          {MONTHS.map((month, index) => {
            const img = internalMonthImages[index];
            return (
                <MonthCard
                    key={`${month}-${index}-${img?.id || "empty"}`}
                    month={month}
                    index={index}
                    img={img}
                />
            );
          })}
        </div>
      </div>

      {/* الكمية والإضافة للسلة */}
      <div className="max-w-2xl mx-auto mb-16 bg-white border border-gray-200 rounded-2xl shadow-sm p-5">
        <div className="flex flex-col sm:flex-row items-center justify-between gap-4">
          <div className="text-center sm:text-right">
            <p className="font-semibold text-gray-800">كمية الرزنامة</p>
            <p className="text-sm text-gray-500">
              السعر يحسب حسب عدد الرزنامات وليس عدد الصور
            </p>
          </div>

          <div className="flex items-center gap-3">
            <button
                type="button"
                onClick={() => setCalendarQty((q) => Math.max(1, q - 1))}
                disabled={calendarQty <= 1 || isAddingToCart}
                className="w-10 h-10 rounded-full bg-gray-100 hover:bg-gray-200 disabled:opacity-50 flex items-center justify-center text-xl font-bold"
            >
              -
            </button>

            <span className="min-w-12 text-center text-xl font-bold text-gray-900">
        {calendarQty}
      </span>

            <button
                type="button"
                onClick={() => setCalendarQty((q) => q + 1)}
                disabled={isAddingToCart}
                className="w-10 h-10 rounded-full bg-pink-500 hover:bg-pink-600 text-white flex items-center justify-center text-xl font-bold"
            >
              +
            </button>
          </div>
        </div>

        <button
            type="button"
            onClick={handleAddToCart}
            disabled={
                isAddingToCart ||
                getCurrentImageCount() !== 12 ||
                internalMonthImages.some((img) => img && isImgUploading(img))
            }
            className="mt-5 w-full h-12 rounded-xl bg-pink-500 hover:bg-pink-600 disabled:bg-gray-300 disabled:cursor-not-allowed text-white font-bold transition-colors"
        >
          {isAddingToCart ? "جاري الإضافة..." : "إضافة للسلة"}
        </button>
      </div>
    </section>
  );
}
