/*
 * Project: Video Sharing Platform
 * Year: 2026
 * Developed by: Molla Samser (RSK World)
 * 
 * Comments system functionality
 */

class CommentsManager {
    constructor() {
        this.commentsContainer = null;
        this.currentVideoId = null;
        this.comments = [];
        this.isLoading = false;
    }

    init(videoId) {
        this.currentVideoId = videoId;
        this.loadComments();
        this.setupEventListeners();
    }

    async loadComments() {
        if (this.isLoading) return;
        
        this.isLoading = true;
        this.showLoadingState();

        try {
            // Simulate API call
            await new Promise(resolve => setTimeout(resolve, 800));
            
            // Mock comments data
            this.comments = [
                {
                    id: 1,
                    user: "Molla Samser",
                    avatar: "https://rskworld.in/avatar1.jpg",
                    content: "Excellent video! The Go implementation is really impressive.",
                    timestamp: "2 hours ago",
                    likes: 42,
                    isVerified: true,
                    replies: [
                        {
                            id: 11,
                            user: "Rima Khatun",
                            avatar: "https://rskworld.in/avatar2.jpg",
                            content: "Totally agree! The performance metrics are outstanding.",
                            timestamp: "1 hour ago",
                            likes: 15,
                            isVerified: true
                        }
                    ]
                },
                {
                    id: 2,
                    user: "Tech Enthusiast",
                    avatar: "https://api.dicebear.com/7.x/avataaars/svg?seed=tech123",
                    content: "Can you make a tutorial on WebRTC integration?",
                    timestamp: "3 hours ago",
                    likes: 28,
                    isVerified: false
                },
                {
                    id: 3,
                    user: "Developer Pro",
                    avatar: "https://api.dicebear.com/7.x/avataaars/svg?seed=dev456",
                    content: "This helped me understand video processing better. Thank you!",
                    timestamp: "5 hours ago",
                    likes: 15,
                    isVerified: false
                }
            ];

            this.renderComments();
        } catch (error) {
            this.showError('Failed to load comments');
        } finally {
            this.isLoading = false;
        }
    }

    renderComments() {
        if (!this.commentsContainer) return;

        this.commentsContainer.innerHTML = `
            <div class="comments-header">
                <h3>Comments (${this.comments.length})</h3>
                <div class="comments-sort">
                    <select class="sort-select">
                        <option value="newest">Newest first</option>
                        <option value="popular">Most popular</option>
                    </select>
                </div>
            </div>
            
            <div class="add-comment">
                <div class="comment-avatar">
                    <img src="https://api.dicebear.com/7.x/avataaars/svg?seed=currentuser" alt="Your avatar">
                </div>
                <div class="comment-input-container">
                    <textarea 
                        class="comment-input" 
                        placeholder="Add a comment..."
                        rows="1"
                    ></textarea>
                    <div class="comment-actions">
                        <button class="btn-cancel">Cancel</button>
                        <button class="btn-comment" disabled>Comment</button>
                    </div>
                </div>
            </div>
            
            <div class="comments-list">
                ${this.comments.map(comment => this.renderComment(comment)).join('')}
            </div>
        `;

        this.setupCommentInteractions();
    }

    renderComment(comment, isReply = false) {
        return `
            <div class="comment ${isReply ? 'comment-reply' : ''}" data-comment-id="${comment.id}">
                <div class="comment-avatar">
                    <img src="${comment.avatar}" alt="${comment.user}">
                    ${comment.isVerified ? '<div class="verified-badge"><i class="fas fa-check"></i></div>' : ''}
                </div>
                <div class="comment-content">
                    <div class="comment-header">
                        <span class="comment-user">${comment.user}</span>
                        <span class="comment-time">${comment.timestamp}</span>
                    </div>
                    <div class="comment-text">${comment.content}</div>
                    <div class="comment-actions">
                        <button class="btn-like" data-comment-id="${comment.id}">
                            <i class="fas fa-thumbs-up"></i>
                            <span class="like-count">${comment.likes}</span>
                        </button>
                        <button class="btn-reply" data-comment-id="${comment.id}">
                            <i class="fas fa-reply"></i>
                            Reply
                        </button>
                        ${!isReply ? `
                            <button class="btn-share" data-comment-id="${comment.id}">
                                <i class="fas fa-share"></i>
                                Share
                            </button>
                        ` : ''}
                    </div>
                    ${!isReply && comment.replies && comment.replies.length > 0 ? `
                        <div class="comment-replies">
                            ${comment.replies.map(reply => this.renderComment(reply, true)).join('')}
                        </div>
                    ` : ''}
                </div>
            </div>
        `;
    }

    setupCommentInteractions() {
        // Comment input
        const commentInput = this.commentsContainer.querySelector('.comment-input');
        const commentButton = this.commentsContainer.querySelector('.btn-comment');
        const cancelButton = this.commentsContainer.querySelector('.btn-cancel');

        if (commentInput) {
            commentInput.addEventListener('input', () => {
                commentButton.disabled = !commentInput.value.trim();
                this.autoResizeTextarea(commentInput);
            });

            commentInput.addEventListener('focus', () => {
                commentInput.parentElement.classList.add('focused');
            });

            commentInput.addEventListener('blur', () => {
                if (!commentInput.value.trim()) {
                    commentInput.parentElement.classList.remove('focused');
                }
            });
        }

        if (commentButton) {
            commentButton.addEventListener('click', () => {
                this.addComment(commentInput.value.trim());
            });
        }

        if (cancelButton) {
            cancelButton.addEventListener('click', () => {
                commentInput.value = '';
                commentInput.parentElement.classList.remove('focused');
                commentButton.disabled = true;
            });
        }

        // Like buttons
        this.commentsContainer.querySelectorAll('.btn-like').forEach(btn => {
            btn.addEventListener('click', (e) => {
                this.likeComment(e.currentTarget.dataset.commentId);
            });
        });

        // Reply buttons
        this.commentsContainer.querySelectorAll('.btn-reply').forEach(btn => {
            btn.addEventListener('click', (e) => {
                this.showReplyInput(e.currentTarget.dataset.commentId);
            });
        });

        // Share buttons
        this.commentsContainer.querySelectorAll('.btn-share').forEach(btn => {
            btn.addEventListener('click', (e) => {
                this.shareComment(e.currentTarget.dataset.commentId);
            });
        });
    }

    async addComment(content) {
        if (!content.trim()) return;

        const newComment = {
            id: Date.now(),
            user: "Current User",
            avatar: "https://api.dicebear.com/7.x/avataaars/svg?seed=currentuser",
            content: content,
            timestamp: "Just now",
            likes: 0,
            isVerified: false
        };

        this.comments.unshift(newComment);
        this.renderComments();
        
        // Show success notification
        showNotification('Comment added successfully!', 'success');
    }

    async likeComment(commentId) {
        const comment = this.comments.find(c => c.id == commentId) || 
                        this.findReply(commentId);
        
        if (comment) {
            comment.likes += 1;
            this.renderComments();
        }
    }

    findReply(commentId) {
        for (let comment of this.comments) {
            if (comment.replies) {
                const reply = comment.replies.find(r => r.id == commentId);
                if (reply) return reply;
            }
        }
        return null;
    }

    showReplyInput(parentId) {
        const parentComment = this.commentsContainer.querySelector(`[data-comment-id="${parentId}"]`);
        const repliesContainer = parentComment.querySelector('.comment-replies');
        
        if (!repliesContainer) {
            const newRepliesContainer = document.createElement('div');
            newRepliesContainer.className = 'comment-replies';
            parentComment.appendChild(newRepliesContainer);
        }

        const replyHtml = `
            <div class="add-reply">
                <div class="comment-avatar">
                    <img src="https://api.dicebear.com/7.x/avataaars/svg?seed=currentuser" alt="Your avatar">
                </div>
                <div class="comment-input-container">
                    <textarea 
                        class="comment-input reply-input" 
                        placeholder="Write a reply..."
                        rows="1"
                    ></textarea>
                    <div class="comment-actions">
                        <button class="btn-cancel-reply">Cancel</button>
                        <button class="btn-reply-submit" disabled>Reply</button>
                    </div>
                </div>
            </div>
        `;

        const existingReply = parentComment.querySelector('.add-reply');
        if (existingReply) {
            existingReply.remove();
        } else {
            const repliesDiv = parentComment.querySelector('.comment-replies') || 
                              document.createElement('div');
            repliesDiv.className = 'comment-replies';
            repliesDiv.innerHTML = replyHtml;
            
            if (!parentComment.querySelector('.comment-replies')) {
                parentComment.appendChild(repliesDiv);
            }

            // Setup reply input events
            const replyInput = repliesDiv.querySelector('.reply-input');
            const replyButton = repliesDiv.querySelector('.btn-reply-submit');
            const cancelButton = repliesDiv.querySelector('.btn-cancel-reply');

            replyInput.addEventListener('input', () => {
                replyButton.disabled = !replyInput.value.trim();
                this.autoResizeTextarea(replyInput);
            });

            replyButton.addEventListener('click', () => {
                this.addReply(parentId, replyInput.value.trim());
            });

            cancelButton.addEventListener('click', () => {
                repliesDiv.querySelector('.add-reply').remove();
            });

            replyInput.focus();
        }
    }

    async addReply(parentId, content) {
        const parentComment = this.comments.find(c => c.id == parentId);
        if (parentComment) {
            if (!parentComment.replies) {
                parentComment.replies = [];
            }

            const newReply = {
                id: Date.now(),
                user: "Current User",
                avatar: "https://api.dicebear.com/7.x/avataaars/svg?seed=currentuser",
                content: content,
                timestamp: "Just now",
                likes: 0,
                isVerified: false
            };

            parentComment.replies.push(newReply);
            this.renderComments();
            showNotification('Reply added successfully!', 'success');
        }
    }

    shareComment(commentId) {
        const comment = this.comments.find(c => c.id == commentId);
        if (comment) {
            // Copy to clipboard functionality
            const shareText = `"${comment.content}" - ${comment.user}`;
            navigator.clipboard.writeText(shareText).then(() => {
                showNotification('Comment copied to clipboard!', 'success');
            });
        }
    }

    showLoadingState() {
        if (this.commentsContainer) {
            this.commentsContainer.innerHTML = `
                <div class="comments-loading">
                    <div class="skeleton-loader">
                        <div class="skeleton-avatar"></div>
                        <div class="skeleton-lines">
                            <div class="skeleton-line"></div>
                            <div class="skeleton-line short"></div>
                        </div>
                    </div>
                    <div class="skeleton-loader">
                        <div class="skeleton-avatar"></div>
                        <div class="skeleton-lines">
                            <div class="skeleton-line"></div>
                            <div class="skeleton-line short"></div>
                        </div>
                    </div>
                </div>
            `;
        }
    }

    showError(message) {
        if (this.commentsContainer) {
            this.commentsContainer.innerHTML = `
                <div class="comments-error">
                    <i class="fas fa-exclamation-circle"></i>
                    <p>${message}</p>
                    <button onclick="commentsManager.loadComments()">Retry</button>
                </div>
            `;
        }
    }

    autoResizeTextarea(textarea) {
        textarea.style.height = 'auto';
        textarea.style.height = textarea.scrollHeight + 'px';
    }

    setupEventListeners() {
        // Sort functionality
        const sortSelect = this.commentsContainer?.querySelector('.sort-select');
        if (sortSelect) {
            sortSelect.addEventListener('change', (e) => {
                this.sortComments(e.target.value);
            });
        }
    }

    sortComments(sortBy) {
        if (sortBy === 'popular') {
            this.comments.sort((a, b) => b.likes - a.likes);
        } else {
            // Default: newest first (already in order)
        }
        this.renderComments();
    }
}

// Initialize comments manager
const commentsManager = new CommentsManager();

// Export for use in main app
window.CommentsManager = CommentsManager;
window.commentsManager = commentsManager;
