'use client';
import { jsxDEV as _jsxDEV } from "react/jsx-dev-runtime";
import { useModal } from '@faceless-ui/modal';
import { formatAdminURL, isImage } from 'payload/shared';
import React, { Fragment, useCallback, useEffect, useRef, useState } from 'react';
import { toast } from 'sonner';
import { FieldError } from '../../fields/FieldError/index.js';
import { fieldBaseClass } from '../../fields/shared/index.js';
import { useForm, useFormProcessing } from '../../forms/Form/index.js';
import { useField } from '../../forms/useField/index.js';
import { useConfig } from '../../providers/Config/index.js';
import { useDocumentInfo } from '../../providers/DocumentInfo/index.js';
import { EditDepthProvider } from '../../providers/EditDepth/index.js';
import { useTranslation } from '../../providers/Translation/index.js';
import { UploadControlsProvider, useUploadControls } from '../../providers/UploadControls/index.js';
import { useUploadEdits } from '../../providers/UploadEdits/index.js';
import { Button } from '../Button/index.js';
import { Drawer } from '../Drawer/index.js';
import { Dropzone } from '../Dropzone/index.js';
import { EditUpload } from '../EditUpload/index.js';
import './index.scss';
import { FileDetails } from '../FileDetails/index.js';
import { PreviewSizes } from '../PreviewSizes/index.js';
import { Thumbnail } from '../Thumbnail/index.js';
const baseClass = 'file-field';
export const editDrawerSlug = 'edit-upload';
export const sizePreviewSlug = 'preview-sizes';
const validate = (value)=>{
    if (!value && value !== undefined) {
        return 'A file is required.';
    }
    if (value && (!value.name || value.name === '')) {
        return 'A file name is required.';
    }
    return true;
};
export const UploadActions = ({ customActions, enableAdjustments, enablePreviewSizes, mimeType })=>{
    const { t } = useTranslation();
    const { openModal } = useModal();
    const fileTypeIsAdjustable = isImage(mimeType) && mimeType !== 'image/svg+xml' && mimeType !== 'image/jxl';
    if (!fileTypeIsAdjustable && (!customActions || customActions.length === 0)) {
        return null;
    }
    return /*#__PURE__*/ _jsxDEV("div", {
        className: `${baseClass}__upload-actions`,
        children: [
            fileTypeIsAdjustable && /*#__PURE__*/ _jsxDEV(React.Fragment, {
                children: [
                    enablePreviewSizes && /*#__PURE__*/ _jsxDEV(Button, {
                        buttonStyle: "pill",
                        className: `${baseClass}__previewSizes`,
                        margin: false,
                        onClick: ()=>{
                            openModal(sizePreviewSlug);
                        },
                        size: "small",
                        children: t('upload:previewSizes')
                    }, void 0, false, {
                        fileName: "src/elements/Upload/index.tsx",
                        lineNumber: 72,
                        columnNumber: 13
                    }, this),
                    enableAdjustments && /*#__PURE__*/ _jsxDEV(Button, {
                        buttonStyle: "pill",
                        className: `${baseClass}__edit`,
                        margin: false,
                        onClick: ()=>{
                            openModal(editDrawerSlug);
                        },
                        size: "small",
                        children: t('upload:editImage')
                    }, void 0, false, {
                        fileName: "src/elements/Upload/index.tsx",
                        lineNumber: 85,
                        columnNumber: 13
                    }, this)
                ]
            }, void 0, true, {
                fileName: "src/elements/Upload/index.tsx",
                lineNumber: 70,
                columnNumber: 9
            }, this),
            customActions && customActions.map((CustomAction, i)=>{
                return /*#__PURE__*/ _jsxDEV(React.Fragment, {
                    children: CustomAction
                }, i, false, {
                    fileName: "src/elements/Upload/index.tsx",
                    lineNumber: 102,
                    columnNumber: 18
                }, this);
            })
        ]
    }, void 0, true, {
        fileName: "src/elements/Upload/index.tsx",
        lineNumber: 68,
        columnNumber: 5
    }, this);
};
export const Upload = (props)=>{
    const { resetUploadEdits, updateUploadEdits, uploadEdits } = useUploadEdits();
    return /*#__PURE__*/ _jsxDEV(UploadControlsProvider, {
        children: /*#__PURE__*/ _jsxDEV(Upload_v4, {
            ...props,
            resetUploadEdits: resetUploadEdits,
            updateUploadEdits: updateUploadEdits,
            uploadEdits: uploadEdits
        }, void 0, false, {
            fileName: "src/elements/Upload/index.tsx",
            lineNumber: 121,
            columnNumber: 7
        }, this)
    }, void 0, false, {
        fileName: "src/elements/Upload/index.tsx",
        lineNumber: 120,
        columnNumber: 5
    }, this);
};
export const Upload_v4 = (props)=>{
    const { collectionSlug, customActions, initialState, onChange, resetUploadEdits, updateUploadEdits, uploadConfig, UploadControls, uploadEdits } = props;
    const { setUploadControlFile, setUploadControlFileName, setUploadControlFileUrl, uploadControlFile, uploadControlFileName, uploadControlFileUrl } = useUploadControls();
    const { config: { routes: { api } } } = useConfig();
    const { t } = useTranslation();
    const { setModified } = useForm();
    const { id, data, docPermissions, setUploadStatus } = useDocumentInfo();
    const isFormSubmitting = useFormProcessing();
    const { errorMessage, setValue, showError, value } = useField({
        path: 'file',
        validate
    });
    const [fileSrc, setFileSrc] = useState(null);
    const [removedFile, setRemovedFile] = useState(false);
    const [filename, setFilename] = useState(value?.name || '');
    const [showUrlInput, setShowUrlInput] = useState(false);
    const [fileUrl, setFileUrl] = useState('');
    const urlInputRef = useRef(null);
    const inputRef = useRef(null);
    const useServerSideFetch = typeof uploadConfig?.pasteURL === 'object' && uploadConfig.pasteURL.allowList?.length > 0;
    const handleFileChange = useCallback(({ file, isNewFile = true })=>{
        if (isNewFile && file instanceof File) {
            setFileSrc(URL.createObjectURL(file));
        }
        setValue(file);
        setShowUrlInput(false);
        setUploadControlFileUrl('');
        setUploadControlFileName(null);
        setUploadControlFile(null);
        if (typeof onChange === 'function') {
            onChange(file);
        }
    }, [
        onChange,
        setValue,
        setUploadControlFile,
        setUploadControlFileName,
        setUploadControlFileUrl
    ]);
    const renameFile = (fileToChange, newName)=>{
        // Creating a new File object with updated properties
        const newFile = new File([
            fileToChange
        ], newName, {
            type: fileToChange.type,
            lastModified: fileToChange.lastModified
        });
        return newFile;
    };
    const handleFileNameChange = React.useCallback((e)=>{
        const updatedFileName = e.target.value;
        if (value) {
            handleFileChange({
                file: renameFile(value, updatedFileName),
                isNewFile: false
            });
            setFilename(updatedFileName);
        }
    }, [
        handleFileChange,
        value
    ]);
    const handleFileSelection = useCallback((files)=>{
        const fileToUpload = files?.[0];
        handleFileChange({
            file: fileToUpload
        });
    }, [
        handleFileChange
    ]);
    const handleFileRemoval = useCallback(()=>{
        setRemovedFile(true);
        handleFileChange({
            file: null
        });
        setFileSrc('');
        setFileUrl('');
        resetUploadEdits();
        setShowUrlInput(false);
        setUploadControlFileUrl('');
        setUploadControlFileName(null);
        setUploadControlFile(null);
    }, [
        handleFileChange,
        resetUploadEdits,
        setUploadControlFile,
        setUploadControlFileName,
        setUploadControlFileUrl
    ]);
    const onEditsSave = useCallback((args)=>{
        setModified(true);
        updateUploadEdits(args);
    }, [
        setModified,
        updateUploadEdits
    ]);
    const handleUrlSubmit = useCallback(async ()=>{
        if (!fileUrl || uploadConfig?.pasteURL === false) {
            return;
        }
        setUploadStatus('uploading');
        try {
            // Attempt client-side fetch
            const clientResponse = await fetch(fileUrl);
            if (!clientResponse.ok) {
                throw new Error(`Fetch failed with status: ${clientResponse.status}`);
            }
            const blob = await clientResponse.blob();
            const fileName = uploadControlFileName || decodeURIComponent(fileUrl.split('/').pop() || '');
            const file = new File([
                blob
            ], fileName, {
                type: blob.type
            });
            handleFileChange({
                file
            });
            setUploadStatus('idle');
            return;
        } // Exit if client-side fetch succeeds
        catch (_clientError) {
            if (!useServerSideFetch) {
                // If server-side fetch is not enabled, show client-side error
                toast.error('Failed to fetch the file.');
                setUploadStatus('failed');
                return;
            }
        }
        // Attempt server-side fetch if client-side fetch fails and useServerSideFetch is true
        try {
            const pasteURL = `/${collectionSlug}/paste-url${id ? `/${id}?` : '?'}src=${encodeURIComponent(fileUrl)}`;
            const serverResponse = await fetch(formatAdminURL({
                apiRoute: api,
                path: pasteURL
            }));
            if (!serverResponse.ok) {
                throw new Error(`Fetch failed with status: ${serverResponse.status}`);
            }
            const blob = await serverResponse.blob();
            const fileName = decodeURIComponent(fileUrl.split('/').pop() || '');
            const file = new File([
                blob
            ], fileName, {
                type: blob.type
            });
            handleFileChange({
                file
            });
            setUploadStatus('idle');
        } catch (_serverError) {
            toast.error('The provided URL is not allowed.');
            setUploadStatus('failed');
        }
    }, [
        api,
        collectionSlug,
        fileUrl,
        handleFileChange,
        id,
        setUploadStatus,
        uploadConfig,
        uploadControlFileName,
        useServerSideFetch
    ]);
    useEffect(()=>{
        if (initialState?.file?.value instanceof File) {
            setFileSrc(URL.createObjectURL(initialState.file.value));
            setRemovedFile(false);
        }
    }, [
        initialState
    ]);
    useEffect(()=>{
        if (showUrlInput && urlInputRef.current) {}
    }, // urlInputRef.current.focus() // Focus on the remote-url input field when showUrlInput is true
    [
        showUrlInput
    ]);
    useEffect(()=>{
        if (isFormSubmitting) {
            setRemovedFile(false);
        }
    }, [
        isFormSubmitting
    ]);
    const canRemoveUpload = docPermissions?.update;
    const hasImageSizes = uploadConfig?.imageSizes?.length > 0;
    const hasResizeOptions = Boolean(uploadConfig?.resizeOptions);
    // Explicity check if set to true, default is undefined
    const focalPointEnabled = uploadConfig?.focalPoint === true;
    const { crop: showCrop = true, focalPoint = true } = uploadConfig;
    const showFocalPoint = focalPoint && (hasImageSizes || hasResizeOptions || focalPointEnabled);
    const acceptMimeTypes = uploadConfig.mimeTypes?.join(', ');
    const imageCacheTag = uploadConfig?.cacheTags && data?.updatedAt;
    useEffect(()=>{
        const handleControlFileUrl = async ()=>{
            if (uploadControlFileUrl) {
                setFileUrl(uploadControlFileUrl);
                await handleUrlSubmit();
            }
        };
        void handleControlFileUrl();
    }, [
        uploadControlFileUrl,
        handleUrlSubmit
    ]);
    useEffect(()=>{
        const handleControlFile = ()=>{
            if (uploadControlFile) {
                handleFileChange({
                    file: uploadControlFile
                });
            }
        };
        void handleControlFile();
    }, [
        uploadControlFile,
        handleFileChange
    ]);
    return /*#__PURE__*/ _jsxDEV("div", {
        className: [
            fieldBaseClass,
            baseClass
        ].filter(Boolean).join(' '),
        children: [
            /*#__PURE__*/ _jsxDEV(FieldError, {
                message: errorMessage,
                showError: showError
            }, void 0, false, {
                fileName: "src/elements/Upload/index.tsx",
                lineNumber: 383,
                columnNumber: 7
            }, this),
            data && data.filename && !removedFile && /*#__PURE__*/ _jsxDEV(FileDetails, {
                collectionSlug: collectionSlug,
                customUploadActions: customActions,
                doc: data,
                enableAdjustments: showCrop || showFocalPoint,
                handleRemove: canRemoveUpload ? handleFileRemoval : undefined,
                hasImageSizes: hasImageSizes,
                hideRemoveFile: uploadConfig.hideRemoveFile,
                imageCacheTag: imageCacheTag,
                uploadConfig: uploadConfig
            }, void 0, false, {
                fileName: "src/elements/Upload/index.tsx",
                lineNumber: 385,
                columnNumber: 9
            }, this),
            (!uploadConfig.hideFileInputOnCreate && !data?.filename || removedFile) && /*#__PURE__*/ _jsxDEV("div", {
                className: `${baseClass}__upload`,
                children: [
                    !value && !showUrlInput && /*#__PURE__*/ _jsxDEV(Dropzone, {
                        onChange: handleFileSelection,
                        children: /*#__PURE__*/ _jsxDEV("div", {
                            className: `${baseClass}__dropzoneContent`,
                            children: [
                                /*#__PURE__*/ _jsxDEV("div", {
                                    className: `${baseClass}__dropzoneButtons`,
                                    children: [
                                        /*#__PURE__*/ _jsxDEV(Button, {
                                            buttonStyle: "pill",
                                            onClick: ()=>{
                                                if (inputRef.current) {
                                                    inputRef.current.click();
                                                }
                                            },
                                            size: "small",
                                            children: t('upload:selectFile')
                                        }, void 0, false, {
                                            fileName: "src/elements/Upload/index.tsx",
                                            lineNumber: 403,
                                            columnNumber: 19
                                        }, this),
                                        /*#__PURE__*/ _jsxDEV("input", {
                                            accept: acceptMimeTypes,
                                            "aria-hidden": "true",
                                            className: `${baseClass}__hidden-input`,
                                            hidden: true,
                                            onChange: (e)=>{
                                                if (e.target.files && e.target.files.length > 0) {
                                                    handleFileSelection(e.target.files);
                                                }
                                            },
                                            ref: inputRef,
                                            type: "file"
                                        }, void 0, false, {
                                            fileName: "src/elements/Upload/index.tsx",
                                            lineNumber: 414,
                                            columnNumber: 19
                                        }, this),
                                        uploadConfig?.pasteURL !== false && /*#__PURE__*/ _jsxDEV(Fragment, {
                                            children: [
                                                /*#__PURE__*/ _jsxDEV("span", {
                                                    className: `${baseClass}__orText`,
                                                    children: t('general:or')
                                                }, void 0, false, {
                                                    fileName: "src/elements/Upload/index.tsx",
                                                    lineNumber: 429,
                                                    columnNumber: 23
                                                }, this),
                                                /*#__PURE__*/ _jsxDEV(Button, {
                                                    buttonStyle: "pill",
                                                    onClick: ()=>{
                                                        setShowUrlInput(true);
                                                        setUploadControlFileUrl('');
                                                        setUploadControlFile(null);
                                                        setUploadControlFileName(null);
                                                    },
                                                    size: "small",
                                                    children: t('upload:pasteURL')
                                                }, void 0, false, {
                                                    fileName: "src/elements/Upload/index.tsx",
                                                    lineNumber: 430,
                                                    columnNumber: 23
                                                }, this)
                                            ]
                                        }, void 0, true, {
                                            fileName: "src/elements/Upload/index.tsx",
                                            lineNumber: 428,
                                            columnNumber: 21
                                        }, this),
                                        UploadControls ? UploadControls : null
                                    ]
                                }, void 0, true, {
                                    fileName: "src/elements/Upload/index.tsx",
                                    lineNumber: 402,
                                    columnNumber: 17
                                }, this),
                                /*#__PURE__*/ _jsxDEV("p", {
                                    className: `${baseClass}__dragAndDropText`,
                                    children: [
                                        t('general:or'),
                                        " ",
                                        t('upload:dragAndDrop')
                                    ]
                                }, void 0, true, {
                                    fileName: "src/elements/Upload/index.tsx",
                                    lineNumber: 447,
                                    columnNumber: 17
                                }, this)
                            ]
                        }, void 0, true, {
                            fileName: "src/elements/Upload/index.tsx",
                            lineNumber: 401,
                            columnNumber: 15
                        }, this)
                    }, void 0, false, {
                        fileName: "src/elements/Upload/index.tsx",
                        lineNumber: 400,
                        columnNumber: 13
                    }, this),
                    showUrlInput && /*#__PURE__*/ _jsxDEV(React.Fragment, {
                        children: [
                            /*#__PURE__*/ _jsxDEV("div", {
                                className: `${baseClass}__remote-file-wrap`,
                                children: [
                                    /* eslint-disable-next-line jsx-a11y/control-has-associated-label */ /*#__PURE__*/ _jsxDEV("input", {
                                        className: `${baseClass}__remote-file`,
                                        onChange: (e)=>{
                                            setFileUrl(e.target.value);
                                        },
                                        ref: urlInputRef,
                                        title: fileUrl,
                                        type: "text",
                                        value: fileUrl
                                    }, void 0, false, {
                                        fileName: "src/elements/Upload/index.tsx",
                                        lineNumber: 457,
                                        columnNumber: 17
                                    }, this),
                                    /*#__PURE__*/ _jsxDEV("div", {
                                        className: `${baseClass}__add-file-wrap`,
                                        children: /*#__PURE__*/ _jsxDEV("button", {
                                            className: `${baseClass}__add-file`,
                                            onClick: ()=>{
                                                void handleUrlSubmit();
                                            },
                                            type: "button",
                                            children: t('upload:addFile')
                                        }, void 0, false, {
                                            fileName: "src/elements/Upload/index.tsx",
                                            lineNumber: 468,
                                            columnNumber: 19
                                        }, this)
                                    }, void 0, false, {
                                        fileName: "src/elements/Upload/index.tsx",
                                        lineNumber: 467,
                                        columnNumber: 17
                                    }, this)
                                ]
                            }, void 0, true, {
                                fileName: "src/elements/Upload/index.tsx",
                                lineNumber: 455,
                                columnNumber: 15
                            }, this),
                            /*#__PURE__*/ _jsxDEV(Button, {
                                buttonStyle: "icon-label",
                                className: `${baseClass}__remove`,
                                icon: "x",
                                iconStyle: "with-border",
                                onClick: ()=>{
                                    setShowUrlInput(false);
                                    setUploadControlFileUrl('');
                                    setUploadControlFile(null);
                                    setUploadControlFileName(null);
                                },
                                round: true,
                                tooltip: t('general:cancel')
                            }, void 0, false, {
                                fileName: "src/elements/Upload/index.tsx",
                                lineNumber: 479,
                                columnNumber: 15
                            }, this)
                        ]
                    }, void 0, true, {
                        fileName: "src/elements/Upload/index.tsx",
                        lineNumber: 454,
                        columnNumber: 13
                    }, this),
                    value && fileSrc && /*#__PURE__*/ _jsxDEV(React.Fragment, {
                        children: [
                            /*#__PURE__*/ _jsxDEV("div", {
                                className: `${baseClass}__thumbnail-wrap`,
                                children: /*#__PURE__*/ _jsxDEV(Thumbnail, {
                                    collectionSlug: collectionSlug,
                                    fileSrc: isImage(value.type) ? fileSrc : null
                                }, void 0, false, {
                                    fileName: "src/elements/Upload/index.tsx",
                                    lineNumber: 498,
                                    columnNumber: 17
                                }, this)
                            }, void 0, false, {
                                fileName: "src/elements/Upload/index.tsx",
                                lineNumber: 497,
                                columnNumber: 15
                            }, this),
                            /*#__PURE__*/ _jsxDEV("div", {
                                className: `${baseClass}__file-adjustments`,
                                children: [
                                    /* eslint-disable-next-line jsx-a11y/control-has-associated-label */ /*#__PURE__*/ _jsxDEV("input", {
                                        className: `${baseClass}__filename`,
                                        onChange: handleFileNameChange,
                                        title: filename || value.name,
                                        type: "text",
                                        value: filename || value.name
                                    }, void 0, false, {
                                        fileName: "src/elements/Upload/index.tsx",
                                        lineNumber: 505,
                                        columnNumber: 17
                                    }, this),
                                    /*#__PURE__*/ _jsxDEV(UploadActions, {
                                        customActions: customActions,
                                        enableAdjustments: showCrop || showFocalPoint,
                                        enablePreviewSizes: hasImageSizes && data?.filename && !removedFile,
                                        mimeType: value.type
                                    }, void 0, false, {
                                        fileName: "src/elements/Upload/index.tsx",
                                        lineNumber: 512,
                                        columnNumber: 17
                                    }, this)
                                ]
                            }, void 0, true, {
                                fileName: "src/elements/Upload/index.tsx",
                                lineNumber: 503,
                                columnNumber: 15
                            }, this),
                            /*#__PURE__*/ _jsxDEV(Button, {
                                buttonStyle: "icon-label",
                                className: `${baseClass}__remove`,
                                icon: "x",
                                iconStyle: "with-border",
                                onClick: handleFileRemoval,
                                round: true,
                                tooltip: t('general:cancel')
                            }, void 0, false, {
                                fileName: "src/elements/Upload/index.tsx",
                                lineNumber: 519,
                                columnNumber: 15
                            }, this)
                        ]
                    }, void 0, true, {
                        fileName: "src/elements/Upload/index.tsx",
                        lineNumber: 496,
                        columnNumber: 13
                    }, this)
                ]
            }, void 0, true, {
                fileName: "src/elements/Upload/index.tsx",
                lineNumber: 398,
                columnNumber: 9
            }, this),
            (value || data?.filename) && /*#__PURE__*/ _jsxDEV(EditDepthProvider, {
                children: /*#__PURE__*/ _jsxDEV(Drawer, {
                    Header: null,
                    slug: editDrawerSlug,
                    children: /*#__PURE__*/ _jsxDEV(EditUpload, {
                        fileName: value?.name || data?.filename,
                        fileSrc: data?.url || fileSrc,
                        imageCacheTag: imageCacheTag,
                        initialCrop: uploadEdits?.crop ?? undefined,
                        initialFocalPoint: {
                            x: uploadEdits?.focalPoint?.x || data?.focalX || 50,
                            y: uploadEdits?.focalPoint?.y || data?.focalY || 50
                        },
                        onSave: onEditsSave,
                        showCrop: showCrop,
                        showFocalPoint: showFocalPoint
                    }, void 0, false, {
                        fileName: "src/elements/Upload/index.tsx",
                        lineNumber: 535,
                        columnNumber: 13
                    }, this)
                }, void 0, false, {
                    fileName: "src/elements/Upload/index.tsx",
                    lineNumber: 534,
                    columnNumber: 11
                }, this)
            }, void 0, false, {
                fileName: "src/elements/Upload/index.tsx",
                lineNumber: 533,
                columnNumber: 9
            }, this),
            data && hasImageSizes && /*#__PURE__*/ _jsxDEV(Drawer, {
                className: `${baseClass}__previewDrawer`,
                hoverTitle: true,
                slug: sizePreviewSlug,
                title: t('upload:sizesFor', {
                    label: data.filename
                }),
                children: /*#__PURE__*/ _jsxDEV(PreviewSizes, {
                    doc: data,
                    imageCacheTag: imageCacheTag,
                    uploadConfig: uploadConfig
                }, void 0, false, {
                    fileName: "src/elements/Upload/index.tsx",
                    lineNumber: 558,
                    columnNumber: 11
                }, this)
            }, void 0, false, {
                fileName: "src/elements/Upload/index.tsx",
                lineNumber: 552,
                columnNumber: 9
            }, this)
        ]
    }, void 0, true, {
        fileName: "src/elements/Upload/index.tsx",
        lineNumber: 382,
        columnNumber: 5
    }, this);
};

//# sourceMappingURL=index.js.map