/**
 * YooTheme Field Controller for Universal DAM
 *
 * Integrates the DAM picker with YooTheme's customizer interface.
 * Uses window.damPickerBridge to open the DAM picker and handle asset selection.
 */

(function($) {
    'use strict';

    /**
     * DAM Field Controller for YooTheme
     * Handles both single and multiple asset selection
     */
    class DamFieldController {
        constructor(element) {
            this.$element = $(element);
            this.$input = this.$element.find('input[type="hidden"]');
            this.$preview = this.$element.find('.dam-preview');
            this.$selectBtn = this.$element.find('.dam-select-btn');
            this.$removeBtn = this.$element.find('.dam-remove-btn');
            this.multiple = this.$element.data('multiple') || false;

            this.init();
        }

        init() {
            // Bind event handlers
            this.$selectBtn.on('click', this.handleSelectClick.bind(this));
            this.$removeBtn.on('click', this.handleRemoveClick.bind(this));

            // Initialize preview if value exists
            const currentValue = this.$input.val();
            if (currentValue) {
                this.updatePreview(currentValue);
            }
        }

        /**
         * Handle select button click - opens DAM picker
         */
        handleSelectClick(e) {
            e.preventDefault();

            if (!window.damPickerBridge) {
                console.error('DAM Picker Bridge not available');
                alert('DAM asset picker is not available. Please ensure the DAM admin app is loaded.');
                return;
            }

            // Open DAM picker with configuration
            window.damPickerBridge.openPicker({
                multiple: this.multiple,
                onSelect: this.handleAssetSelection.bind(this)
            });
        }

        /**
         * Handle asset selection from DAM picker
         * @param {Object|Array} selection - Selected asset(s)
         */
        handleAssetSelection(selection) {
            if (this.multiple) {
                // Multiple selection - array of assets
                if (!Array.isArray(selection) || selection.length === 0) {
                    return;
                }

                // Extract asset IDs
                const assetIds = selection.map(asset => asset.uuid || asset.id);
                const assetData = selection.map(asset => ({
                    id: asset.uuid || asset.id,
                    url: asset.url || asset.cloudfront_url,
                    thumbnail: asset.thumbnail_url,
                    filename: asset.filename,
                    mime_type: asset.mime_type
                }));

                // Update field value (comma-separated IDs for multiple)
                this.$input.val(assetIds.join(',')).trigger('change');

                // Update preview
                this.updatePreview(assetData);

            } else {
                // Single selection
                if (!selection || (!selection.uuid && !selection.id)) {
                    return;
                }

                const assetData = {
                    id: selection.uuid || selection.id,
                    url: selection.url || selection.cloudfront_url,
                    thumbnail: selection.thumbnail_url,
                    filename: selection.filename,
                    mime_type: selection.mime_type
                };

                // Update field value
                this.$input.val(assetData.id).trigger('change');

                // Update preview
                this.updatePreview(assetData);
            }

            // Show remove button
            this.$removeBtn.show();
        }

        /**
         * Handle remove button click
         */
        handleRemoveClick(e) {
            e.preventDefault();

            // Clear field value
            this.$input.val('').trigger('change');

            // Clear preview
            this.$preview.html('');

            // Hide remove button
            this.$removeBtn.hide();
        }

        /**
         * Update preview display
         * @param {Object|Array|String} value - Asset data or ID(s)
         */
        updatePreview(value) {
            // If value is a string (asset ID), fetch asset data
            if (typeof value === 'string') {
                this.fetchAndDisplayAsset(value);
                return;
            }

            // If value is array (multiple assets)
            if (Array.isArray(value)) {
                this.displayMultipleAssets(value);
                return;
            }

            // If value is object (single asset)
            if (typeof value === 'object') {
                this.displaySingleAsset(value);
                return;
            }
        }

        /**
         * Fetch asset data and display
         * @param {String} assetIds - Comma-separated asset IDs
         */
        fetchAndDisplayAsset(assetIds) {
            if (!assetIds) {
                this.$preview.html('');
                return;
            }

            // Show loading state
            this.$preview.html('<div class="dam-loading">Loading asset preview...</div>');

            // Use DAM bridge to fetch asset data
            if (window.damPickerBridge && window.damPickerBridge.getAssetData) {
                const ids = assetIds.split(',');

                Promise.all(ids.map(id => window.damPickerBridge.getAssetData(id)))
                    .then(assets => {
                        if (this.multiple) {
                            this.displayMultipleAssets(assets);
                        } else {
                            this.displaySingleAsset(assets[0]);
                        }
                    })
                    .catch(error => {
                        console.error('Failed to fetch asset data:', error);
                        this.$preview.html('<div class="dam-error">Failed to load asset preview</div>');
                    });
            } else {
                // Fallback: Display asset ID only
                this.$preview.html(`<div class="dam-asset-id">Asset ID: ${assetIds}</div>`);
            }
        }

        /**
         * Display single asset preview
         * @param {Object} asset - Asset data
         */
        displaySingleAsset(asset) {
            if (!asset) {
                this.$preview.html('');
                return;
            }

            const thumbnailUrl = asset.thumbnail_url || asset.url || '';
            const filename = asset.filename || 'Unknown file';
            const isImage = asset.mime_type && asset.mime_type.startsWith('image/');

            const previewHtml = `
                <div class="dam-asset-preview">
                    ${isImage ? `
                        <img src="${thumbnailUrl}" alt="${filename}" class="dam-preview-image">
                    ` : `
                        <div class="dam-preview-file">
                            <span class="dam-file-icon">${this.getFileIcon(asset.mime_type)}</span>
                        </div>
                    `}
                    <div class="dam-asset-info">
                        <div class="dam-filename">${filename}</div>
                    </div>
                </div>
            `;

            this.$preview.html(previewHtml);
        }

        /**
         * Display multiple assets preview
         * @param {Array} assets - Array of asset data
         */
        displayMultipleAssets(assets) {
            if (!assets || assets.length === 0) {
                this.$preview.html('');
                return;
            }

            const previewsHtml = assets.map(asset => {
                const thumbnailUrl = asset.thumbnail_url || asset.url || '';
                const filename = asset.filename || 'Unknown file';
                const isImage = asset.mime_type && asset.mime_type.startsWith('image/');

                return `
                    <div class="dam-asset-preview-item">
                        ${isImage ? `
                            <img src="${thumbnailUrl}" alt="${filename}" class="dam-preview-thumbnail">
                        ` : `
                            <div class="dam-preview-file-small">
                                <span class="dam-file-icon">${this.getFileIcon(asset.mime_type)}</span>
                            </div>
                        `}
                    </div>
                `;
            }).join('');

            const containerHtml = `
                <div class="dam-assets-preview-multiple">
                    ${previewsHtml}
                    <div class="dam-asset-count">${assets.length} asset${assets.length !== 1 ? 's' : ''}</div>
                </div>
            `;

            this.$preview.html(containerHtml);
        }

        /**
         * Get file icon based on MIME type
         * @param {String} mimeType - MIME type
         * @returns {String} Icon HTML or character
         */
        getFileIcon(mimeType) {
            if (!mimeType) return '📄';

            if (mimeType.startsWith('image/')) return '🖼️';
            if (mimeType.startsWith('video/')) return '🎥';
            if (mimeType.startsWith('audio/')) return '🎵';
            if (mimeType.includes('pdf')) return '📕';
            if (mimeType.includes('document') || mimeType.includes('word')) return '📝';
            if (mimeType.includes('spreadsheet') || mimeType.includes('excel')) return '📊';
            if (mimeType.includes('presentation') || mimeType.includes('powerpoint')) return '📽️';

            return '📄';
        }
    }

    /**
     * Initialize DAM field controllers on YooTheme fields
     */
    function initDamFields() {
        $('.dam-field-controller').each(function() {
            if (!$(this).data('dam-controller')) {
                const controller = new DamFieldController(this);
                $(this).data('dam-controller', controller);
            }
        });
    }

    // Initialize on document ready
    $(document).ready(function() {
        initDamFields();

        // Re-initialize when YooTheme customizer adds new fields
        if (window.UIkit) {
            UIkit.util.on(document, 'beforeshow', '.uk-modal', function() {
                setTimeout(initDamFields, 100);
            });
        }
    });

    // Expose for manual initialization if needed
    window.DamFieldController = DamFieldController;
    window.initDamFields = initDamFields;

})(jQuery);
