/**
 * SocialPilot Meta Box JavaScript
 * 
 * Handles all meta box interactions, media uploads, and post scheduling.
 *
 * @package SocialPilot
 * @since 1.0.0
 */

/* global wp, socialpilotData */
jQuery(function($) {
            'use strict';

            // Store all DOM selectors
            const DOM = {
                postType: 'input[name="socialpilot_post_type"]',
                caption: '#socialpilot_caption',
                scheduleTime: '#socialpilot_schedule_time',
                accountCheckbox: '.account-checkbox',
                mediaPreview: '#socialpilot_media_preview',
                thumbnailPreview: '#article_thumbnail_preview',
                thumbnailId: '#article_thumbnail_id',
                articleTitle: '#article_title',
                articleDesc: '#article_description',
                messages: '#socialpilot_messages',
                imageFields: '#image_post_fields',
                articleFields: '#article_post_fields',
                buttons: {
                    addMedia: '#add_media',
                    addThumbnail: '#add_thumbnail',
                    generateCaption: '#generate_caption',
                    schedulePost: '#schedule_post'
                }
            };

            // Store MediaFrame instances
            const mediaFrames = {
                multiple: null,
                single: null
            };

            // Store selected media items
            let selectedMedia = [];

            /**
             * Initialize the meta box functionality
             */
            function init() {
                initializeMediaFrames();
                bindEvents();
                loadAccounts();
                setInitialValues();
            }

            /**
             * Initialize WordPress media frames
             */
            function initializeMediaFrames() {
                // Multiple media selector for image posts
                mediaFrames.multiple = wp.media({
                    title: (socialpilotData && socialpilotData.strings && socialpilotData.strings.selectMedia) || 'Select Images',
                    button: {
                        text: (socialpilotData && socialpilotData.strings && socialpilotData.strings.addToPost) || 'Add to Post'
                    },
                    multiple: true,
                    library: { type: 'image' }
                });

                // Single image selector for article thumbnail
                mediaFrames.single = wp.media({
                    title: (socialpilotData && socialpilotData.strings && socialpilotData.strings.selectThumbnail) || 'Select Featured Image',
                    button: {
                        text: (socialpilotData && socialpilotData.strings && socialpilotData.strings.setThumbnail) || 'Set Featured Image'
                    },
                    multiple: false,
                    library: { type: 'image' }
                });

                mediaFrames.multiple.on('select', handleMultipleMediaSelection);
                mediaFrames.single.on('select', handleSingleMediaSelection);
            }

            /**
             * Bind all event listeners
             */
            function bindEvents() {
                $(DOM.postType).on('change', function() {
                    togglePostType($(this).val());
                });

                $(DOM.buttons.addMedia).on('click', function(e) {
                    e.preventDefault();
                    mediaFrames.multiple.open();
                });

                $(DOM.buttons.addThumbnail).on('click', function(e) {
                    e.preventDefault();
                    mediaFrames.single.open();
                });

                $(document).on('click', '.remove-media', function(e) {
                    e.preventDefault();
                    removeMedia($(this).data('id'));
                });

                $(document).on('click', '.remove-thumbnail', function(e) {
                    e.preventDefault();
                    $(DOM.thumbnailPreview).empty();
                    $(DOM.thumbnailId).val('');
                });

                $(DOM.buttons.generateCaption).on('click', generateCaption);
                $(DOM.buttons.schedulePost).on('click', schedulePost);

                $('#title').on('change keyup', function() {
                    if ($(DOM.articleTitle).length) {
                        $(DOM.articleTitle).val($(this).val());
                    }
                });

                // Handle WordPress featured image changes
                if (typeof wp !== 'undefined' && wp.media && wp.media.featuredImage) {
                    const frame = wp.media.featuredImage.frame();
                    if (frame) {
                        frame.on('select', function() {
                            const featured = frame.state().get('selection').first();
                            if (featured) {
                                updateThumbnailPreview(featured.toJSON());
                            }
                        });
                    }
                }
            }

            /**
             * Set initial form values
             */
            function setInitialValues() {
                const initialPostType = $(DOM.postType + ':checked').val() || 'text';
                togglePostType(initialPostType);

                const defaultTime = new Date();
                defaultTime.setMinutes(defaultTime.getMinutes() + 30);
                $(DOM.scheduleTime).val(defaultTime.toISOString().slice(0, 16));
            }

            /**
             * Toggle between different post types
             */
            function togglePostType(postType) {
                $(DOM.imageFields + ', ' + DOM.articleFields).hide();

                if (postType !== 'image') {
                    selectedMedia = [];
                    updateMediaPreview();
                }

                switch (postType) {
                    case 'image':
                        $(DOM.imageFields).show();
                        break;
                    case 'article':
                        $(DOM.articleFields).show();
                        setArticleDefaults();
                        break;
                }
            }

            /**
             * Set default values for article fields
             */
            function setArticleDefaults() {
                const defaults = {
                    title: $('#title').val() || '',
                    excerpt: $('#excerpt').val() || '',
                    imageUrl: $('#set-post-thumbnail img').attr('src') || '',
                    imageId: $('#_thumbnail_id').val() || ''
                };

                if (!$(DOM.articleTitle).val() && defaults.title) {
                    $(DOM.articleTitle).val(defaults.title);
                }

                if (!$(DOM.articleDesc).val() && defaults.excerpt) {
                    $(DOM.articleDesc).val(defaults.excerpt);
                }

                if (!$(DOM.thumbnailId).val() && defaults.imageUrl && defaults.imageId) {
                    updateThumbnailPreview({
                        url: defaults.imageUrl,
                        id: defaults.imageId
                    });
                }
            }

            /**
             * Handle selection of multiple media items
             */
            function handleMultipleMediaSelection() {
                const selection = mediaFrames.multiple.state().get('selection');

                selection.forEach(function(attachment) {
                    const file = attachment.toJSON();
                    if (!selectedMedia.some(media => media.id === file.id)) {
                        const thumbnail = file.sizes && file.sizes.thumbnail ?
                            file.sizes.thumbnail.url : file.url;
                        selectedMedia.push({
                            id: file.id,
                            url: file.url,
                            thumbnail: thumbnail,
                            type: 'image'
                        });
                    }
                });

                updateMediaPreview();
            }

            /**
             * Handle selection of single media item
             */
            function handleSingleMediaSelection() {
                const attachment = mediaFrames.single.state().get('selection').first().toJSON();
                updateThumbnailPreview(attachment);
            }

            /**
             * Update media preview grid
             */
            function updateMediaPreview() {
                const container = $(DOM.mediaPreview);
                container.empty();

                if (!selectedMedia.length) {
                    container.html('<div class="media-placeholder">No images selected</div>');
                    return;
                }

                const mediaHtml = selectedMedia.map(media => `
            <div class="media-item" data-id="${media.id}">
                <img src="${media.thumbnail}" alt="">
                <button type="button" class="remove-media" data-id="${media.id}">×</button>
            </div>
        `).join('');

                container.html(mediaHtml);
            }

            /**
             * Update thumbnail preview
             */
            function updateThumbnailPreview(attachment) {
                if (!attachment || !attachment.url) return;

                const html = `
            <div class="thumbnail-container">
                <img src="${attachment.url}" alt="Article thumbnail">
                <button type="button" class="remove-thumbnail">×</button>
            </div>`;

                $(DOM.thumbnailPreview).html(html);
                $(DOM.thumbnailId).val(attachment.id || '');
            }

            /**
             * Remove media from selection
             */
            function removeMedia(mediaId) {
                selectedMedia = selectedMedia.filter(media => media.id !== mediaId);
                updateMediaPreview();
            }

            /**
             * Load social media accounts
             */
            function loadAccounts() {
                if (!socialpilotData || !socialpilotData.ajaxurl || !socialpilotData.nonce) {
                    showMessage('Configuration error', 'error');
                    return;
                }

                $.ajax({
                        url: socialpilotData.ajaxurl,
                        method: 'POST',
                        data: {
                            action: 'socialpilot_get_accounts',
                            nonce: socialpilotData.nonce
                        }
                    })
                    .done(function(response) {
                        if (response && response.success && response.data &&
                            response.data.response && response.data.response.list) {
                            renderAccounts(response.data.response.list);
                        } else {
                            const message = response && response.data && response.data.message ?
                                response.data.message : 'Failed to load accounts';
                            showMessage(message, 'error');
                        }
                    })
                    .fail(function() {
                        showMessage('Failed to connect to server', 'error');
                    });
            }

            /**
             * Render social media accounts
             */
            function renderAccounts(accounts) {
                if (!accounts || !accounts.length) {
                    $('#socialpilot_accounts').html('<p>No social media accounts found</p>');
                    return;
                }

                const accountsHtml = accounts.map(account => {
                            const isDisabled = account.isLocked || account.isReconnect;
                            const disabledTitle = account.isLocked ? 'Account is locked' :
                                account.isReconnect ? 'Account needs reconnection' : '';

                            return `
                        <div class="account-item ${isDisabled ? 'account-disabled' : ''}" 
                             title="${isDisabled ? disabledTitle : ''}">
                            <label>
                                <input type="checkbox" 
                                       class="account-checkbox" 
                                       value="${account.loginId}" 
                                       name="socialpilot_accounts[]"
                                       ${isDisabled ? 'disabled' : ''}>
                                ${account.socialMediaLogoUrl ? 
                                    `<img src="${account.socialMediaLogoUrl}" 
                                         alt="Social media logo" 
                                         class="platform-logo"
                                         onerror="this.style.display='none'">` 
                                    : ''}
                                <span class="account-username">${account.accountUsername}</span>
                            </label>
                            ${account.accountUrl ? 
                                `<a href="${account.accountUrl}" 
                                    class="account-link" 
                                    target="_blank" 
                                    title="View Account Profile"
                                    rel="noopener noreferrer">
                                    <span class="dashicons dashicons-external"></span>
                                </a>` 
                                : ''}
                        </div>
                    `;
                }).join('');
        
                $('#socialpilot_accounts').html(accountsHtml);
            }

    /**
     * Generate caption using AI
     */
    function generateCaption() {
        const $button = $(this);
        
        // Get title and content based on editor type
        var title = '';
        var content = '';

        // Get current post type dynamically
        var bodyClasses = $('body').attr('class').split(' ');
        var isCustomPostType = bodyClasses.some(function(className) {
            return className.startsWith('post-type-') &&
                !['post-type-post', 'post-type-page'].includes(className);
        });

        // Check editor type and get content accordingly
        if (isCustomPostType) {
            title = document.getElementById('title').value;
            content = $('.wp-editor-area').val();
        }
        // Check for Gutenberg editor
        else if ($('body').hasClass('block-editor-page')) {
            title = wp.data.select('core/editor').getEditedPostAttribute('title');
            content = wp.data.select('core/editor').getEditedPostContent();
        }
        // Check for classic editor
        else if (typeof tinyMCE !== 'undefined' && tinyMCE.activeEditor && !tinyMCE.activeEditor.isHidden()) {
            title = document.getElementById('title').value;
            content = tinyMCE.activeEditor.getContent();
        }
        // Fallback for text editor mode
        else {
            title = document.getElementById('title').value;
            content = $('#content').val();
        }

        // Validate inputs
        if (!title || !content) {
            showMessage('Post title and content are required for caption generation', 'error');
            button.prop('disabled', false).text('Generate Caption');
            return;
        }


        if (!socialpilotData || !socialpilotData.ajaxurl || !socialpilotData.nonce) {
            showMessage('Configuration error', 'error');
            return;
        }

        $button.prop('disabled', true)
               .text((socialpilotData && socialpilotData.strings && 
                     socialpilotData.strings.generating) || 'Generating...');

        $.ajax({
            url: socialpilotData.ajaxurl,
            method: 'POST',
            data: {
                action: 'socialpilot_generate_caption',
                title: title,
                content: content,
                nonce: socialpilotData.nonce
            }
        })
        .done(function(response) {
            if (response && response.success && response.data && 
                response.data.response && response.data.response.data) {
                $(DOM.caption).val(response.data.response.data);
                showMessage('Caption generated successfully!', 'success');
            } else {
                const message = response && response.data && response.data.message ? 
                    response.data.message : 'Failed to generate caption';
                showMessage(message, 'error');
            }
        })
        .fail(function() {
            showMessage('Failed to generate caption', 'error');
        })
        .always(function() {
            $button.prop('disabled', false)
                   .text((socialpilotData && socialpilotData.strings && 
                         socialpilotData.strings.generateCaption) || 'Generate Caption');
        });
    }

    /**
     * Get post content based on editor type
     */
    function getPostContent() {
        if ($('body').hasClass('block-editor-page') && wp.data && 
            wp.data.select('core/editor')) {
            return wp.data.select('core/editor').getEditedPostContent();
        }
        
        if (typeof tinyMCE !== 'undefined' && tinyMCE.activeEditor && 
            !tinyMCE.activeEditor.isHidden()) {
            return tinyMCE.activeEditor.getContent();
        }
        
        return $('#content').val() || '';
    }

    /**
     * Schedule post
     */
    function schedulePost() {
        if (!validateForm()) return;

        const $button = $(this);
        $button.prop('disabled', true)
               .text((socialpilotData && socialpilotData.strings && 
                     socialpilotData.strings.scheduling) || 'Scheduling...');

        const postType = $(DOM.postType + ':checked').val() || 'text';
        
        switch (postType) {
            case 'image':
                if (selectedMedia.length) {
                    handleImagePost($button);
                } else {
                    handleError($button, 'Please select images');
                }
                break;
            case 'article':
                handleArticlePost($button);
                break;
            case 'text':
                createPost([], 'text', $button);
                break;
            default:
                handleError($button, 'Invalid post type');
        }
    }

    /**
     * Validate form before submission
     */
    function validateForm() {
        const validation = [
            {
                condition: !$(DOM.caption).val(),
                message: 'Please enter a caption'
            },
            {
                condition: !$(DOM.scheduleTime).val(),
                message: 'Please select a schedule time'
            },
            {
                condition: !$(DOM.accountCheckbox + ':checked').length,
                message: 'Please select at least one social media account'
            }
        ];

        const postType = $(DOM.postType + ':checked').val() || 'text';
        if (postType === 'image') {
            validation.push({
                condition: !selectedMedia.length,
                message: 'Please select at least one image'
            });
        } else if (postType === 'article') {
            validation.push({
                condition: !$(DOM.thumbnailPreview + ' img').length,
                message: 'Please select a featured image'
            });
        }

        for (const rule of validation) {
            if (rule.condition) {
                showMessage(rule.message, 'error');
                return false;
            }
        }

        return true;
    }

    /**
     * Handle error in scheduling
     */
    function handleError($button, message) {
        $button.prop('disabled', false)
               .text((socialpilotData && socialpilotData.strings && 
                     socialpilotData.strings.schedulePost) || 'Schedule Post');
        showMessage(message, 'error');
    }

    /**
     * Handle image post scheduling
     */
    function handleImagePost($button) {
        Promise.all(selectedMedia.map(media => uploadMedia(media.url)))
            .then(mediaIds => createPost(mediaIds, 'image', $button))
            .catch(error => handleError($button, error || 'Failed to upload images'));
    }

    /**
     * Handle article post scheduling
     */
    function handleArticlePost($button) {
        const thumbnailUrl = $(DOM.thumbnailPreview + ' img').attr('src');

        if (thumbnailUrl) {
            uploadMedia(thumbnailUrl)
                .then(mediaId => createPost([mediaId], 'article', $button))
                .catch(error => handleError($button, error || 'Failed to upload thumbnail'));
        } else {
            createPost([], 'article', $button);
        }
    }

    /**
     * Upload media to SocialPilot
     */
    function uploadMedia(mediaUrl) {
        if (!socialpilotData || !socialpilotData.ajaxurl || !socialpilotData.nonce) {
            return Promise.reject('Configuration error');
        }

        return new Promise((resolve, reject) => {
            $.ajax({
                url: socialpilotData.ajaxurl,
                method: 'POST',
                data: {
                    action: 'socialpilot_upload_media',
                    media_url: mediaUrl,
                    media_type: 'IMAGE',
                    nonce: socialpilotData.nonce
                }
            })
            .done(function(response) {
                if (response && response.success && response.data && 
                    response.data.response && response.data.response.mediaIds && 
                    response.data.response.mediaIds[0]) {
                    resolve(response.data.response.mediaIds[0].mediaId);
                } else {
                    const message = response && response.data && response.data.message ? 
                        response.data.message : 'Failed to upload media';
                    reject(message);
                }
            })
            .fail(function() {
                reject('Failed to upload media');
            });
        });
    }

    /**
     * Create and schedule post with SocialPilot
     */
    function createPost(mediaIds, postType, $button) {
        if (!socialpilotData || !socialpilotData.ajaxurl || !socialpilotData.nonce) {
            handleError($button, 'Configuration error');
            return;
        }

        const scheduleTime = $(DOM.scheduleTime).val().replace('T', ' ');
        const selectedAccounts = $(DOM.accountCheckbox + ':checked')
            .map(function() { return parseInt($(this).val(), 10); })
            .get();

        const postData = {
            scheduleDateTime: [scheduleTime],
            shareType: 3, // scheduled post
            loginIds: selectedAccounts,
            posts: [{
                type: 'original',
                postDesc: $(DOM.caption).val()
            },{
                type: 'pinterest',
                postDesc: $(DOM.caption).val()
            }]
        };

        // Add type-specific data
        switch (postType) {
            case 'article':
                postData.posts[0].postTitle = $(DOM.articleTitle).val() || '';
                postData.posts[0].postUrl = socialpilotData.postUrl || '';
                postData.posts[0].longPostDesc = $(DOM.articleDesc).val() || '';
                if (mediaIds && mediaIds.length) {
                    postData.posts[0].mediaId = mediaIds;
                }

                postData.posts[1].postTitle = $(DOM.articleTitle).val() || '';
                postData.posts[1].postUrl = socialpilotData.postUrl || '';
                postData.posts[1].longPostDesc = $(DOM.articleDesc).val() || '';
                postData.posts[1].pinTitle = $(DOM.articleTitle).val() || '';
                postData.posts[1].destinationUrl = socialpilotData.postUrl || '';
                postData.posts[1].pinAltText = '';
                postData.posts[1].sameTextAndUrl = true;
                if (mediaIds && mediaIds.length) {
                    postData.posts[1].mediaId = mediaIds;
                }

                break;

            case 'image':
                if (mediaIds && mediaIds.length) {
                    postData.posts[0].mediaId = mediaIds;
                    postData.posts[1].mediaId = mediaIds;
                }
                break;
        }

       
        $.ajax({
            url: socialpilotData.ajaxurl,
            method: 'POST',
            data: {
                action: 'socialpilot_schedule_post',
                post_data: JSON.stringify(postData),
                nonce: socialpilotData.nonce
            }
        })
        .done(function(response) {
            if (response && response.success) {
                showMessage('Post scheduled successfully!', 'success');
                resetForm();
              setTimeout(() => {
                setInitialValues();
              }, 100);
            } else {
                let errorMessage = '';
                if (response && response.data && response.data.reasons) {
                    errorMessage = response.data.reasons
                        .map(reason => reason.message || reason)
                        .join('\n');
                } else {
                    errorMessage = response && response.data && response.data.message ? 
                        response.data.message : 'Failed to schedule post';
                }
                showMessage(errorMessage, 'error');
            }
        })
        .fail(function() {
            showMessage('Failed to schedule post', 'error');
        })
        .always(function() {
            $button.prop('disabled', false)
                   .text((socialpilotData && socialpilotData.strings && 
                         socialpilotData.strings.schedulePost) || 'Schedule Post');
        });
    }

    /**
     * Reset form after successful posting
     */
    function resetForm() {
        $(DOM.caption).val('');
        $(DOM.scheduleTime).val('');
        $(DOM.accountCheckbox).prop('checked', false);

        const postType = $(DOM.postType + ':checked').val() || 'text';
        if (postType === 'image') {
            selectedMedia = [];
            updateMediaPreview();
        } else if (postType === 'article') {
            setArticleDefaults();
        }
    }

    /**
     * Show message to user
     */
    function showMessage(message, type) {
        const messageHtml = `
            <div class="notice notice-${type === 'success' ? 'success' : 'error'} inline">
                ${message.includes('\n') 
                    ? '<ul>' + message.split('\n')
                          .filter(line => line.trim())
                          .map(line => `<li>${line.trim()}</li>`)
                          .join('') + '</ul>'
                    : `<p>${message}</p>`}
            </div>`;

        $(DOM.messages).html(messageHtml);

        // Auto-hide message after 5 seconds
        setTimeout(() => {
            $(DOM.messages).empty();
        }, 5000);
    }

    // Initialize everything
    init();
});