/// <reference types="@dhwaniapp/plugin-sdk" />

(function () {
    const React = window.React;
    const { Node, ReactNodeViewRenderer, NodeViewWrapper } = window.DhwaniEditorSDK;
    const { useState, useEffect, useRef } = React;

    function CarouselComponent(props) {
        const { node, updateAttributes } = props;
        const { images = [] } = node.attrs;
        const [isDragging, setIsDragging] = useState(false);
        const [imageWidths, setImageWidths] = useState({});
        const fileInputRef = useRef(null);

        // Get contentId via scoped SDK
        const contentId = sdk ? sdk.api.getCurrentContentId() : "temp-carousel-id";

        // Normalize images to always be an array of objects: { url: string, width?: number }
        const imagesArray = Array.isArray(images)
            ? images.map(img => typeof img === 'string' ? { url: img } : img)
            : (typeof images === 'string' && images ? images.split(',').filter(Boolean).map(url => ({ url })) : []);

        // Synchronize local width state with node attributes
        useEffect(() => {
            const widths = {};
            imagesArray.forEach((img, i) => {
                widths[i] = img.width || 560;
            });
            setImageWidths(widths);
        }, [images]);

        const handleDragOver = (e) => {
            e.preventDefault();
            setIsDragging(true);
        };

        const handleDragLeave = () => {
            setIsDragging(false);
        };

        const uploadFiles = async (files) => {
            const imageFiles = Array.from(files).filter(file => file.type.startsWith('image/'));
            if (imageFiles.length === 0) return;

            const newImages = [...imagesArray];
            for (const file of imageFiles) {
                try {
                    const arrayBuffer = await file.arrayBuffer();
                    const attachment = await sdk.api.saveAttachment(contentId, arrayBuffer, file.name);
                    newImages.push({
                        url: attachment.file_path,
                        width: 560 // default width (double of 280)
                    });
                } catch (err) {
                    console.error("[CarouselPlugin] Failed to save attachment:", err);
                }
            }
            updateAttributes({ images: newImages });
        };

        const handleDrop = async (e) => {
            e.preventDefault();
            setIsDragging(false);
            if (e.dataTransfer.files) {
                await uploadFiles(e.dataTransfer.files);
            }
        };

        const handleFileSelect = async (e) => {
            if (e.target.files) {
                await uploadFiles(e.target.files);
            }
        };

        const handleRemoveImage = async (index, url) => {
            const newImages = imagesArray.filter((_, i) => i !== index);
            updateAttributes({ images: newImages });

            try {
                const fileName = url.replace("dhwani-attachment://", "");
                const id = fileName.split(".")[0];
                await sdk.api.deleteAttachment(id);
                console.log("[CarouselPlugin] Attachment deleted:", id);
            } catch (err) {
                console.warn("[CarouselPlugin] Failed to delete attachment from disk:", err);
            }
        };

        // Resize handler using mouse drag
        const handleMouseDown = (index, e) => {
            e.preventDefault();
            const startX = e.clientX;
            const startWidth = imageWidths[index] || 560;

            const handleMouseMove = (moveEvent) => {
                const currentWidth = Math.max(200, Math.min(1200, startWidth + (moveEvent.clientX - startX)));
                setImageWidths(prev => ({
                    ...prev,
                    [index]: currentWidth
                }));
            };

            const handleMouseUp = (upEvent) => {
                window.removeEventListener('mousemove', handleMouseMove);
                window.removeEventListener('mouseup', handleMouseUp);

                const finalWidth = Math.max(200, Math.min(1200, startWidth + (upEvent.clientX - startX)));
                const newImages = imagesArray.map((img, i) => {
                    if (i === index) {
                        return { ...img, width: finalWidth };
                    }
                    return img;
                });
                updateAttributes({ images: newImages });
            };

            window.addEventListener('mousemove', handleMouseMove);
            window.addEventListener('mouseup', handleMouseUp);
        };

        // Render Empty/Upload state
        if (imagesArray.length === 0) {
            return React.createElement(
                NodeViewWrapper,
                { className: "my-4" },
                React.createElement(
                    "div",
                    {
                        onDragOver: handleDragOver,
                        onDragLeave: handleDragLeave,
                        onDrop: handleDrop,
                        onClick: () => fileInputRef.current && fileInputRef.current.click(),
                        className: "flex flex-col items-center justify-center p-8 border-2 border-dashed rounded-xl cursor-pointer transition-all " +
                            (isDragging ? "border-primary bg-primary/10" : "border-base-300 hover:border-primary/50 hover:bg-base-200/30")
                    },
                    React.createElement(
                        "svg",
                        {
                            className: "w-10 h-10 text-gray-400 mb-2",
                            fill: "none",
                            viewBox: "0 0 24 24",
                            stroke: "currentColor",
                            strokeWidth: "1.5"
                        },
                        React.createElement("path", {
                            strokeLinecap: "round",
                            strokeLinejoin: "round",
                            d: "M2.25 15.75l5.159-5.159a2.25 2.25 0 013.182 0l5.159 5.159m-1.5-1.5l1.409-1.409a2.25 2.25 0 013.182 0l2.9 2.9m-18 3.75h16.5a1.5 1.5 0 001.5-1.5V6a1.5 1.5 0 00-1.5-1.5H3.75A1.5 1.5 0 002.25 6v12a1.5 1.5 0 001.5 1.5zm10.5-11.25h.008v.008h-.008V8.25zm.375 0a.375.375 0 11-.75 0 .375.375 0 01.75 0z"
                        })
                    ),
                    React.createElement("span", { className: "text-sm font-medium text-base-content/80" }, "Drag & drop images here"),
                    React.createElement("span", { className: "text-xs text-gray-400 mt-1" }, "or click to browse files"),
                    React.createElement("input", {
                        ref: fileInputRef,
                        type: "file",
                        multiple: true,
                        accept: "image/*",
                        onChange: handleFileSelect,
                        className: "hidden"
                    })
                )
            );
        }

        // Render Carousel state
        return React.createElement(
            NodeViewWrapper,
            { className: "my-6 relative group border border-base-300 rounded-2xl p-4 bg-base-100/40 shadow-sm" },
            // Settings header
            React.createElement(
                "div",
                { className: "flex items-center justify-between gap-4 mb-3" },
                React.createElement(
                    "div",
                    { className: "flex items-center gap-1.5 text-xs font-semibold text-gray-400 uppercase tracking-wider" },
                    React.createElement(
                        "svg",
                        {
                            className: "w-4 h-4 text-primary",
                            fill: "none",
                            viewBox: "0 0 24 24",
                            stroke: "currentColor",
                            strokeWidth: "2"
                        },
                        React.createElement("path", {
                            strokeLinecap: "round",
                            strokeLinejoin: "round",
                            d: "M2.25 15.75l5.159-5.159a2.25 2.25 0 013.182 0l5.159 5.159m-1.5-1.5l1.409-1.409a2.25 2.25 0 013.182 0l2.9 2.9m-18 3.75h16.5a1.5 1.5 0 001.5-1.5V6a1.5 1.5 0 00-1.5-1.5H3.75A1.5 1.5 0 002.25 6v12a1.5 1.5 0 001.5 1.5zm10.5-11.25h.008v.008h-.008V8.25zm.375 0a.375.375 0 11-.75 0 .375.375 0 01.75 0z"
                        })
                    ),
                    "Image Carousel (Snap to Center)"
                ),
                React.createElement(
                    "button",
                    {
                        onClick: () => fileInputRef.current && fileInputRef.current.click(),
                        className: "btn btn-xs btn-outline btn-primary font-medium px-2.5"
                    },
                    "Add Images"
                ),
                React.createElement("input", {
                    ref: fileInputRef,
                    type: "file",
                    multiple: true,
                    accept: "image/*",
                    onChange: handleFileSelect,
                    className: "hidden"
                })
            ),
            // Carousel container
            React.createElement(
                "div",
                {
                    onDragOver: handleDragOver,
                    onDragLeave: handleDragLeave,
                    onDrop: handleDrop,
                    className: "carousel carousel-center flex flex-row w-full overflow-x-auto rounded-xl gap-4 py-3 bg-base-200/50 " +
                        (isDragging ? " border-2 border-dashed border-primary bg-primary/5" : "border border-base-200")
                },
                imagesArray.map((img, index) => {
                    const currentWidth = imageWidths[index] || 560;
                    return React.createElement(
                        "div",
                        {
                            key: index,
                            className: "carousel-item relative rounded-lg overflow-hidden group/item border border-base-300 bg-base-100 shrink-0 shadow-sm transition-shadow hover:shadow-md",
                            style: {
                                width: currentWidth + "px",
                                height: "360px"
                            }
                        },
                        React.createElement("img", {
                            src: img.url,
                            className: "w-full h-full object-cover select-none pointer-events-none",
                            loading: "lazy"
                        }),
                        // Remove button overlay
                        React.createElement(
                            "button",
                            {
                                onClick: () => handleRemoveImage(index, img.url),
                                className: "absolute top-2 right-2 p-1.5 rounded-full bg-error text-error-content opacity-0 group-hover/item:opacity-100 hover:scale-105 transition-all shadow-md z-10"
                            },
                            React.createElement(
                                "svg",
                                {
                                    className: "w-3.5 h-3.5",
                                    fill: "none",
                                    viewBox: "0 0 24 24",
                                    stroke: "currentColor",
                                    strokeWidth: "2.5"
                                },
                                React.createElement("path", {
                                    strokeLinecap: "round",
                                    strokeLinejoin: "round",
                                    d: "M6 18L18 6M6 6l12 12"
                                })
                            )
                        ),
                        // Resize Handle (right edge)
                        React.createElement(
                            "div",
                            {
                                onMouseDown: (e) => handleMouseDown(index, e),
                                className: "absolute right-0 top-0 bottom-0 w-2 cursor-col-resize hover:bg-primary/40 active:bg-primary/60 opacity-0 group-hover/item:opacity-100 transition-opacity z-20"
                            }
                        )
                    );
                })
            )
        );
    }

    const CarouselNode = Node.create({
        name: "carousel",
        group: "block",
        atom: true,

        addAttributes() {
            return {
                images: {
                    default: [],
                    parseHTML: element => {
                        const val = element.getAttribute('images');
                        if (!val) return [];
                        try {
                            const parsed = JSON.parse(val);
                            return Array.isArray(parsed)
                                ? parsed.map(img => typeof img === 'string' ? { url: img } : img)
                                : [];
                        } catch (e) {
                            return val.split(',').filter(Boolean).map(url => ({ url }));
                        }
                    },
                    renderHTML: attributes => {
                        return {
                            images: JSON.stringify(attributes.images)
                        };
                    }
                },
                snap: {
                    default: "center",
                    parseHTML: element => element.getAttribute('snap') || 'center',
                    renderHTML: attributes => {
                        return {
                            snap: attributes.snap
                        };
                    }
                }
            };
        },

        parseHTML() {
            return [{ tag: 'div[data-type="carousel"]' }];
        },

        renderHTML({ HTMLAttributes }) {
            return ["div", window.DhwaniEditorSDK.mergeAttributes(HTMLAttributes, { "data-type": "carousel" })];
        },

        addNodeView() {
            return ReactNodeViewRenderer(CarouselComponent);
        }
    });

    sdk = window.Dhwani.registerPageExtension({
        name: "carousel",
        tiptapExtension: CarouselNode,
        slashCommand: {
            title: "Carousel",
            description: "Insert an image carousel",
            icon: `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-5 h-5"><path stroke-linecap="round" stroke-linejoin="round" d="M2.25 15.75l5.159-5.159a2.25 2.25 0 013.182 0l5.159 5.159m-1.5-1.5l1.409-1.409a2.25 2.25 0 013.182 0l2.9 2.9m-18 3.75h16.5a1.5 1.5 0 001.5-1.5V6a1.5 1.5 0 00-1.5-1.5H3.75A1.5 1.5 0 002.25 6v12a1.5 1.5 0 001.5 1.5zm10.5-11.25h.008v.008h-.008V8.25zm.375 0a.375.375 0 11-.75 0 .375.375 0 01.75 0z" /></svg>`,
            command: (editor) => {
                editor.chain().focus().insertContent({ type: "carousel" }).run();
            }
        }
    });
})();
