/**
 * StoryPosts Admin - Story Edit Screen
 * Handles automatic thumbnail/poster generation for videos and text stories
 */
(function($) {
    'use strict';

    // Only run on storyposts_story post type edit screen
    if (typeof pagenow === 'undefined' || (pagenow !== 'stpo_story' && document.getElementById('post_type')?.value !== 'stpo_story')) {
        return;
    }

    const SPStoryAdmin = {
        init() {
            this.bindEvents();
            this.checkForMissingPosters();
        },

        bindEvents() {
            // Listen for CMB2 file upload changes on video field
            $(document).on('cmb_media_modal_select', this.handleMediaSelect.bind(this));
            
            // Listen for story type changes
            $('#_stpo_type').on('change', this.handleTypeChange.bind(this));

            // Hook into form submission for text story poster generation
            $('#post').on('submit', this.handleFormSubmit.bind(this));
        },

        async checkForMissingPosters() {
            const storyType = $('#_stpo_type').val();
            const posterId = $('#_stpo_poster_id').val();

            // Only generate if no valid poster URL exists
            const isUrl = posterId && (posterId.startsWith('http') || posterId.startsWith('/'));
            if (isUrl) return;

            if (storyType === 'video') {
                const videoUrl = $('#_stpo_video_id').val();
                
                if (videoUrl && (videoUrl.startsWith('http') || videoUrl.startsWith('/'))) {
                    this.generateVideoPoster(videoUrl);
                }
            }
        },

        handleTypeChange(e) {
            const type = $(e.target).val();
            // CMB2 handles conditional fields, but we can add extra logic here if needed
        },

        handleMediaSelect(e, selection, media) {
            // Check if this is the binary/URL field for video
            const $field = $(media.el).closest('.cmb-row');
            const fieldId = $field.find('input[type="hidden"]').attr('id') || $field.find('input[type="text"]').attr('id');
            
            // CMB2 uses _id suffix for the URL field
            if (fieldId && fieldId.includes('_stpo_video_id')) {
                // Respect manual posters: only generate if poster field is empty
                const existingPoster = $('#_stpo_poster_id').val();
                if (existingPoster && (existingPoster.startsWith('http') || existingPoster.startsWith('/'))) {
                    return;
                }

                const attachment = selection.first().toJSON();
                if (attachment.type === 'video' || attachment.subtype === 'mp4' || attachment.subtype === 'quicktime') {
                    this.generateVideoPoster(attachment.url);
                }
            }
        },

        async generateVideoPoster(videoUrl) {
            try {
                const blob = await this.extractVideoFrame(videoUrl, 1);
                const data = await this.uploadPosterBlob(blob, 'video-poster.jpg');
                
                if (data && data.url) {
                    this.setPosterField(data);
                    this.showNotice('Video poster generated automatically.', 'success');
                }
            } catch (error) {
                console.error('Video poster generation failed:', error);
                this.showNotice('Could not generate video poster. Please upload manually.', 'warning');
            }
        },

        extractVideoFrame(videoUrl, seekTime = 1) {
            return new Promise((resolve, reject) => {
                const video = document.createElement('video');
                video.crossOrigin = 'anonymous';
                video.muted = true;
                video.playsInline = true;
                video.src = videoUrl;

                const timeout = setTimeout(() => {
                    reject(new Error('Video loading timed out'));
                    cleanup();
                }, 10000);

                function cleanup() {
                    video.removeEventListener('canplay', handleCanPlay);
                    video.removeEventListener('seeked', handleSeeked);
                    video.removeEventListener('error', handleError);
                    clearTimeout(timeout);
                }

                function handleError(err) {
                    reject(new Error('Video error: ' + (err.message || 'Unknown error')));
                    cleanup();
                }

                function handleCanPlay() {
                    video.currentTime = seekTime;
                }

                function handleSeeked() {
                    const canvas = document.createElement('canvas');
                    canvas.width = video.videoWidth || 640;
                    canvas.height = video.videoHeight || 360;
                    const ctx = canvas.getContext('2d');
                    ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
                    
                    canvas.toBlob(
                        (blob) => {
                            if (blob) {
                                resolve(blob);
                            } else {
                                reject(new Error('Canvas blob conversion failed'));
                            }
                            cleanup();
                        },
                        'image/jpeg',
                        0.85
                    );
                }

                video.addEventListener('canplay', handleCanPlay);
                video.addEventListener('seeked', handleSeeked);
                video.addEventListener('error', handleError);
            });
        },

        async handleFormSubmit(e) {
            const storyType = $('#_stpo_type').val();
            
            // For text stories, generate poster before submit
            if (storyType === 'text') {
                const existingPoster = $('#_stpo_poster_id').val();
                const isUrl = existingPoster && (existingPoster.startsWith('http') || existingPoster.startsWith('/'));
                
                // Regenerate if no poster exists OR if the current value looks like a malformed ID/numeric
                if (!existingPoster || !isUrl) {
                    e.preventDefault();
                    
                    try {
                        const title = $('#title').val() || '';
                        const caption = $('#_stpo_caption').val() || '';
                        const color = $('#_stpo_color').val() || '#000000';
                        
                        const blob = await this.generateTextPoster({ title, caption, backgroundColor: color });
                        const data = await this.uploadPosterBlob(blob, 'text-poster.jpg');
                        
                        if (data) {
                            this.setPosterField(data);
                        }
                        
                        // Re-submit the form
                        $('#post').off('submit').submit();
                    } catch (error) {
                        console.error('Text poster generation failed:', error);
                        // Allow form to submit anyway
                        $('#post').off('submit').submit();
                    }
                }
            }
        },

        generateTextPoster({ title, caption, backgroundColor = '#000' }) {
            return new Promise((resolve, reject) => {
                const canvas = document.createElement('canvas');
                const ctx = canvas.getContext('2d');

                canvas.width = 720;
                canvas.height = 1280;

                // Fill background
                ctx.fillStyle = backgroundColor;
                ctx.fillRect(0, 0, canvas.width, canvas.height);

                // Text settings
                ctx.fillStyle = '#ffffff';
                ctx.textAlign = 'center';

                const MAX_WIDTH = canvas.width * 0.8;
                const titleFont = 'bold 70px sans-serif';
                const captionFont = '40px sans-serif';
                const titleLineHeight = 80;
                const captionLineHeight = 70;
                const gapBetween = 40;

                // Measure text blocks
                let titleHeight = 0;
                let captionHeight = 0;

                if (title) {
                    ctx.font = titleFont;
                    const titleLines = this.getWrappedTextLines(ctx, title, MAX_WIDTH);
                    titleHeight = titleLines.length * titleLineHeight;
                }

                if (caption) {
                    ctx.font = captionFont;
                    const captionLines = this.getWrappedTextLines(ctx, caption, MAX_WIDTH);
                    captionHeight = captionLines.length * captionLineHeight;
                }

                // Calculate starting position
                const totalHeight = titleHeight + (title && caption ? gapBetween : 0) + captionHeight;
                let currentY = (canvas.height - totalHeight) / 2;

                // Helper for baseline offset (matching frontend)
                const getBaselineOffset = (fontStyle) => {
                    const sizeMatch = fontStyle.match(/(\d+)px/);
                    const fontSize = sizeMatch ? parseInt(sizeMatch[1]) : 40;
                    return Math.round(fontSize * 0.8);
                };

                // Draw title
                if (title) {
                    ctx.font = titleFont;
                    const titleLines = this.getWrappedTextLines(ctx, title, MAX_WIDTH);
                    titleLines.forEach((line) => {
                        ctx.fillText(line, canvas.width / 2, currentY + getBaselineOffset(titleFont));
                        currentY += titleLineHeight;
                    });
                    if (caption) currentY += gapBetween;
                }

                // Draw caption
                if (caption) {
                    ctx.font = captionFont;
                    const captionLines = this.getWrappedTextLines(ctx, caption, MAX_WIDTH);
                    captionLines.forEach((line) => {
                        ctx.fillText(line, canvas.width / 2, currentY + getBaselineOffset(captionFont));
                        currentY += captionLineHeight;
                    });
                }

                canvas.toBlob(
                    blob => blob ? resolve(blob) : reject(new Error('Canvas blob conversion failed')),
                    'image/jpeg',
                    0.9
                );
            });
        },

        getWrappedTextLines(ctx, text, maxWidth) {
            const words = text.split(' ');
            const lines = [];
            let currentLine = '';

            words.forEach(word => {
                const testLine = currentLine ? `${currentLine} ${word}` : word;
                const width = ctx.measureText(testLine).width;

                if (width <= maxWidth) {
                    currentLine = testLine;
                } else {
                    if (currentLine) lines.push(currentLine);
                    currentLine = word;
                }
            });

            if (currentLine) lines.push(currentLine);
            return lines;
        },

        uploadPosterBlob(blob, filename) {
            return new Promise((resolve, reject) => {
                const formData = new FormData();
                formData.append('action', 'storyposts_upload_admin_poster');
                formData.append('_wpnonce', storypostsAdminStory.nonce);
                formData.append('poster', blob, filename);
                formData.append('post_id', $('#post_ID').val());

                $.ajax({
                    url: storypostsAdminStory.ajax_url,
                    type: 'POST',
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function(response) {
                        if (response.success && response.data.attachment_id) {
                            resolve({
                                id: response.data.attachment_id,
                                url: response.data.url
                            });
                        } else {
                            reject(new Error(response.data?.message || 'Upload failed'));
                        }
                    },
                    error: function(xhr, status, error) {
                        reject(new Error(error));
                    }
                });
            });
        },

        setPosterField(data) {
            const { id, url } = data;
            
            // Update the CMB2 poster field (URL field)
            const $posterUrlField = $('#_stpo_poster_id');
            if ($posterUrlField.length) {
                $posterUrlField.val(url);
                // Trigger change for CMB2 preview if applicable
                $posterUrlField.trigger('change');
            }
            
            // Update the hidden _id field that CMB2 uses (Attachment ID field)
            const $posterIdField = $('input[name="_stpo_poster_id_id"]');
            if ($posterIdField.length) {
                $posterIdField.val(id);
            }

            // Update CMB2 preview if it exists
            const $previewContainer = $posterUrlField.closest('.cmb-td').find('.cmb2-media-status');
            if ($previewContainer.length && url) {
                $previewContainer.html('<div class="img-status"><img src="' + url + '" style="max-width:100px; height:auto;"><div class="cmb2-media-item-buttons"><button type="button" class="dashicons-before dashicons-no-alt cmb2-remove-file-button" title="Remove Image"></button></div></div>');
            }
        },

        showNotice(message, type = 'info') {
            const $notice = $('<div class="notice notice-' + type + ' is-dismissible"><p>' + message + '</p></div>');
            $('.wrap h1').first().after($notice);
            
            // Auto-dismiss after 5 seconds
            setTimeout(() => {
                $notice.fadeOut(() => $notice.remove());
            }, 5000);
        }
    };

    $(document).ready(function() {
        SPStoryAdmin.init();
    });

})(jQuery);
