/* eslint-disable @typescript-eslint/no-explicit-any */
"use client";

import React, { useEffect, useRef, useState } from "react";
import Link from "next/link";
import { useRouter, useSearchParams } from "next/navigation";
import apiClient from "@/lib/apiClient";
import {
  ArrowUpIcon,
  CrossIcon,
  DownloadIcon,
  HeartIcon,
  ImageIcon,
  PlayIcon,
  RectangleHorizontal,
  RectangleVertical,
  Square,
  StarsIcon,
  UploadIcon,
  VideoIcon,
  XIcon,
} from "lucide-react";
import "../../../styles/creative-page.css";
import { ChevronLeft, ChevronRight } from "react-feather";
import VersionsGallery from "@/components/versions/VersionsGallery";
import { Version } from "@/types/versions";
import LimitModal from "@/components/show-dailog/LimitModal";
import { useToast } from "@/components/ui/ToastContext";
import { DEFAULT_MAX_ATTEMPTS, makeMessage, Message, pollVideoStatus, VoiceInputButton } from "@/components/generate-creative";

const API_BASE_URL =
  process.env.NEXT_PUBLIC_API_BASE_URL || "http://localhost:4000";

// type GeneratedMedia = {
//   id: number;
//   partner_id: number | null;
//   type: string; // "IMAGE" | "VIDEO"
//   prompt: string;
//   provider: string;
//   s3_key?: string | null;
//   external_url?: string | null;
//   job_id?: string | null;
//   parent_id?: number | null;
//   version?: number;
//   created_at: string;
//   updated_at: string;
// };

export default function EditCreativeImagePage() {
  const searchParams = useSearchParams();
  const [media, setMedia] = useState<Version | null>(null);
  const [loading, setLoading] = useState<boolean>(false);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // Local UI state for bottom "search" strip (same as generate-creative)
  const [previewSrc, setPreviewSrc] = useState<string | null>(null);
  const [selectedAspect, setSelectedAspect] = useState<string>("2:3");
  const [mode, setMode] = useState<"Image" | "Video">("Image");
  const [showPresets, setShowPresets] = useState<boolean>(false);
  const [promptMessage, setPromptMessage] = useState<string>("");
  const [popoverOpen, setPopoverOpen] = useState<boolean>(false);
  const fileInputRef = useRef<HTMLInputElement | null>(null);
  const popoverRef = useRef<HTMLDivElement | null>(null);
  const popoverToggleRef = useRef<HTMLButtonElement | null>(null);
  const [editing, setEditing] = useState<boolean>(false);
  // const [editMessage, setEditMessage] = useState<string | null>(null);
  const [imageSrc, setImageSrc] = useState<string>("");
  const [versions, setVersions] = useState<Version[]>([]);
  const [currentVersionIndex, setCurrentVersionIndex] = useState<number>(0);
  const [isTransitioning, setIsTransitioning] = useState<boolean>(false);
  const [quota, setQuota] = useState<any>(null);
  // const [selectedVersion, setSelectedVersion] = useState<Version | null>(null);
  // const [isLimitReached, setIsLimitReached] = useState(false);
  const [showLimitModal, setShowLimitModal] = useState<boolean>(false);
  const router = useRouter();
  const [isLiked, setIsLiked] = useState(false);
  const [showExceedLimitModal, setShowExceedLimitModal] = useState<boolean>(false);
  const [makingVideo, setMakingVideo] = useState<boolean>(false);
  const [isChatMode, setIsChatMode] = useState<boolean>(false);
  const [messages, setMessages] = useState<Message[]>([]);
  const [showVideoDialog, setShowVideoDialog] = useState(false);
  const [pendingMediaId, setPendingMediaId] = useState<number | null>(null);
  const [videoSrc, setVideoSrc] = useState<string | null>(null);

  const showToast = useToast();

  const id = searchParams.get("id");

  useEffect(() => {
    if (!id) return;

    let cancelled = false;

    async function load() {
      try {
        setLoading(true);
        setError(null);

        const res = await apiClient.get("/image/generated-media", {
          params: { id },
        });

        if (cancelled) return;

        if (res.data?.success && Array.isArray(res.data.data)) {
          const allVersions = res.data.data as Version[];

          const first =
            allVersions.find((v) => v.id === Number(id)) || allVersions[0];

          if (!first) {
            setError("Creative not found.");
          } else {
            setMedia(first);
            setVersions(allVersions);
          }
        } else {
          setError("Failed to load creative.");
        }
      } catch (e: any) {
        if (cancelled) return;
        setError("Failed to load creative. Please try again.");
      } finally {
        if (!cancelled) setLoading(false);
      }
    }

    load();

    return () => {
      cancelled = true;
    };
  }, [id]); // ✅ ONLY primitive dependency


  // Load the image with authentication if needed
  useEffect(() => {
    if (!media) return;

    let blobUrl: string | null = null;

    const loadImage = async () => {
      try {
        // console.log("Loading image for media:", media);

        // Priority 1: Use external_url if available (S3 signed URL)
        if (media.external_url) {
          console.log("Using external_url:", media.external_url);
          setImageSrc(media.external_url);
          return;
        }

        // Priority 2: Use s3_key to fetch via thumbnail endpoint
        if (media.s3_key) {
          console.log(
            "Fetching via thumbnail endpoint for s3_key:",
            media.s3_key
          );
          const url = `${API_BASE_URL}/image/generated-media/${media.id}/thumbnail`;
          const token = localStorage.getItem("access_token");

          const response = await fetch(url, {
            headers: {
              Authorization: `Bearer ${token}`,
            },
          });

          if (response.ok) {
            const blob = await response.blob();
            blobUrl = URL.createObjectURL(blob);
            console.log("Created blob URL:", blobUrl);
            setImageSrc(blobUrl);
          } else {
            console.error(
              "Failed to load image:",
              response.status,
              await response.text()
            );
            setImageSrc("/assets/img/only-icon-photo.svg");
          }
          return;
        }

        // Fallback: placeholder
        console.log("No image source available, using placeholder");
        setImageSrc("/assets/img/only-icon-photo.svg");
      } catch (error) {
        console.error("Error loading image:", error);
        setImageSrc("/assets/img/only-icon-photo.svg");
      }
    };

    loadImage();

    // Cleanup blob URL when component unmounts or media changes
    return () => {
      if (blobUrl) {
        console.log("Cleaning up blob URL:", blobUrl);
        URL.revokeObjectURL(blobUrl);
      }
    };
  }, [media]);

  useEffect(() => {
    function onDocumentClick(e: MouseEvent) {
      if (!popoverOpen) return;
      const target = e.target as Node | null;
      if (!target) return;

      if (
        (popoverRef.current && popoverRef.current.contains(target)) ||
        (popoverToggleRef.current && popoverToggleRef.current.contains(target))
      ) {
        return;
      }
      closePopover();
    }

    function onDocumentKey(e: KeyboardEvent) {
      if (e.key === "Escape") closePopover();
    }

    document.addEventListener("click", onDocumentClick);
    document.addEventListener("keydown", onDocumentKey);
    return () => {
      document.removeEventListener("click", onDocumentClick);
      document.removeEventListener("keydown", onDocumentKey);
    };
  }, [popoverOpen]);

  // Handlers for bottom strip
  function handlePreviewImage(e: React.ChangeEvent<HTMLInputElement>) {
    const file = e.target.files?.[0];
    if (!file) return;
    const url = URL.createObjectURL(file);
    setPreviewSrc(url);
  }

  function removeImg() {
    setPreviewSrc(null);
    if (fileInputRef.current) fileInputRef.current.value = "";
  }

  function handleAspect(ratio: string) {
    setSelectedAspect(ratio);
  }

  function togglePopover() {
    setPopoverOpen((s) => !s);
  }

  function closePopover() {
    setPopoverOpen(false);
  }

  function togglePresets() {
    setShowPresets((s) => !s);
  }

  async function handleSend() {
    console.log({
      media,
    });
    const prompt = promptMessage.trim();
    if (!prompt || !media) return;
    setEditing(true);

    try {
      // Use the versioning endpoint - it uses the existing media's s3_key
      // No need to upload the image again, just send the new prompt
      const form = new FormData();
      form.append("prompt", prompt);

      const token = localStorage.getItem("access_token");
      const resp = await fetch(
        `${API_BASE_URL}/image/generated-media/${media.id}/edit`,
        {
          method: "POST",
          headers: {
            Authorization: `Bearer ${token}`,
          },
          body: form,
        }
      );

      if (!resp.ok) {
        const txt = await resp.text();
        throw new Error(`Image edit API error: ${resp.status} ${txt}`);
      }

      const payload = await resp.json();
      console.log("Edit response:", payload);

      if (payload?.success) {
        const newVersion = payload?.data;
        const imageUrl = newVersion?.imageUrl || newVersion?.external_url;

        if (imageUrl) {
          // Show the newly edited image in the preview area
          setImageSrc(imageUrl);
        }

        // Use versions from the edit API response directly (no need for separate call)
        if (Array.isArray(payload?.versions) && payload.versions.length > 0) {
          const updatedVersions = payload.versions as Version[];
          console.log("Updated versions from edit response:", updatedVersions);
          setVersions(updatedVersions);

          // Set the newest version (first in array as they're ordered DESC) as the current media
          const newestVersion = updatedVersions[0];
          if (newestVersion) {
            setMedia(newestVersion);
            setCurrentVersionIndex(0); // Reset to show the newest version
          }
        }
      } else {
        // setEditMessage("Failed to create new version. Please try again.");
      }
    } catch (err: any) {
      // eslint-disable-next-line no-console
      console.error("Image edit error", err);
      // setEditMessage(
      //   err?.message || "Something went wrong while editing the image."
      // );
    } finally {
      setEditing(false);
    }
  }

  function handleKeyDown(e: React.KeyboardEvent<HTMLInputElement>) {
    if (e.key === "Enter" && !e.shiftKey) {
      e.preventDefault();
      handleSend();
    }
  }
  const handleVersionSelect = (version: Version): void => {
    // setSelectedVersion(version);
    console.log("Selected version:", version);

    // Update the main image display
    if (version.external_url) {
      setImageSrc(version.external_url);
    }
    setMedia(version);

    // Update the current version index
    const index = versions.findIndex((v) => v.id === version.id);
    if (index !== -1) {
      setCurrentVersionIndex(index);
    }
  };

  const handlePreviousVersion = () => {
    if (versions.length === 0 || isTransitioning) return;

    setIsTransitioning(true);

    setTimeout(() => {
      const newIndex =
        currentVersionIndex > 0 ? currentVersionIndex - 1 : versions.length - 1;
      setCurrentVersionIndex(newIndex);
      const version = versions[newIndex];
      if (version.external_url) {
        setImageSrc(version.external_url);
      }
      setMedia(version);

      setTimeout(() => {
        setIsTransitioning(false);
      }, 50);
    }, 200);
  };

  const handleNextVersion = () => {
    if (versions.length === 0 || isTransitioning) return;

    setIsTransitioning(true);

    setTimeout(() => {
      const newIndex =
        currentVersionIndex < versions.length - 1 ? currentVersionIndex + 1 : 0;
      setCurrentVersionIndex(newIndex);
      const version = versions[newIndex];
      if (version.external_url) {
        setImageSrc(version.external_url);
      }
      setMedia(version);

      setTimeout(() => {
        setIsTransitioning(false);
      }, 50);
    }, 200);
  };
  function closeLimitModal() {
    setShowLimitModal(false);
    setShowExceedLimitModal(false);
  }
  const handleUpgrade = () => {
    router.push("/pricing");
  };

  const handleCopyLink = async () => {
    const imageUrl = imageSrc || media?.external_url || "";
    if (!imageUrl) {
      showToast("No image link available");
      return;
    }

    try {
      await navigator.clipboard.writeText(imageUrl);
      showToast("Link copied");
    } catch (error) {
      console.error("Failed to copy link:", error);
      showToast("Failed to copy link");
    }
  };

  useEffect(() => {
    const fetchQuotaStatus = async () => {
      try {
        setError(null);

        const { data } = await apiClient.get("/quota/status");

        const quotaData = data.data;

        setQuota(quotaData);
        if (quotaData.close_to_limit) {
          setTimeout(() => {
            //  console.log("3 time used ");
            setShowExceedLimitModal(true);
          }, 1000);
        }
        // if (quotaData.remaining <= 0) {
        //   setIsLimitReached(true);
        // } else {
        //   setIsLimitReached(false);
        // }
        // Show modal when used equals or exceeds limit
        if (quotaData.used >= quotaData.limit) {
          // console.log("Quota limit reached, showing modal");
          setTimeout(() => {
            setShowLimitModal(true);
          }, 1000);
        }
      } catch (err) {
        console.error("Failed to fetch quota status", err);
        setError("Unable to fetch quota status");
      }
    };
    fetchQuotaStatus();
  }, [versions]);
  function handleVoiceTranscript(transcript: string) {
    // Append the voice transcript to the existing prompt
    setPromptMessage((prev) => {
      const separator = prev.trim() ? " " : "";
      return prev + separator + transcript;
    });
  }

  // Sync isLiked state with media.is_favorite
  useEffect(() => {
    if (media) {
      setIsLiked(media.is_favorite ?? false);
    }
  }, [media]);

  // Handle like/unlike toggle with API call
  const handleLikeToggle = async () => {
    if (!media) return;

    const newLikedState = !isLiked;
    const previousLikedState = isLiked;

    // Optimistic UI update
    setIsLiked(newLikedState);

    try {
      const response = await apiClient.patch(
        `/image/generated-media/${media.id}/favorite`,
        { is_favorite: newLikedState }
      );

      if (response.data?.success) {
        setMedia((prev) => prev ? { ...prev, is_favorite: newLikedState } : prev);
        showToast(newLikedState ? "Added to favorites" : "Removed from favorites");
      } else {
        // Revert on failure
        setIsLiked(previousLikedState);
        showToast("Failed to update favorite status");
      }
    } catch (error) {
      console.error("Failed to toggle favorite:", error);
      // Revert on error
      setIsLiked(previousLikedState);
      showToast("Failed to update favorite status");
    }
  };
  function pushMessage(msg: Message) {
    setMessages((prev) => [...prev, msg]);
  }

  const handleMakeVideo = async (mediaId: number) => {
    console.log(mediaId, "----media id ----------")
    const prompt = promptMessage.trim();
    if (!prompt) {
      showToast("Please enter a prompt to continue");
      return;
    }

    setMakingVideo(true);
    try {
      const token = localStorage.getItem("access_token");

      const resp = await fetch(
        `${API_BASE_URL}/video/image-to-video/${mediaId}`,
        {
          method: "POST",
          headers: {
            Authorization: `Bearer ${token}`,
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            image_id: mediaId,
            prompt,
            duration: 5,
            guidance_scale: 0.5,
          }),
        }
      );
      console.log(resp, '------this is the response --');
      if (!resp.ok) {
        throw new Error(await resp.text());
      }
      const data = await resp.json();
      console.log(data, 'thisis is the data ');
      const generationVideoId =
        data?.data?.VideoId ?? data?.VideoId;

      if (!generationVideoId) {
        throw new Error("VideoId not returned");
      }

      showToast("Video generation started! Processing...");

      // Poll for video status to get the actual video URL
      const statusPayload = await pollVideoStatus(Number(generationVideoId), {
        maxAttempts: DEFAULT_MAX_ATTEMPTS,
      });

      const videoUrl = statusPayload?.dbData?.external_url;

      if (videoUrl) {
        setVideoSrc(videoUrl);
        showToast("Video generated successfully!");
      } else {
        throw new Error("Video URL not available");
      }

    } catch (err: any) {
      pushMessage(
        makeMessage("bot", { text: err.message || "Video failed" })
      );
    } finally {
      setMakingVideo(false);
    }

  };



  return (
    <div className="pcoded-main-container bg-white">
      <div className="pcoded-content generate-page-content px-0 bg-white">
        <section className="generate-section w-100 m-0 bg-white">
          <div className="generate-section-area w-100 m-0">
            {/* Header row, matches PHP layout */}
            <div className="row align-items-center">
              <div className="col-xxl-12 col-xl-12 col-lg-12 col-md-12 col-sm-12 col-12 mb-md-0 mb-2 d-flex align-items-center gap-1">
                <Link
                  href="/ai-library"
                  className="hover-bg-btn mb-0"
                  aria-label="Back to AI Library"
                >
                  <svg width="18" height="18" viewBox="0 0 24 24" fill="none">
                    <path
                      d="M15 18L9 12L15 6"
                      stroke="#374151"
                      strokeWidth="2"
                      strokeLinecap="round"
                      strokeLinejoin="round"
                    />
                  </svg>
                </Link>
                <div>
                  <h3 className="subHeading mb-0">Edit Creative</h3>
                </div>
              </div>
            </div>

            {/* Main content row – carousel + options + versions grid */}
            <div className="row mt-3 mb-5 library-svg">
              <div className="col-12 col-md-12 col-lg-9 col-xl-8 col-xxl-8 mx-auto">
                <div
                  className=""
                  style={{
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "center",
                    gap: 30,
                  }}
                >
                  {error && !loading && (
                    <div className="library-error-state">{error}</div>
                  )}
                  {!loading && !error && (
                    <>
                      <div
                        hidden={isLoading || versions.length <= 1 || !!videoSrc}
                        style={{
                          background: "#51667b",
                          padding: 4,
                          borderRadius: 8,
                          cursor: "pointer",
                        }}
                        onClick={handlePreviousVersion}
                        role="button"
                        aria-label="Previous version"
                      >
                        <ChevronLeft stroke="white" />
                      </div>
                      <div
                        className="imagine-post imagineImgDiv w-max"
                        style={{ position: "relative" }}
                      >
                        {(isLoading || editing) && (
                          <div
                            className="image-skeleton"
                            style={{
                              width: "100%",
                              height: 400,
                              borderRadius: "12px",
                              background: "linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%)",
                              backgroundSize: "200% 100%",
                              animation: "shimmer 1.5s infinite",
                            }}
                          />
                        )}
                        {videoSrc ? (
                          <video
                            src={videoSrc}
                            controls
                            autoPlay
                            loop
                            className="rounded-3 m-0 brick-image"
                            style={{ height: 400 }}
                          />
                        ) : (
                          <img
                            className="rounded-3 m-0 brick-image"
                            style={{ height: 400 }}
                            src={previewSrc || imageSrc || "/assets/img/only-icon-photo.svg"}
                            alt={media?.prompt || "Selected creative"}
                            onLoad={() => setIsLoading(false)}
                            onError={() => setIsLoading(false)}
                          />
                        )}


                      </div>
                      <div
                        hidden={isLoading || versions.length <= 1 || !!videoSrc}
                        style={{
                          background: "#51667b",
                          padding: 4,
                          borderRadius: 8,
                          cursor: "pointer",
                        }}
                        onClick={handleNextVersion}
                        role="button"
                        aria-label="Next version"
                      >
                        <ChevronRight stroke="white" />
                      </div>
                    </>
                  )}
                </div>
                {editing && (
                  <div
                    style={{
                      display: "flex",
                      marginTop: 12,
                      textAlign: "center",
                      fontSize: 14,
                      color: "#6b7280",
                      justifySelf: "center",
                    }}
                  >
                    Generating new version...
                  </div>
                )}
              </div>
            </div>

            {/* Bottom prompt strip – reuse generate-creative search UI - Hide when video is shown */}
            {!videoSrc && (
            <div className="bg-white py-2 py-md-3 px-2 m-0">
              <div className="row align-items-center justify-content-center g-md-3 g-2 m-0">
                <div className="col-xxl-10 col-xl-10 col-lg-10 col-md-12 col-sm-12 col-12 m-0">
                  <div className="row mb-3">
                    <div className="col-12 col-md-12 col-lg-12 col-xl-12 col-xxl-12">
                      <div className="d-flex flex-wrap justify-content-between align-items-start gap-2 gap-md-3 m-0">
                        <div className="d-flex justify-content-start align-items-center gap-2 p-0 m-0">
                          <button
                            type="button"
                            className={`border rounded-3 p-2 m-0 bg-white ${isLiked ? "border-danger" : ""
                              }`}
                            style={{
                              height: 40,
                              width: 40,
                              display: "flex",
                              alignItems: "center",
                              justifyContent: "center",
                            }}
                            onClick={handleLikeToggle}
                          >
                            <HeartIcon
                              size={18}
                              color={isLiked ? "#dc3545" : "#6c757d"} // red / gray
                              fill={isLiked ? "#dc3545" : "none"}
                            />
                          </button>

                          <Link
                            href={media?.download_url || media?.external_url || imageSrc || ""}
                            download={media?.download_url || media?.external_url || imageSrc || undefined}
                            type="button"
                            className="border rounded-3 p-2 m-0 bg-white"
                            style={{
                              height: 40,
                              width: 40,
                              display: "flex",
                              alignItems: "center",
                              justifyContent: "center",
                            }}
                          >
                            <DownloadIcon size={18} />
                          </Link>
                          <button
                            type="button"
                            className="border rounded-3 p-2 m-0 bg-white"
                            style={{
                              height: 40,
                              width: 40,
                              display: "flex",
                              alignItems: "center",
                              justifyContent: "center",
                            }}
                            onClick={handleCopyLink}
                          >
                            <UploadIcon size={18} />
                          </button>
                        </div>
                        {/* <div className="make-video-section d-flex justify-content-end align-items-center gap-1 rounded-md w-max-content p-0 m-0"> */}
                        <button
                          className="btn h-40 text-white border-0 rounded-3 d-flex justify-content-center align-items-center gap-2 py-2 px-3 "
                          type="button"
                          onClick={() => {
                            if (media?.id === undefined) return;
                            
                            // Check if prompt is empty
                            if (!promptMessage.trim()) {
                              showToast("Please enter a prompt to continue");
                              return;
                            }
                            
                            setPendingMediaId(media.id);
                            setShowVideoDialog(true);
                          }}
                          disabled={makingVideo}
                          style={{
                            background: "#51667b",
                            color: "white",
                            border: "none",
                            opacity: makingVideo ? 0.6 : 1,
                            cursor: makingVideo ? "not-allowed" : "pointer",
                          }}
                        >
                          {makingVideo ? (
                            <>
                              <div
                                className="spinner-border spinner-border-sm"
                                role="status"
                                style={{ width: "18px", height: "18px" }}
                              >
                                <span className="visually-hidden">Loading...</span>
                              </div>
                              Generating...
                            </>
                          ) : (
                            <>
                              <PlayIcon stroke="white" size={18} /> Make Video
                            </>
                          )}
                        </button>
                      </div>
                    </div>
                  </div>
                  <p className="upload-text d-flex justify-content-start align-items-center gap-1 gap-md-2 bg-light px-2 py-1 rounded-2">
                    <StarsIcon className="upload-text-svg" size={20} />
                    Describe changes or upload a reference.
                  </p>
                  <div className="my-3">
                    <button
                      type="button"
                      className="stylePresets-a collapsed d-flex justify-content-between align-items-center gap-2 w-100 text-decoration-none fw-medium no-bg-btn p-0 m-0"
                      onClick={togglePresets}
                      aria-expanded={showPresets}
                    >
                      Style Presets
                      <svg
                        className="icon-18px"
                        viewBox="0 0 24 24"
                        fill="none"
                        xmlns="http://www.w3.org/2000/svg"
                        style={{
                          transition: "transform 0.3s ease",
                          transform: showPresets
                            ? "rotate(180deg)"
                            : "rotate(0deg)",
                        }}
                      >
                        <polyline
                          points="18 15 12 9 6 15"
                          stroke="var(--color-second)"
                          strokeWidth="2"
                          strokeLinecap="round"
                          strokeLinejoin="round"
                        />
                      </svg>
                    </button>
                    <div
                      className={`d-flex flex-wrap creative-type-options creative-other-type-options gap-1 gap-md-2 my-1 my-md-3 ${showPresets ? "" : "d-none"
                        }`}
                    >
                      {[
                        "Amazon Product Shot",
                        "Skincare Aesthetic",
                        "Home Décor Lifestyle",
                        "Fashion Mirror Selfie",
                        "Aesthetic Room Background",
                        "TikTok-Style UGC Background",
                        "Reels-Friendly Vertical Video",
                        "Make My Product Look Expensive",
                      ].map((label) => (
                        <div className="d-flex gap-1" key={label}>
                          <button
                            type="button"
                            className="btn text-start bg-light d-flex gap-1 align-items-center border border-1 rounded-2"
                            onClick={() => setPromptMessage(label)}
                          >
                            <small>{label}</small>
                          </button>
                        </div>
                      ))}
                    </div>
                  </div>
                </div>

                <div className="col-xxl-10 col-xl-10 col-lg-10 col-md-12 col-sm-12 col-12 m-0 d-flex flex-column gap-3">
                  <div className="d-flex gap-2 align-items-center upload-img-section bg-light p-2 rounded-2 border">
                    <span className="input-group-text p-0 border-0 bg-transparent order-md-1 order-2">
                      <label className="image-upload-box cover-photo-section creative-photo-box mb-0">
                        {previewSrc ? (
                          <>
                            <img
                              className="preview-img"
                              src={previewSrc}
                              alt="preview"
                            />
                            <button
                              type="button"
                              className="remove-btn action-icon remove-icon"
                              onClick={removeImg}
                              aria-label="Remove image"
                            >
                              <CrossIcon />
                            </button>
                          </>
                        ) : (
                          <UploadIcon style={{ height: 16, width: 16 }} />
                        )}
                        <input
                          ref={fileInputRef}
                          type="file"
                          accept="image/*,video/*"
                          className="imageInput"
                          onChange={handlePreviewImage}
                        />
                      </label>
                    </span>

                    <input
                      type="text"
                      className="form-control rounded-3 ps-2 creative-type-input order-md-2 order-1"
                      placeholder="Type to imagine"
                      value={promptMessage}
                      onChange={(e) => setPromptMessage(e.target.value)}
                      onKeyDown={handleKeyDown}
                    />

                    <span className="input-group-text py-0 px-0 mb-0 border-0 bg-transparent d-flex order-md-3 order-3">
                      <VoiceInputButton
                        onTranscript={handleVoiceTranscript}
                        disabled={loading}
                      />
                      <div
                        className="dropdown select-creative-options rounded-2 me-2 p-2"
                        style={{ position: "relative" }}
                      >

                        <button
                          ref={popoverToggleRef}
                          type="button"
                          id="imagine-dropdown-toggle"
                          className="button bg-transparent rounded-2 border border-1 p-2 dropdown-toggle plus-icon d-flex justify-content-center align-items-center gap-1"
                          onClick={togglePopover}
                          aria-expanded={popoverOpen}
                          aria-haspopup="dialog"
                        >
                          {mode === "Video" ? (
                            <VideoIcon className="icon-18px" />
                          ) : (
                            <ImageIcon className="icon-18px" />
                          )}
                          <span className="dropdown-text mb-0">{mode}</span>
                        </button>

                        <div
                          hidden={!popoverOpen}
                          className="dropdown-menu rounded-2 upload-box z-9999"
                          role="dialog"
                          aria-label="Generate options"
                          style={{
                            display: "block",
                            top: "auto",
                            bottom: "calc(100% + 8px)",
                            right: 0,
                          }}
                          ref={popoverRef}
                        >
                          <div className="py-1 px-2">
                            <p className="menu-title d-block fw-semibold color-second w-100 mb-1">
                              Aspect Ratio
                            </p>
                            <div className="aspectRatio d-flex align-items-center p-0 m-0">
                              <button
                                type="button"
                                className={`aspectRatioBtn hover-icons-bg rounded-pill ${selectedAspect === "2:3" ? "active" : ""}`}
                                onClick={() => handleAspect("2:3")}
                              >
                                <RectangleVertical className="tools-icon m-0 p-0" />
                                <div className="aspectRatioText text-12 fw-semibold color-second  rounded-2 mx-auto py-1 px-2">
                                  2:3
                                </div>
                              </button>
                              <button
                                type="button"
                                className={`aspectRatioBtn hover-icons-bg rounded-pill ${selectedAspect === "3:2" ? "active" : ""}`}
                                onClick={() => handleAspect("3:2")}
                              >
                                <RectangleHorizontal className="tools-icon m-0 p-0" />
                                <div className="aspectRatioText text-12 fw-semibold color-second  rounded-2 mx-auto py-1 px-2">
                                  3:2
                                </div>
                              </button>
                              <button
                                type="button"
                                className={`aspectRatioBtn hover-icons-bg rounded-pill ${selectedAspect === "1:1" ? "active" : ""}`}
                                onClick={() => handleAspect("1:1")}
                              >
                                <Square className="tools-icon m-0 p-0" />
                                <div className="aspectRatioText text-12 fw-semibold color-second  rounded-2 mx-auto py-1 px-2">
                                  1:1
                                </div>
                              </button>
                            </div>
                          </div>
                          <hr className="my-2" />
                          <button
                            type="button"
                            className={`text-start imagine-dropdown-item hover-icons-bg dropdown-item d-flex justify-content-start align-items-center gap-2 w-100 h-auto py-1 px-2 mx-0 mt-0 mb-1 ${mode === "Video" ? "active" : ""}`}
                            onClick={() => {
                              setMode("Video");
                              setPopoverOpen(false);
                            }}
                          >
                            <VideoIcon className="icon-18px" />
                            <div>
                              <p className="mb-0 my-text-small fw-medium">
                                Video
                              </p>
                              <p className="text-11 fw-medium color-second p-0 m-0">
                                Generate a video
                              </p>
                            </div>
                          </button>
                          <button
                            type="button"
                            className={`text-start imagine-dropdown-item hover-icons-bg dropdown-item d-flex justify-content-start align-items-center gap-2 w-100 h-auto py-1 px-2 mx-0 mt-0 mb-0 ${mode === "Image" ? "active" : ""}`}
                            onClick={() => {
                              setMode("Image");
                              setPopoverOpen(false);
                            }}
                          >
                            <ImageIcon className="icon-18px" />
                            <div>
                              <p className="mb-0 my-text-small fw-medium">
                                Image
                              </p>
                              <p className="text-11 fw-medium color-second p-0 m-0">
                                Generate multiple images
                              </p>
                            </div>
                          </button>
                        </div>
                      </div>
                      <button
                        className="search-btn border bg-color-second p-2 rounded-2"
                        type="button"
                        style={{
                          background: promptMessage ? "#51667b" : "#ccc",
                        }}
                        aria-label="Generate"
                        onClick={handleSend}
                        title="Send"
                        disabled={editing}
                      >
                        <ArrowUpIcon
                          style={{
                            height: 16,
                            width: 16,
                            stroke: promptMessage ? "#fff" : "black",
                          }}
                        />
                      </button>
                    </span>
                  </div>
                </div>
              </div>
              <div>
                {/* Only show versions gallery when there are multiple versions */}
                {versions.length > 1 && (
                  <VersionsGallery
                    initialVersions={versions}
                    onVersionSelect={handleVersionSelect}
                    isLoadingProp={isLoading}
                    selectedVersionId={media?.id}
                  />
                )}
              </div>
            </div>
            )}
          </div>
        </section>
      </div>


      {showLimitModal && (
        <>
          {/* Backdrop */}
          <div
            style={{
              position: "fixed",
              top: 0,
              left: 0,
              right: 0,
              bottom: 0,
              backgroundColor: "rgba(0, 0, 0, 0.5)",
              zIndex: 9998,
            }}
            onClick={closeLimitModal}
          />

          {/* Modal */}
          <div
            style={{
              position: "fixed",
              top: "50%",
              left: "50%",
              transform: "translate(-50%, -50%)",
              backgroundColor: "white",
              borderRadius: "12px",
              padding: "32px",
              maxWidth: "440px",
              width: "90%",
              zIndex: 9999,
              boxShadow:
                "0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04)",
            }}
          >
            {/* Close button */}
            <button
              onClick={closeLimitModal}
              style={{
                position: "absolute",
                top: "16px",
                right: "16px",
                background: "transparent",
                border: "none",
                cursor: "pointer",
                padding: "4px",
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
                color: "#6b7280",
              }}
              aria-label="Close modal"
            >
              <XIcon size={20} />
            </button>

            {/* Icon */}
            <div
              style={{
                width: "64px",
                height: "64px",
                borderRadius: "50%",
                backgroundColor: "#fee2e2",
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
                margin: "0 auto 24px",
              }}
            >
              <svg
                width="32"
                height="32"
                viewBox="0 0 24 24"
                fill="none"
                stroke="#dc2626"
                strokeWidth="2"
                strokeLinecap="round"
                strokeLinejoin="round"
              >
                <circle cx="12" cy="12" r="10" />
                <line x1="15" y1="9" x2="9" y2="15" />
                <line x1="9" y1="9" x2="15" y2="15" />
              </svg>
            </div>

            {/* Title */}
            <h2
              style={{
                fontSize: "24px",
                fontWeight: "600",
                color: "#111827",
                textAlign: "center",
                marginBottom: "12px",
              }}
            >
              Limit Exceeded
            </h2>

            {/* Description */}
            <p
              style={{
                fontSize: "14px",
                color: "#6b7280",
                textAlign: "center",
                lineHeight: "1.5",
                marginBottom: "8px",
              }}
            >
              You&apos;ve used all your free generations for today.
            </p>

            {/* Reset time */}
            <p
              style={{
                fontSize: "13px",
                color: "#9ca3af",
                textAlign: "center",
                marginBottom: "24px",
              }}
            >
              {quota?.resets_at
                ? `Your next free generation will reset on ${new Date(
                  quota.resets_at
                ).toLocaleString()}.`
                : "Your quota will reset soon."}
            </p>

            {/* Upgrade button */}
          <button
    onClick={closeLimitModal} // 👈 close popup
    style={{
      width: "100%",
      padding: "6px 14px",
      backgroundColor: "#6b7280",
      color: "white",
      border: "none",
      borderRadius: "8px",
      fontSize: "16px",
      fontWeight: "600",
      cursor: "pointer",
      transition: "background-color 0.2s",
    }}
    onMouseEnter={(e) => {
      e.currentTarget.style.backgroundColor = "#4b5563";
    }}
    onMouseLeave={(e) => {
      e.currentTarget.style.backgroundColor = "#6b7280";
    }}
  >
    OK
  </button>
          </div>
        </>
      )
      }

      {
        showExceedLimitModal && (
          <LimitModal
            showLimitModal={showExceedLimitModal}
            closeLimitModal={closeLimitModal}
            quota={quota}
            handleUpgrade={handleUpgrade}
            isLimitExceeded={showLimitModal}
          />
        )
      }

      {
        showVideoDialog && (
          <div className="dialog-backdrop">
            <div className="dialog-box">
              <h3>Confirm Video Creation</h3>

              <p>
                After you create the video from this image, you can’t create
                an image from the video.
              </p>

              <div className="dialog-actions">
                <button
                  onClick={() => {
                    setShowVideoDialog(false);
                    setPendingMediaId(null);
                  }}
                >
                  Cancel
                </button>

                <button
                  className="primary"
                  onClick={() => {
                    if (pendingMediaId) {
                      handleMakeVideo(pendingMediaId);
                    }
                    setShowVideoDialog(false);
                    setPendingMediaId(null);
                  }}
                >
                  Confirm
                </button>
              </div>
            </div>
          </div>
        )
      }
    </div>
  )
}
