'use strict';

var React = require('react');

/**
 * dragDrop.ts — External drag & drop support for editors.
 *
 * Handles file/image drops from the OS or other applications
 * into the editor canvas area.
 */
// ── File Processing ─────────────────────────────────────────────
async function fileToImageData(file) {
    if (!file.type.startsWith("image/"))
        return null;
    return new Promise((resolve) => {
        const img = new Image();
        const url = URL.createObjectURL(file);
        img.onload = () => {
            const canvas = document.createElement("canvas");
            canvas.width = img.width;
            canvas.height = img.height;
            const ctx = canvas.getContext("2d");
            if (!ctx) {
                resolve(null);
                return;
            }
            ctx.drawImage(img, 0, 0);
            resolve(ctx.getImageData(0, 0, img.width, img.height));
            URL.revokeObjectURL(url);
        };
        img.onerror = () => { resolve(null); URL.revokeObjectURL(url); };
        img.src = url;
    });
}
function validateFile(file, config) {
    var _a;
    const maxSize = (_a = config.maxSize) !== null && _a !== void 0 ? _a : 50 * 1024 * 1024;
    if (file.size > maxSize) {
        return `File "${file.name}" exceeds maximum size of ${Math.round(maxSize / 1024 / 1024)}MB`;
    }
    if (config.accept && config.accept.length > 0) {
        const accepted = config.accept.some((mime) => {
            if (mime.endsWith("/*")) {
                return file.type.startsWith(mime.slice(0, -1));
            }
            return file.type === mime;
        });
        if (!accepted) {
            return `File type "${file.type}" is not accepted`;
        }
    }
    return null;
}
/** React hook for handling external file/image drag & drop. */
function useDragDrop(config) {
    const [isDragging, setIsDragging] = React.useState(false);
    const dragCounter = React.useRef(0);
    const handleDragEnter = React.useCallback((e) => {
        var _a;
        e.preventDefault();
        e.stopPropagation();
        dragCounter.current++;
        if (dragCounter.current === 1) {
            setIsDragging(true);
            (_a = config.onDragEnter) === null || _a === void 0 ? void 0 : _a.call(config);
        }
    }, [config]);
    const handleDragOver = React.useCallback((e) => {
        e.preventDefault();
        e.stopPropagation();
        e.dataTransfer.dropEffect = "copy";
    }, []);
    const handleDragLeave = React.useCallback((e) => {
        var _a;
        e.preventDefault();
        e.stopPropagation();
        dragCounter.current--;
        if (dragCounter.current === 0) {
            setIsDragging(false);
            (_a = config.onDragLeave) === null || _a === void 0 ? void 0 : _a.call(config);
        }
    }, [config]);
    const handleDrop = React.useCallback(async (e) => {
        var _a, _b, _c;
        e.preventDefault();
        e.stopPropagation();
        dragCounter.current = 0;
        setIsDragging(false);
        const dt = e.dataTransfer;
        const maxFiles = (_a = config.maxFiles) !== null && _a !== void 0 ? _a : 10;
        const files = [];
        const urls = [];
        // Collect files
        for (let i = 0; i < Math.min(dt.files.length, maxFiles); i++) {
            const file = dt.files[i];
            const error = validateFile(file, config);
            if (error) {
                (_b = config.onError) === null || _b === void 0 ? void 0 : _b.call(config, error);
                return;
            }
            files.push(file);
        }
        // Collect URLs from text/uri-list
        const uriList = dt.getData("text/uri-list");
        if (uriList) {
            for (const line of uriList.split("\n")) {
                const trimmed = line.trim();
                if (trimmed && !trimmed.startsWith("#")) {
                    try {
                        new URL(trimmed);
                        urls.push(trimmed);
                    }
                    catch ( /* not a valid URL */_d) { /* not a valid URL */ }
                }
            }
        }
        const text = dt.getData("text/plain") || undefined;
        // Convert image files to ImageData
        const images = [];
        for (const file of files) {
            const imgData = await fileToImageData(file);
            if (imgData)
                images.push(imgData);
        }
        (_c = config.onDrop) === null || _c === void 0 ? void 0 : _c.call(config, { files, images, text, urls });
    }, [config]);
    return {
        isDragging,
        dragProps: {
            onDragEnter: handleDragEnter,
            onDragOver: handleDragOver,
            onDragLeave: handleDragLeave,
            onDrop: handleDrop,
        },
    };
}
/** Visual overlay shown when dragging files over the editor. */
const DropZoneOverlay = ({ isDragging, message }) => {
    if (!isDragging)
        return null;
    return React.createElement("div", {
        style: {
            position: "absolute",
            inset: 0,
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            background: "rgba(59, 130, 246, 0.15)",
            border: "2px dashed rgba(59, 130, 246, 0.6)",
            borderRadius: 8,
            zIndex: 999,
            pointerEvents: "none",
        },
    }, React.createElement("div", {
        style: {
            padding: "16px 32px",
            background: "rgba(255,255,255,0.95)",
            borderRadius: 8,
            fontSize: 14,
            fontWeight: 600,
            color: "#3b82f6",
        },
    }, message !== null && message !== void 0 ? message : "Drop files here"));
};

exports.DropZoneOverlay = DropZoneOverlay;
exports.useDragDrop = useDragDrop;
//# sourceMappingURL=dragDrop.js.map
