/*
 * Project: Video Sharing Platform
 * Year: 2026
 * Developed by: Molla Samser (RSK World)
 * 
 * User profile management system
 */

class UserProfileManager {
    constructor() {
        this.currentUser = null;
        this.isEditing = false;
        this.profileData = null;
    }

    async init(username) {
        await this.loadProfile(username);
        this.setupEventListeners();
    }

    async loadProfile(username) {
        try {
            // Simulate API call
            await new Promise(resolve => setTimeout(resolve, 500));
            
            // Mock profile data
            this.profileData = {
                username: username,
                displayName: username === 'mollasamser' ? 'Molla Samser' : 'Rima Khatun',
                avatar: username === 'mollasamser' ? 
                    'https://rskworld.in/avatar1.jpg' : 'https://rskworld.in/avatar2.jpg',
                bio: username === 'mollasamser' ? 
                    'Founder of RSK World | Building the future of video streaming with Go and cutting-edge technology' :
                    'UI/UX Designer | Creating beautiful user experiences for modern web applications',
                subscribers: username === 'mollasamser' ? 842109 : 125000,
                totalViews: username === 'mollasamser' ? '15.2M' : '2.8M',
                videosCount: 42,
                joinDate: username === 'mollasamser' ? 'January 2025' : 'March 2025',
                isVerified: true,
                socialLinks: {
                    website: 'https://rskworld.in',
                    twitter: '@rskworld',
                    github: 'rskworld',
                    linkedin: 'rskworld'
                },
                stats: {
                    dailyViews: 45200,
                    monthlyViews: 1250000,
                    engagementRate: '12.5%',
                    avgWatchTime: '8:45'
                },
                recentVideos: [
                    {
                        id: 1,
                        title: "Building High-Performance Media Systems with Go",
                        thumbnail: "https://images.unsplash.com/photo-1498050108023-c5249f4df085?auto=format&fit=crop&q=80&w=800",
                        views: "1.2M",
                        uploadDate: "2 days ago",
                        duration: "15:24"
                    },
                    {
                        id: 2,
                        title: "Live: Advanced Video Processing Techniques",
                        thumbnail: "https://images.unsplash.com/photo-1498050108023-c5249f4df085?auto=format&fit=crop&q=80&w=800",
                        views: "450K",
                        uploadDate: "1 week ago",
                        duration: "LIVE"
                    },
                    {
                        id: 3,
                        title: "Mastering FFmpeg for HLS Streaming",
                        thumbnail: "https://images.unsplash.com/photo-1550745165-9bc0b252726f?auto=format&fit=crop&q=80&w=800",
                        views: "89K",
                        uploadDate: "2 weeks ago",
                        duration: "45:10"
                    }
                ]
            };

            this.renderProfile();
        } catch (error) {
            this.showError('Failed to load profile');
        }
    }

    renderProfile() {
        const profileContainer = document.getElementById('profileContent');
        if (!profileContainer) return;

        profileContainer.innerHTML = `
            <div class="profile-header">
                <div class="profile-cover">
                    <div class="cover-gradient"></div>
                    <div class="profile-info">
                        <div class="profile-avatar-container">
                            <img src="${this.profileData.avatar}" alt="${this.profileData.displayName}" class="profile-avatar">
                            ${this.profileData.isVerified ? '<div class="verified-badge large"><i class="fas fa-check"></i></div>' : ''}
                        </div>
                        <div class="profile-details">
                            <h1 class="profile-name">
                                ${this.profileData.displayName}
                                ${this.profileData.isVerified ? '<i class="fas fa-check-circle verified-icon"></i>' : ''}
                            </h1>
                            <p class="profile-username">@${this.profileData.username}</p>
                            <p class="profile-bio">${this.profileData.bio}</p>
                            
                            <div class="profile-stats">
                                <div class="stat-item">
                                    <span class="stat-value">${this.formatNumber(this.profileData.subscribers)}</span>
                                    <span class="stat-label">Subscribers</span>
                                </div>
                                <div class="stat-item">
                                    <span class="stat-value">${this.profileData.totalViews}</span>
                                    <span class="stat-label">Total Views</span>
                                </div>
                                <div class="stat-item">
                                    <span class="stat-value">${this.profileData.videosCount}</span>
                                    <span class="stat-label">Videos</span>
                                </div>
                            </div>
                            
                            <div class="profile-actions">
                                <button class="btn-subscribe ${this.isSubscribed() ? 'subscribed' : ''}" onclick="profileManager.toggleSubscribe()">
                                    ${this.isSubscribed() ? 'SUBSCRIBED' : 'SUBSCRIBE'}
                                </button>
                                <button class="btn-bell">
                                    <i class="fas fa-bell"></i>
                                </button>
                                <button class="btn-share">
                                    <i class="fas fa-share"></i>
                                </button>
                                <button class="btn-more">
                                    <i class="fas fa-ellipsis-h"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="profile-content">
                <div class="profile-tabs">
                    <button class="tab-btn active" data-tab="videos">Videos</button>
                    <button class="tab-btn" data-tab="about">About</button>
                    <button class="tab-btn" data-tab="analytics">Analytics</button>
                </div>

                <div class="tab-content">
                    <div class="tab-pane active" id="videos-tab">
                        <div class="videos-grid">
                            ${this.profileData.recentVideos.map(video => this.renderVideoCard(video)).join('')}
                        </div>
                    </div>

                    <div class="tab-pane" id="about-tab">
                        <div class="about-section">
                            <div class="about-card">
                                <h3>About ${this.profileData.displayName}</h3>
                                <p>${this.profileData.bio}</p>
                                
                                <div class="about-details">
                                    <div class="detail-item">
                                        <i class="fas fa-calendar"></i>
                                        <span>Joined ${this.profileData.joinDate}</span>
                                    </div>
                                    <div class="detail-item">
                                        <i class="fas fa-eye"></i>
                                        <span>${this.profileData.totalViews} total views</span>
                                    </div>
                                    <div class="detail-item">
                                        <i class="fas fa-users"></i>
                                        <span>${this.formatNumber(this.profileData.subscribers)} subscribers</span>
                                    </div>
                                </div>

                                <div class="social-links">
                                    ${Object.entries(this.profileData.socialLinks).map(([platform, link]) => `
                                        <a href="${link}" class="social-link" target="_blank">
                                            <i class="fab fa-${platform}"></i>
                                        </a>
                                    `).join('')}
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="tab-pane" id="analytics-tab">
                        <div class="analytics-grid">
                            <div class="analytics-card">
                                <h3>Performance Overview</h3>
                                <div class="analytics-stats">
                                    <div class="analytics-stat">
                                        <span class="analytics-value">${this.formatNumber(this.profileData.stats.dailyViews)}</span>
                                        <span class="analytics-label">Daily Views</span>
                                    </div>
                                    <div class="analytics-stat">
                                        <span class="analytics-value">${this.formatNumber(this.profileData.stats.monthlyViews)}</span>
                                        <span class="analytics-label">Monthly Views</span>
                                    </div>
                                    <div class="analytics-stat">
                                        <span class="analytics-value">${this.profileData.stats.engagementRate}</span>
                                        <span class="analytics-label">Engagement Rate</span>
                                    </div>
                                    <div class="analytics-stat">
                                        <span class="analytics-value">${this.profileData.stats.avgWatchTime}</span>
                                        <span class="analytics-label">Avg. Watch Time</span>
                                    </div>
                                </div>
                            </div>

                            <div class="analytics-card">
                                <h3>Recent Performance</h3>
                                <canvas id="performanceChart"></canvas>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        `;

        this.setupTabNavigation();
        this.initializeAnalyticsChart();
    }

    renderVideoCard(video) {
        return `
            <div class="profile-video-card" onclick="openVideo({id: ${video.id}, title: '${video.title}', creator: '${this.profileData.displayName}'})">
                <div class="video-thumbnail">
                    <img src="${video.thumbnail}" alt="${video.title}" loading="lazy">
                    <span class="duration-tag">${video.duration}</span>
                </div>
                <div class="video-info">
                    <h4>${video.title}</h4>
                    <div class="video-meta">
                        <span>${video.views} views</span>
                        <span>•</span>
                        <span>${video.uploadDate}</span>
                    </div>
                </div>
            </div>
        `;
    }

    setupTabNavigation() {
        const tabButtons = document.querySelectorAll('.tab-btn');
        const tabPanes = document.querySelectorAll('.tab-pane');

        tabButtons.forEach(button => {
            button.addEventListener('click', () => {
                const targetTab = button.dataset.tab;

                // Update button states
                tabButtons.forEach(btn => btn.classList.remove('active'));
                button.classList.add('active');

                // Update pane visibility
                tabPanes.forEach(pane => pane.classList.remove('active'));
                document.getElementById(`${targetTab}-tab`).classList.add('active');
            });
        });
    }

    initializeAnalyticsChart() {
        const canvas = document.getElementById('performanceChart');
        if (!canvas) return;

        // Simple chart visualization
        const ctx = canvas.getContext('2d');
        const width = canvas.width = canvas.offsetWidth;
        const height = canvas.height = 200;

        // Draw simple line chart
        ctx.strokeStyle = '#ff4b2b';
        ctx.lineWidth = 2;
        ctx.beginPath();

        const data = [65, 78, 90, 81, 95, 89, 102, 110, 95, 108, 115, 125];
        const stepX = width / (data.length - 1);
        const maxValue = Math.max(...data);

        data.forEach((value, index) => {
            const x = index * stepX;
            const y = height - (value / maxValue) * height * 0.8 - 10;
            
            if (index === 0) {
                ctx.moveTo(x, y);
            } else {
                ctx.lineTo(x, y);
            }
        });

        ctx.stroke();
    }

    toggleSubscribe() {
        const subscribeButton = document.querySelector('.btn-subscribe');
        const isSubscribed = subscribeButton.classList.contains('subscribed');

        if (isSubscribed) {
            subscribeButton.classList.remove('subscribed');
            subscribeButton.textContent = 'SUBSCRIBE';
            this.profileData.subscribers--;
            showNotification('Unsubscribed from ' + this.profileData.displayName, 'info');
        } else {
            subscribeButton.classList.add('subscribed');
            subscribeButton.textContent = 'SUBSCRIBED';
            this.profileData.subscribers++;
            showNotification('Subscribed to ' + this.profileData.displayName + '!', 'success');
        }

        // Update subscribers count
        const subscribersElement = document.querySelector('.stat-value');
        if (subscribersElement) {
            subscribersElement.textContent = this.formatNumber(this.profileData.subscribers);
        }
    }

    isSubscribed() {
        // Check if current user is subscribed to this profile
        return localStorage.getItem(`subscribed_${this.profileData.username}`) === 'true';
    }

    formatNumber(num) {
        if (num >= 1000000) {
            return (num / 1000000).toFixed(1) + 'M';
        } else if (num >= 1000) {
            return (num / 1000).toFixed(1) + 'K';
        }
        return num.toString();
    }

    setupEventListeners() {
        // Share functionality
        const shareButton = document.querySelector('.btn-share');
        if (shareButton) {
            shareButton.addEventListener('click', () => {
                const shareUrl = `${window.location.origin}/profile/${this.profileData.username}`;
                navigator.clipboard.writeText(shareUrl).then(() => {
                    showNotification('Profile link copied to clipboard!', 'success');
                });
            });
        }

        // Notification bell
        const bellButton = document.querySelector('.btn-bell');
        if (bellButton) {
            bellButton.addEventListener('click', () => {
                showNotification('Notifications enabled for ' + this.profileData.displayName, 'success');
            });
        }
    }

    showError(message) {
        const profileContainer = document.getElementById('profileContent');
        if (profileContainer) {
            profileContainer.innerHTML = `
                <div class="error-state">
                    <i class="fas fa-exclamation-circle"></i>
                    <h3>Profile Not Found</h3>
                    <p>${message}</p>
                    <button onclick="window.history.back()">Go Back</button>
                </div>
            `;
        }
    }
}

// Initialize profile manager
const profileManager = new UserProfileManager();

// Export for use in main app
window.UserProfileManager = UserProfileManager;
window.profileManager = profileManager;
