"use client";
import { useAtom } from "jotai";
import { Section } from "../section";
import { formAtom, videoUploadingAtom } from "@/components/state/autionAtoms";
import { useTranslations } from "next-intl";
import { uploadImage, removeImage } from "@/actions/upload-image";
import { toast } from "react-toastify";
import ModalCropper from "@/views/shared/ModalCropper";
import { useState, useRef } from "react";
import Image from "next/image";
import { Input } from "@heroui/react";
import { useSession } from "@/auth/session-provider";
import { BaseModal } from "@/components/modal";
import PdfViewer from "@/components/viewers/PdfViewer";

type CropModalState = {
  open: boolean;
  files: File[];
  currentIndex: number;
  fieldName: string;
  collection: string;
  croppedResults: Blob[];
};

export function Step7() {
  const t = useTranslations("ADD_LISTING.STEP7");
  const tDocs = useTranslations("ADD_LISTING.STEP5");
  const [form, setForm] = useAtom(formAtom);
  const [, setVideoUploading] = useAtom(videoUploadingAtom);
  const session = useSession();
  const [previewUrl, setPreviewUrl] = useState<string | null>(null);
  const uploadAbortRef = useRef<AbortController | null>(null);
  const [pdfModalOpen, setPdfModalOpen] = useState(false);
  const [selectedPdf, setSelectedPdf] = useState<{
    url: string;
    title: string;
  } | null>(null);
  /*   const modelName = form.offer === "fixed" ? "Offer" : "Auction";
   */
  const [cropModal, setCropModal] = useState<CropModalState>({
    open: false,
    files: [],
    currentIndex: 0,
    fieldName: "",
    collection: "",
    croppedResults: [],
  });

  const getFileKind = (f: any): "video" | "pdf" | "image" | "other" => {
    const url = String(f?.url || "").toLowerCase();
    const type = String(f?.type || "").toLowerCase();
    const name = String(f?.name || "").toLowerCase();

    if (String(f?.collection_name || "") === "video") return "video";
    if (type.includes("pdf") || url.endsWith(".pdf") || name.endsWith(".pdf"))
      return "pdf";
    if (
      type.startsWith("image/") ||
      url.match(/\.(jpg|jpeg|png|gif|webp)$/i) ||
      name.match(/\.(jpg|jpeg|png|gif|webp)$/i)
    )
      return "image";
    return "other";
  };

  const getCollectionLabel = (collection: string) => {
    if (collection === "main_image") return t("collections.main_image");
    if (collection === "additional_images")
      return t("collections.additional_images");
    if (collection === "video") return t("collections.video");
    return t("collections.other", { value: collection || "-" });
  };

  // Filter files to show only media (not documents like certificates)
  const mediaCollections = ["main_image", "additional_images", "video"];
  const mediaFiles = (form.files || []).filter((f: any) =>
    mediaCollections.includes(f.collection_name),
  );

  const openPdf = (url: string, title: string) => {
    setSelectedPdf({ url, title });
    setPdfModalOpen(true);
  };

  const handleVideoFileChange = (files: FileList | null) => {
    if (!files?.length) return;

    const modelName = form.offer === "fixed" ? "Offer" : "Auction";

    const selectedFile = files[0];
    const localId = `local_${Date.now()}_${Math.random().toString(16).slice(2)}`;
    const localUrl = URL.createObjectURL(selectedFile);

    setForm((prev) => ({
      ...prev,
      files: [
        ...(prev.files || []),
        {
          localId,
          uploading: true,
          name: selectedFile.name,
          type: selectedFile.type,
          collection_name: "video",
          url: localUrl,
        },
      ],
    }));

    // Show persistent toast for video upload
    const toastId = toast.loading(t("toast.video_uploading_background"), {
      autoClose: false,
      closeOnClick: false,
    });

    // Mark video as uploading (for navigation warning)
    setVideoUploading(true);

    // Run upload in background (non-blocking)
    (async () => {
      try {
        const formData = new FormData();
        formData.append("model_name", modelName);
        formData.append("media[video]", selectedFile);

        const res = await uploadImage(formData);
        if (res?.success && Array.isArray(res.data) && res.data[0]) {
          const uploaded = res.data[0] as any;
          setForm((prev) => ({
            ...prev,
            files: (prev.files || []).map((x: any) =>
              x?.localId === localId
                ? {
                    id: uploaded.id,
                    collection_name: uploaded.collection_name,
                    url: uploaded.url,
                    uploading: false,
                    name: selectedFile.name,
                    type: selectedFile.type,
                  }
                : x,
            ),
          }));
          toast.update(toastId, {
            render: t("toast.video_upload_success"),
            type: "success",
            isLoading: false,
            autoClose: 3000,
            closeOnClick: true,
          });
        } else {
          setForm((prev) => ({
            ...prev,
            files: (prev.files || []).filter(
              (x: any) => x?.localId !== localId,
            ),
          }));
          toast.update(toastId, {
            render: tDocs("toast.upload_failed"),
            type: "error",
            isLoading: false,
            autoClose: 4000,
            closeOnClick: true,
          });
        }
      } catch (err) {
        console.error("❌ Video upload failed:", err);
        setForm((prev) => ({
          ...prev,
          files: (prev.files || []).filter((x: any) => x?.localId !== localId),
        }));
        toast.update(toastId, {
          render: tDocs("toast.upload_failed"),
          type: "error",
          isLoading: false,
          autoClose: 4000,
          closeOnClick: true,
        });
      } finally {
        setVideoUploading(false);
      }
    })();
  };

  const handleVideoChange = (index: number, value: string) => {
    setForm((prev) => {
      const current = prev.videoLinks || [];
      const next = [...current];
      next[index] = value;
      return { ...prev, videoLinks: next };
    });
  };

  const addVideoField = () => {
    setForm((prev) => ({
      ...prev,
      videoLinks: [...(prev.videoLinks || []), ""],
    }));
  };

  const removeVideoField = (index: number) => {
    setForm((prev) => {
      const current = prev.videoLinks || [];
      const next = current.filter((_, i) => i !== index);
      return { ...prev, videoLinks: next.length ? next : [""] };
    });
  };

  const handleFileChange = (
    fieldName: string,
    collectionName: string,
    files: FileList | null,
  ) => {
    if (!files?.length) return;
    const fileArray = Array.from(files);
    setPreviewUrl(URL.createObjectURL(fileArray[0]));
    setCropModal({
      open: true,
      files: fileArray,
      currentIndex: 0,
      fieldName,
      collection: collectionName,
      croppedResults: [],
    });
  };

  const handleUseOriginalImage = async () => {
    const file = cropModal.files[cropModal.currentIndex];
    if (!file) return;
    const blob = new Blob([await file.arrayBuffer()], {
      type: file.type || "image/jpeg",
    });
    await handleCropConfirm(blob);
  };

  const handleCropConfirm = async (croppedBlob: Blob) => {
    const nextIndex = cropModal.currentIndex + 1;
    const newResults = [...cropModal.croppedResults, croppedBlob];

    if (nextIndex < cropModal.files.length) {
      const nextImage = URL.createObjectURL(cropModal.files[nextIndex]);
      setPreviewUrl(nextImage);
      setCropModal({
        ...cropModal,
        currentIndex: nextIndex,
        croppedResults: newResults,
      });
    } else {
      await uploadAllImages(
        newResults,
        cropModal.fieldName,
        cropModal.collection,
      );

      setCropModal({
        open: false,
        files: [],
        currentIndex: 0,
        fieldName: "",
        collection: "",
        croppedResults: [],
      });
      setPreviewUrl(null);
    }
  };

  const blobToUploadFile = (blob: Blob, index: number, coll: string) => {
    const mime =
      blob.type && blob.type !== "application/octet-stream"
        ? blob.type
        : "image/jpeg";
    let ext = "jpg";
    if (mime.includes("png")) ext = "png";
    else if (mime.includes("webp")) ext = "webp";
    else if (mime.includes("gif")) ext = "gif";
    const name =
      coll === "main_image" ? `main.${ext}` : `image_${index}.${ext}`;
    return new File([blob], name, { type: mime });
  };

  const uploadAllImages = async (
    croppedBlobs: Blob[],
    fieldName: string,
    collection: string,
  ) => {
    const formData = new FormData();

    const modelName = form.offer === "fixed" ? "Offer" : "Auction";
    formData.append("model_name", modelName);

    if (collection === "main_image") {
      formData.append(
        fieldName,
        blobToUploadFile(croppedBlobs[0], 0, collection),
      );
    } else {
      croppedBlobs.forEach((blob, i) => {
        formData.append(
          `${fieldName}[${i}]`,
          blobToUploadFile(blob, i, collection),
        );
      });
    }

    try {
      const res = await uploadImage(formData);
      if (res?.success && Array.isArray(res.data)) {
        const uploadedFiles = res.data.map((f) => ({
          id: (f as any).id,
          collection_name: f.collection_name,
          url: f.url,
        }));

        toast.success(
          t("toast.uploaded_with_collection", {
            collection: getCollectionLabel(collection),
          }),
        );
        setForm((p) => ({
          ...p,
          files: [...(p.files || []), ...uploadedFiles],
        }));
      } else toast.error(t("toast.upload_failed"));
    } catch (err) {
      console.error("❌ upload error:", err);
      toast.error(t("toast.upload_failed"));
    }
  };

  const handleRemoveFile = async (f: any) => {
    const mediaId = (f as any)?.id as number | undefined;

    if (!mediaId) {
      setForm((prev) => ({
        ...prev,
        files: (prev.files || []).filter((x: any) => {
          if ((f as any)?.localId && (x as any)?.localId)
            return (x as any).localId !== (f as any).localId;
          return !(
            String((x as any)?.url || "") === String((f as any)?.url || "") &&
            String((x as any)?.collection_name || "") ===
              String((f as any)?.collection_name || "")
          );
        }),
      }));
      return;
    }

    try {
      const token = session?.access_token;
      if (!token) {
        toast.error(t("toast.remove_failed"));
        return;
      }

      const res = await removeImage({ mediaIds: [mediaId], token });
      if ((res as any)?.success === false) {
        toast.error((res as any)?.message || t("toast.remove_failed"));
        return;
      }

      toast.success(
        t("toast.removed_with_collection", {
          collection: getCollectionLabel(String(f?.collection_name || "")),
        }),
      );
      setForm((prev) => ({
        ...prev,
        files: (prev.files || []).filter(
          (x: any) => String((x as any)?.id) !== String(mediaId),
        ),
      }));
    } catch (err) {
      toast.error(t("toast.remove_failed"));
    }
  };

  const mainImage = mediaFiles.find(
    (f: any) => f.collection_name === "main_image",
  );
  const additionalImages = mediaFiles.filter(
    (f: any) => f.collection_name === "additional_images",
  );
  const videoFiles = mediaFiles.filter(
    (f: any) => f.collection_name === "video",
  );

  const mainImageInputRef = useRef<HTMLInputElement>(null);
  const galleryInputRef = useRef<HTMLInputElement>(null);
  const videoInputRef = useRef<HTMLInputElement>(null);

  return (
    <Section title={t("title")}>
      <div className="space-y-6 text-start">
        {/* ── Main Image ── */}
        <div>
          <h4 className="text-sm font-semibold text-slate-800 mb-2">
            {t("main_image")}
          </h4>
          {mainImage ? (
            <div className="relative w-full max-w-xs aspect-square rounded-2xl overflow-hidden border-2 border-primary/30 shadow-sm group">
              <Image
                src={mainImage.url}
                alt="main"
                fill
                className="object-cover"
                unoptimized
              />
              {mainImage.uploading && (
                <div className="absolute inset-0 bg-black/50 flex items-center justify-center">
                  <div className="flex flex-col items-center gap-2">
                    <div className="w-8 h-8 border-3 border-white border-t-transparent rounded-full animate-spin" />
                    <span className="text-white text-xs font-medium">
                      {t("uploading_overlay")}
                    </span>
                  </div>
                </div>
              )}
              <div className="absolute top-2 start-2 bg-primary text-white text-[10px] font-bold px-2 py-0.5 rounded-full">
                {t("collections.main_image")}
              </div>
              <button
                type="button"
                onClick={() => void handleRemoveFile(mainImage)}
                className="absolute top-2 end-2 bg-red-500 hover:bg-red-600 text-white rounded-full w-7 h-7 flex items-center justify-center text-sm shadow-md opacity-0 group-hover:opacity-100 transition-opacity"
              >
                <svg xmlns="http://www.w3.org/2000/svg" className="w-4 h-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M3 6h18"/><path d="M19 6v14a2 2 0 01-2 2H7a2 2 0 01-2-2V6"/><path d="M8 6V4a2 2 0 012-2h4a2 2 0 012 2v2"/></svg>
              </button>
            </div>
          ) : (
            <>
              <input
                ref={mainImageInputRef}
                type="file"
                accept="image/*"
                className="hidden"
                onChange={(e) => {
                  const files = e.target.files;
                  if (files && files.length > 1) {
                    toast.error(t("toast.only_one_main_image"));
                    return;
                  }
                  handleFileChange("media[main_image]", "main_image", files);
                  e.target.value = "";
                }}
              />
              <button
                type="button"
                onClick={() => mainImageInputRef.current?.click()}
                className="w-full max-w-xs aspect-square rounded-2xl border-2 border-dashed border-primary/40 bg-primary/[0.03] hover:bg-primary/[0.06] hover:border-primary/60 transition-all flex flex-col items-center justify-center gap-3 cursor-pointer"
              >
                <div className="w-14 h-14 rounded-2xl bg-primary/10 flex items-center justify-center">
                  <svg xmlns="http://www.w3.org/2000/svg" className="w-7 h-7 text-primary" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><path d="M21 15l-5-5L5 21"/></svg>
                </div>
                <div className="text-center">
                  <p className="text-sm font-semibold text-primary">{t("main_image")}</p>
                  <p className="text-xs text-slate-400 mt-0.5">{t("click_to_upload")}</p>
                </div>
              </button>
            </>
          )}
        </div>

        {/* ── Additional Images ── */}
        <div>
          <div className="flex items-center justify-between mb-2">
            <h4 className="text-sm font-semibold text-slate-800">{t("gallery")}</h4>
            <input
              ref={galleryInputRef}
              type="file"
              accept="image/*"
              multiple
              className="hidden"
              onChange={(e) => {
                handleFileChange(
                  "media[additional_images]",
                  "additional_images",
                  e.target.files,
                );
                e.target.value = "";
              }}
            />
            <button
              type="button"
              onClick={() => galleryInputRef.current?.click()}
              className="text-xs font-medium text-primary hover:text-primary/80 border border-primary/30 hover:border-primary/50 rounded-lg px-3 py-1.5 transition-all flex items-center gap-1.5"
            >
              <svg xmlns="http://www.w3.org/2000/svg" className="w-3.5 h-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M12 5v14"/><path d="M5 12h14"/></svg>
              {t("add_images")}
            </button>
          </div>

          {additionalImages.length > 0 ? (
            <div className="grid grid-cols-3 sm:grid-cols-4 lg:grid-cols-5 gap-3">
              {additionalImages.map((f, i) => (
                <div
                  key={`${(f as any)?.id ?? (f as any)?.localId ?? i}`}
                  className="relative aspect-square rounded-xl overflow-hidden border border-slate-200 shadow-sm group"
                >
                  <Image
                    src={f.url}
                    alt={`gallery-${i}`}
                    fill
                    className="object-cover"
                    unoptimized
                  />
                  {f.uploading && (
                    <div className="absolute inset-0 bg-black/50 flex items-center justify-center">
                      <div className="w-6 h-6 border-2 border-white border-t-transparent rounded-full animate-spin" />
                    </div>
                  )}
                  <button
                    type="button"
                    onClick={() => void handleRemoveFile(f)}
                    className="absolute top-1.5 end-1.5 bg-black/60 hover:bg-red-500 text-white rounded-full w-6 h-6 flex items-center justify-center text-xs opacity-0 group-hover:opacity-100 transition-all"
                  >
                    <svg xmlns="http://www.w3.org/2000/svg" className="w-3.5 h-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M18 6L6 18"/><path d="M6 6l12 12"/></svg>
                  </button>
                </div>
              ))}

              {/* Add more button */}
              <button
                type="button"
                onClick={() => galleryInputRef.current?.click()}
                className="aspect-square rounded-xl border-2 border-dashed border-slate-300 hover:border-primary/50 bg-slate-50 hover:bg-primary/[0.03] transition-all flex flex-col items-center justify-center gap-1.5 cursor-pointer"
              >
                <svg xmlns="http://www.w3.org/2000/svg" className="w-6 h-6 text-slate-400" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><path d="M12 5v14"/><path d="M5 12h14"/></svg>
                <span className="text-[10px] text-slate-400 font-medium">{t("add_images")}</span>
              </button>
            </div>
          ) : (
            <button
              type="button"
              onClick={() => galleryInputRef.current?.click()}
              className="w-full py-10 rounded-2xl border-2 border-dashed border-slate-300 hover:border-primary/50 bg-slate-50 hover:bg-primary/[0.03] transition-all flex flex-col items-center justify-center gap-3 cursor-pointer"
            >
              <div className="w-12 h-12 rounded-xl bg-slate-200/80 flex items-center justify-center">
                <svg xmlns="http://www.w3.org/2000/svg" className="w-6 h-6 text-slate-500" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><path d="M21 15l-5-5L5 21"/></svg>
              </div>
              <div className="text-center">
                <p className="text-sm font-medium text-slate-600">{t("gallery")}</p>
                <p className="text-xs text-slate-400 mt-0.5">{t("click_to_upload")}</p>
              </div>
            </button>
          )}
        </div>

        {/* ── Video Upload ── */}
        <div>
          <div className="flex items-center justify-between mb-2">
            <div>
              <h4 className="text-sm font-semibold text-slate-800">
                {t("video")}
              </h4>
              <p className="text-xs text-slate-400">{t("video_max_size_note")}</p>
            </div>
          </div>

          {videoFiles.length > 0 ? (
            <div className="space-y-3">
              {videoFiles.map((f, i) => (
                <div
                  key={`${(f as any)?.id ?? (f as any)?.localId ?? i}`}
                  className="relative rounded-2xl overflow-hidden border border-slate-200 shadow-sm bg-black group"
                >
                  <video
                    src={f.url}
                    className="w-full max-h-64 object-contain"
                    controls={!f.uploading}
                  />
                  {f.uploading && (
                    <div className="absolute inset-0 bg-black/60 flex flex-col items-center justify-center gap-3">
                      <div className="w-10 h-10 border-3 border-white border-t-transparent rounded-full animate-spin" />
                      <span className="text-white text-sm font-medium">
                        {t("uploading_overlay")}
                      </span>
                    </div>
                  )}
                  <button
                    type="button"
                    onClick={() => void handleRemoveFile(f)}
                    className="absolute top-3 end-3 bg-red-500 hover:bg-red-600 text-white rounded-full w-8 h-8 flex items-center justify-center shadow-lg opacity-0 group-hover:opacity-100 transition-opacity"
                  >
                    <svg xmlns="http://www.w3.org/2000/svg" className="w-4 h-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M3 6h18"/><path d="M19 6v14a2 2 0 01-2 2H7a2 2 0 01-2-2V6"/><path d="M8 6V4a2 2 0 012-2h4a2 2 0 012 2v2"/></svg>
                  </button>
                  <div className="absolute bottom-0 inset-x-0 bg-gradient-to-t from-black/80 to-transparent px-3 py-2">
                    <span className="text-white text-xs font-medium">
                      {f.uploading ? t("uploading_status") : t("collections.video")}
                    </span>
                  </div>
                </div>
              ))}
            </div>
          ) : (
            <>
              <input
                ref={videoInputRef}
                type="file"
                accept="video/*"
                className="hidden"
                onChange={(e) => {
                  handleVideoFileChange(e.target.files);
                  e.target.value = "";
                }}
              />
              <button
                type="button"
                onClick={() => videoInputRef.current?.click()}
                className="w-full py-10 rounded-2xl border-2 border-dashed border-slate-300 hover:border-primary/50 bg-slate-50 hover:bg-primary/[0.03] transition-all flex flex-col items-center justify-center gap-3 cursor-pointer"
              >
                <div className="w-12 h-12 rounded-xl bg-slate-200/80 flex items-center justify-center">
                  <svg xmlns="http://www.w3.org/2000/svg" className="w-6 h-6 text-slate-500" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><polygon points="23 7 16 12 23 17 23 7"/><rect x="1" y="5" width="15" height="14" rx="2"/></svg>
                </div>
                <div className="text-center">
                  <p className="text-sm font-medium text-slate-600">{t("video")}</p>
                  <p className="text-xs text-slate-400 mt-0.5">{t("click_to_upload")}</p>
                </div>
              </button>
            </>
          )}
        </div>

        {/* ── Video Links ── */}
        <div>
          <div className="flex items-center justify-between mb-2">
            <h4 className="text-sm font-semibold text-slate-800">
              {t("videos_title")}
            </h4>
            <button
              type="button"
              onClick={addVideoField}
              className="text-xs font-medium text-primary hover:text-primary/80 border border-primary/30 hover:border-primary/50 rounded-lg px-3 py-1.5 transition-all flex items-center gap-1.5"
            >
              <svg xmlns="http://www.w3.org/2000/svg" className="w-3.5 h-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M12 5v14"/><path d="M5 12h14"/></svg>
              {t("add_video")}
            </button>
          </div>
          <div className="space-y-2">
            {(form.videoLinks || [""]).map((link, index) => (
              <div
                key={index}
                className="flex items-center gap-2 rounded-xl border border-slate-200 bg-white px-3 py-1.5 transition-all focus-within:border-primary/40 focus-within:shadow-sm"
              >
                <svg xmlns="http://www.w3.org/2000/svg" className="w-4 h-4 text-slate-400 shrink-0" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><path d="M10 13a5 5 0 007.54.54l3-3a5 5 0 00-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 00-7.54-.54l-3 3a5 5 0 007.07 7.07l1.71-1.71"/></svg>
                <Input
                  type="text"
                  variant="underlined"
                  classNames={{ inputWrapper: "border-0 shadow-none after:hidden", input: "text-sm" }}
                  placeholder={t("video_placeholder")}
                  value={link}
                  onValueChange={(v) => handleVideoChange(index, v)}
                />
                <button
                  type="button"
                  onClick={() => removeVideoField(index)}
                  className="shrink-0 w-7 h-7 rounded-full hover:bg-red-50 flex items-center justify-center text-slate-400 hover:text-red-500 transition-colors"
                >
                  <svg xmlns="http://www.w3.org/2000/svg" className="w-4 h-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M18 6L6 18"/><path d="M6 6l12 12"/></svg>
                </button>
              </div>
            ))}
          </div>
        </div>
      </div>

      <BaseModal
        isOpen={pdfModalOpen}
        onOpenChange={setPdfModalOpen}
        placement="center"
        contentClassName="w-full max-w-4xl max-h-[85vh] overflow-y-auto rounded-2xl p-3"
        title={selectedPdf?.title || t("modal_pdf_title")}
      >
        {selectedPdf ? (
          <PdfViewer fileUrl={selectedPdf.url} fileName={selectedPdf.title} />
        ) : null}
      </BaseModal>

      {cropModal.open && previewUrl && (
        <ModalCropper
          open={cropModal.open}
          image={previewUrl}
          aspect={cropModal.collection === "main_image" ? 1 : 4 / 3}
          onCancel={() =>
            setCropModal({
              open: false,
              files: [],
              currentIndex: 0,
              fieldName: "",
              collection: "",
              croppedResults: [],
            })
          }
          onConfirm={handleCropConfirm}
          onUseOriginal={handleUseOriginalImage}
          useOriginalLabel={t("crop_use_original")}
        />
      )}
    </Section>
  );
}
