/**
 * Havenlytics File Field Handler
 * @package Havenlytics
 * @version 2.0.0
 */

(function($) {
    'use strict';

    class HavenlyticsFileField {
        constructor(fieldId, $container) {
            this.fieldId = fieldId;
            this.$container = $container;
            this.$input = $container.find('input[type="url"]');
            this.$uploadButton = $container.find('.hvnly-popup-upload-button');
            this.fileType = this.$uploadButton.data('type') || 'file';
            this.initialized = false;

            this.init();
        }

        init() {
            if (this.initialized) return;

            this.bindEvents();
            this.updatePreview();
            this.initialized = true;
        }

        bindEvents() {
            // Upload button
            this.$uploadButton.on('click', (e) => {
                e.preventDefault();
                this.openFileUploader();
            });

            // Manual input
            this.$input.on('input', () => {
                this.updatePreview();
            });

            // Remove preview - use event delegation
            this.$container.on('click', '.hvnly-popup-remove-preview', (e) => {
                e.preventDefault();
                this.removeFile();
            });
        }

        openFileUploader() {
            if (typeof wp === 'undefined' || typeof wp.media === 'undefined') {
                alert('Media uploader is not available.');
                return;
            }

            const allowedType = this.fileType === 'pdf' ? 'application/pdf' : 
                               this.fileType === 'image' ? 'image' : '';

            const frame = wp.media({
                title: this.fileType === 'image' ? 'Select Image' : 'Select File',
                button: { text: 'Use this file' },
                library: { type: allowedType },
                multiple: false
            });

            frame.on('select', () => {
                const attachment = frame.state().get('selection').first().toJSON();
                
                // Validate file type
                if (!this.validateFileType(attachment.url)) {
                    alert(`Please select a valid ${this.fileType} file.`);
                    return;
                }

                this.$input.val(attachment.url).trigger('change');
                this.updatePreview();
            });

            frame.open();
        }

        validateFileType(url) {
            if (this.fileType === 'pdf') {
                return url.toLowerCase().endsWith('.pdf');
            } else if (this.fileType === 'image') {
                return /\.(jpe?g|png|gif|webp)$/i.test(url);
            }
            return true;
        }

        updatePreview() {
            const $container = this.$container.find('.hvnly-popup-preview-container');
            const val = this.$input.val();

            $container.empty();
            if (!val) return;

            let previewHTML = '';

            if (this.fileType === 'image' && /\.(jpe?g|png|gif|webp)$/i.test(val)) {
                previewHTML = `
                    <div class="hvnly-popup-preview-wrapper">
                        <img src="${val}" alt="" style="max-width:150px; height:auto;" />
                        <button type="button" class="hvnly-popup-remove-preview" data-target="#${this.$input.attr('id')}">
                            <span class="dashicons dashicons-no-alt"></span>
                        </button>
                    </div>`;
            } else if (this.fileType === 'pdf' && /\.pdf$/i.test(val)) {
                const filename = val.split('/').pop();
                previewHTML = `
                    <div class="hvnly-popup-preview-wrapper">
                        <a href="${val}" target="_blank" class="pdf-link">
                            <span class="dashicons dashicons-media-document"></span> ${filename}
                        </a>
                        <button type="button" class="hvnly-popup-remove-preview" data-target="#${this.$input.attr('id')}">
                            <span class="dashicons dashicons-no-alt"></span>
                        </button>
                    </div>`;
            } else if (this.fileType === 'file') {
                const filename = val.split('/').pop();
                previewHTML = `
                    <div class="hvnly-popup-preview-wrapper">
                        <a href="${val}" target="_blank" style="display:inline-block; padding:5px 10px; background:#f0f0f0; border-radius:3px;">
                            <span class="dashicons dashicons-media-document"></span> ${filename}
                        </a>
                        <button type="button" class="hvnly-popup-remove-preview" data-target="#${this.$input.attr('id')}">
                            <span class="dashicons dashicons-no-alt"></span>
                        </button>
                    </div>`;
            }

            if (previewHTML) {
                $container.html(previewHTML);
            }
        }

        removeFile() {
            this.$input.val('');
            this.updatePreview();
        }

        getFileData() {
            return {
                url: this.$input.val() || '',
                type: this.fileType,
                filename: this.$input.val() ? this.$input.val().split('/').pop() : ''
            };
        }
    }

    // Simple initialization for file fields
    $(document).ready(() => {
        // Initialize file fields that are NOT inside video containers
        $('[data-field-type="file"]').each((index, element) => {
            const $field = $(element);
            // Check if this file field is inside a video container
            if ($field.closest('.hvnly-video-field-container').length === 0) {
                const $metaInput = $field.find('.hvnly-popup-meta-input');
                if ($metaInput.length) {
                    const fieldId = $field.data('field-id') || `file-${index}`;
                    new HavenlyticsFileField(fieldId, $metaInput);
                }
            }
        });
    });

})(jQuery);