/**
 * EasyStream Social Sharing Component
 * Handles sharing content to various social media platforms
 */

class SocialSharing {
    constructor(options = {}) {
        this.options = {
            url: options.url || window.location.href,
            title: options.title || document.title,
            description: options.description || '',
            image: options.image || '',
            hashtags: options.hashtags || [],
            ...options
        };
    }

    // Share to Facebook
    shareToFacebook() {
        const url = `https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(this.options.url)}`;
        this.openPopup(url, 'Facebook');
    }

    // Share to Twitter/X
    shareToTwitter() {
        const text = encodeURIComponent(this.options.title);
        const hashtags = this.options.hashtags.join(',');
        const url = `https://twitter.com/intent/tweet?url=${encodeURIComponent(this.options.url)}&text=${text}&hashtags=${hashtags}`;
        this.openPopup(url, 'Twitter');
    }

    // Share to LinkedIn
    shareToLinkedIn() {
        const url = `https://www.linkedin.com/sharing/share-offsite/?url=${encodeURIComponent(this.options.url)}`;
        this.openPopup(url, 'LinkedIn');
    }

    // Share to WhatsApp
    shareToWhatsApp() {
        const text = encodeURIComponent(`${this.options.title} ${this.options.url}`);
        const url = `https://wa.me/?text=${text}`;
        this.openPopup(url, 'WhatsApp');
    }

    // Share to Reddit
    shareToReddit() {
        const url = `https://reddit.com/submit?url=${encodeURIComponent(this.options.url)}&title=${encodeURIComponent(this.options.title)}`;
        this.openPopup(url, 'Reddit');
    }

    // Share via Email
    shareViaEmail() {
        const subject = encodeURIComponent(this.options.title);
        const body = encodeURIComponent(`${this.options.description}\n\n${this.options.url}`);
        window.location.href = `mailto:?subject=${subject}&body=${body}`;
    }

    // Copy link to clipboard
    copyLink() {
        if (navigator.clipboard && navigator.clipboard.writeText) {
            navigator.clipboard.writeText(this.options.url).then(() => {
                this.showNotification('Link copied to clipboard!');
            }).catch(err => {
                this.fallbackCopyLink();
            });
        } else {
            this.fallbackCopyLink();
        }
    }

    // Fallback copy method
    fallbackCopyLink() {
        const textArea = document.createElement('textarea');
        textArea.value = this.options.url;
        textArea.style.position = 'fixed';
        textArea.style.left = '-999999px';
        document.body.appendChild(textArea);
        textArea.select();
        try {
            document.execCommand('copy');
            this.showNotification('Link copied!');
        } catch (err) {
            this.showNotification('Failed to copy link');
        }
        document.body.removeChild(textArea);
    }

    // Generate QR code (requires QR code library)
    generateQRCode() {
        if (typeof QRCode !== 'undefined') {
            const qr = new QRCode(document.createElement('div'), {
                text: this.options.url,
                width: 256,
                height: 256
            });
            return qr;
        }
        return null;
    }

    // Native share API (mobile)
    async nativeShare() {
        if (navigator.share) {
            try {
                await navigator.share({
                    title: this.options.title,
                    text: this.options.description,
                    url: this.options.url
                });
            } catch (err) {
                if (err.name !== 'AbortError') {
                    console.error('Share failed:', err);
                }
            }
        } else {
            this.showShareDialog();
        }
    }

    // Open popup window
    openPopup(url, name) {
        const width = 600;
        const height = 400;
        const left = (screen.width - width) / 2;
        const top = (screen.height - height) / 2;
        const features = `width=${width},height=${height},left=${left},top=${top},scrollbars=yes`;
        window.open(url, name, features);
    }

    // Show notification
    showNotification(message) {
        // Simple notification - customize as needed
        const notification = document.createElement('div');
        notification.className = 'share-notification';
        notification.textContent = message;
        notification.style.cssText = `
            position: fixed;
            bottom: 20px;
            left: 50%;
            transform: translateX(-50%);
            background: #333;
            color: white;
            padding: 12px 24px;
            border-radius: 4px;
            z-index: 10000;
            animation: slideUp 0.3s ease;
        `;
        document.body.appendChild(notification);
        setTimeout(() => notification.remove(), 3000);
    }

    // Show share dialog
    showShareDialog() {
        const dialog = document.createElement('div');
        dialog.className = 'share-dialog';
        dialog.innerHTML = `
            <div class="share-dialog-overlay"></div>
            <div class="share-dialog-content">
                <h3>Share this content</h3>
                <div class="share-buttons">
                    <button onclick="socialSharing.shareToFacebook()">Facebook</button>
                    <button onclick="socialSharing.shareToTwitter()">Twitter</button>
                    <button onclick="socialSharing.shareToLinkedIn()">LinkedIn</button>
                    <button onclick="socialSharing.shareToWhatsApp()">WhatsApp</button>
                    <button onclick="socialSharing.shareToReddit()">Reddit</button>
                    <button onclick="socialSharing.shareViaEmail()">Email</button>
                    <button onclick="socialSharing.copyLink()">Copy Link</button>
                </div>
                <button class="close-dialog" onclick="this.closest('.share-dialog').remove()">×</button>
            </div>
        `;
        document.body.appendChild(dialog);
    }
}

// Export for global use
window.SocialSharing = SocialSharing;
