/**
 * RSL Drag and Drop Image Upload
 *
 * Provides drag-and-drop file upload functionality with image preview support.
 * Supports both legacy ID-based implementation and modern class-based components.
 * Creates visual previews for images and file icons for non-image files.
 *
 * @fileoverview Drag-and-drop file upload with image preview
 * @version 2.0.0
 * @license MIT
 *
 * Key Features:
 * - Drag and drop file upload with visual feedback
 * - Image preview with thumbnail generation
 * - Non-image file handling with icons and filenames
 * - Click to upload as fallback option
 * - Individual file deletion from preview
 * - Automatic memory cleanup (URL.revokeObjectURL)
 * - Dragover visual state indication
 * - Support for multiple files
 * - Legacy and modern implementation support
 * - Integration with RSL file tile components
 *
 * Usage:
 * // Modern implementation (recommended):
 * <div class="rsl-file-tile" data-enable-preview="true">
 *   <label class="rsl-file-label">Drag files here or click to upload</label>
 *   <input type="file" class="rsl-file-input" multiple>
 *   <!-- Preview container auto-generated -->
 * </div>
 *
 * // Legacy implementation (for backward compatibility):
 * <div id="drag-and-drop-area">Drop files here</div>
 * <div id="file-preview"></div>
 *
 * Preview item structure (auto-generated):
 * <div class="rsl-dnd__preview-item">
 *   <img class="rsl-dnd__preview-img" src="blob:..."> // For images
 *   // OR for non-images:
 *   <div class="rsl-dnd__preview-file-icon"><i class="fa-solid fa-file"></i></div>
 *   <div class="rsl-dnd__preview-file-name">filename.pdf</div>
 *   <span class="rsl-dnd__preview-delete">×</span>
 * </div>
 *
 * Public API:
 * All functionality is automatically initialized on DOMContentLoaded.
 * No manual JavaScript API required - works through HTML structure.
 */

(function() {
    'use strict';

    /**
     * Initialize drag-and-drop on DOM ready
     */
    document.addEventListener('DOMContentLoaded', init);

    /**
     * Main initialization function
     * Sets up both legacy and modern drag-and-drop implementations
     */
    function init() {
        initLegacyDragDrop();
        initModernFileTiles();
    }

    /**
     * Initialize legacy ID-based drag-and-drop area
     *
     * Provides backward compatibility for older implementations using
     * #drag-and-drop-area and #file-preview IDs. Sets up drag events,
     * click-to-upload, and file handling.
     *
     * @example
     * <div id="drag-and-drop-area">Drop files here</div>
     * <div id="file-preview"></div>
     */
    function initLegacyDragDrop() {
        const dndArea = document.getElementById('drag-and-drop-area');
        const filePreview = document.getElementById('file-preview');

        if (!dndArea || !filePreview) return;

        /**
         * Handle dragover event
         * Prevents default behavior and adds visual feedback
         * @param {DragEvent} event - Drag event
         */
        dndArea.addEventListener('dragover', (event) => {
            event.preventDefault();
            dndArea.classList.add('dragover');
        });

        /**
         * Handle dragleave event
         * Removes visual feedback when drag leaves area
         */
        dndArea.addEventListener('dragleave', () => {
            dndArea.classList.remove('dragover');
        });

        /**
         * Handle drop event
         * Processes dropped files and creates previews
         * @param {DragEvent} event - Drop event
         */
        dndArea.addEventListener('drop', (event) => {
            event.preventDefault();
            dndArea.classList.remove('dragover');
            const files = event.dataTransfer.files;
            handleFilesLegacy(files, filePreview);
        });

        /**
         * Handle click to upload
         * Creates temporary file input for manual file selection
         */
        dndArea.addEventListener('click', () => {
            const input = document.createElement('input');
            input.type = 'file';
            input.multiple = true;
            input.addEventListener('change', () => {
                handleFilesLegacy(input.files, filePreview);
            });
            input.click();
        });
    }

    /**
     * Initialize modern file tile components
     *
     * Sets up drag-and-drop functionality for .rsl-file-tile elements
     * with data-enable-preview="true". Creates preview containers and
     * handles both drag-drop and input change events.
     *
     * @example
     * <div class="rsl-file-tile" data-enable-preview="true">
     *   <label class="rsl-file-label">Upload</label>
     *   <input type="file" class="rsl-file-input" multiple>
     * </div>
     */
    function initModernFileTiles() {
        const fileTiles = document.querySelectorAll('.rsl-file-tile[data-enable-preview="true"]');

        fileTiles.forEach(tile => {
            const fileInput = tile.querySelector('.rsl-file-input');

            if (!fileInput) return;

            // Create or get preview container
            let previewContainer = tile.querySelector('.rsl-file-preview');
            if (!previewContainer) {
                previewContainer = document.createElement('div');
                previewContainer.classList.add('rsl-file-preview');
                tile.appendChild(previewContainer);
            }

            /**
             * Handle dragover event on tile
             * @param {DragEvent} event - Drag event
             */
            tile.addEventListener('dragover', (event) => {
                event.preventDefault();
                tile.classList.add('dragover');
            });

            /**
             * Handle dragleave event on tile
             */
            tile.addEventListener('dragleave', () => {
                tile.classList.remove('dragover');
            });

            /**
             * Handle drop event on tile
             * @param {DragEvent} event - Drop event
             */
            tile.addEventListener('drop', (event) => {
                event.preventDefault();
                tile.classList.remove('dragover');
                const files = event.dataTransfer.files;
                handleFilesModern(files, previewContainer, fileInput);
            });

            /**
             * Handle file input change
             */
            fileInput.addEventListener('change', () => {
                if (fileInput.files && fileInput.files.length > 0) {
                    handleFilesModern(fileInput.files, previewContainer, fileInput);
                }
            });
        });
    }

    /**
     * Handle files for legacy implementation
     *
     * Processes FileList and appends preview items to container.
     * Does not clear existing previews (additive behavior).
     *
     * @param {FileList} files - Files to process
     * @param {HTMLElement} previewContainer - Container for preview items
     *
     * @example
     * handleFilesLegacy(event.dataTransfer.files, previewElement);
     */
    function handleFilesLegacy(files, previewContainer) {
        for (let i = 0; i < files.length; i++) {
            const file = files[i];
            const previewItem = createPreviewItem(file);
            previewContainer.appendChild(previewItem);
        }
    }

    /**
     * Handle files for modern implementation
     *
     * Processes FileList, clears existing previews, and creates new preview items.
     * Replaces all previews on each upload (replacement behavior).
     *
     * @param {FileList} files - Files to process
     * @param {HTMLElement} previewContainer - Container for preview items
     * @param {HTMLInputElement} fileInput - File input element (for future use)
     *
     * @example
     * handleFilesModern(event.dataTransfer.files, previewElement, inputElement);
     */
    function handleFilesModern(files, previewContainer, fileInput) {
        // Clear existing previews
        previewContainer.innerHTML = '';

        for (let i = 0; i < files.length; i++) {
            const file = files[i];
            const previewItem = createPreviewItem(file);
            previewContainer.appendChild(previewItem);
        }
    }

    /**
     * Create a preview item element for a file
     *
     * Generates a preview DOM element with:
     * - Image thumbnail for image files (with blob URL)
     * - File icon and name for non-image files
     * - Delete button with click handler
     * - Automatic memory cleanup for blob URLs
     *
     * @param {File} file - File object to create preview for
     * @returns {HTMLElement} Preview item element with image/icon and delete button
     *
     * @example
     * const preview = createPreviewItem(file);
     * container.appendChild(preview);
     */
    function createPreviewItem(file) {
        const item = document.createElement('div');
        item.classList.add('rsl-dnd__preview-item');

        // Handle image files
        if (file.type.startsWith('image/')) {
            const img = document.createElement('img');
            img.classList.add('rsl-dnd__preview-img');
            img.src = URL.createObjectURL(file);

            // Clean up blob URL after image loads to prevent memory leaks
            img.onload = () => {
                URL.revokeObjectURL(img.src);
            };

            item.appendChild(img);
        } else {
            // Handle non-image files
            const fileIcon = document.createElement('div');
            fileIcon.classList.add('rsl-dnd__preview-file-icon');
            fileIcon.innerHTML = '<i class="fa-solid fa-file"></i>';
            item.appendChild(fileIcon);

            const fileName = document.createElement('div');
            fileName.classList.add('rsl-dnd__preview-file-name');
            fileName.textContent = file.name;
            item.appendChild(fileName);
        }

        // Create delete button
        const deleteButton = document.createElement('span');
        deleteButton.classList.add('rsl-dnd__preview-delete');
        deleteButton.textContent = '×';

        /**
         * Handle delete button click
         * Removes preview item from DOM
         */
        deleteButton.addEventListener('click', () => {
            item.remove();
        });

        item.appendChild(deleteButton);

        return item;
    }

})();
