/**
 * EasyStream Embed Code Generator
 * Generates iframe embed codes for videos
 */

class EmbedGenerator {
    constructor(options = {}) {
        this.options = {
            baseUrl: options.baseUrl || window.location.origin,
            fileKey: options.fileKey || '',
            fileType: options.fileType || 'video',
            width: options.width || 560,
            height: options.height || 315,
            autoplay: options.autoplay || false,
            controls: options.controls !== false,
            startTime: options.startTime || 0,
            ...options
        };
    }

    // Generate iframe embed code
    generateIframeCode() {
        const params = new URLSearchParams();
        if (this.options.autoplay) params.append('autoplay', '1');
        if (!this.options.controls) params.append('controls', '0');
        if (this.options.startTime) params.append('t', this.options.startTime);

        const queryString = params.toString() ? '&' + params.toString() : '';
        const embedUrl = `${this.options.baseUrl}/f_modules/m_frontend/m_player/embed.php?${this.options.fileType[0]}=${this.options.fileKey}${queryString}`;

        return `<iframe width="${this.options.width}" height="${this.options.height}" src="${embedUrl}" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>`;
    }

    // Generate responsive embed code
    generateResponsiveCode() {
        const aspectRatio = (this.options.height / this.options.width) * 100;
        const params = new URLSearchParams();
        if (this.options.autoplay) params.append('autoplay', '1');
        if (!this.options.controls) params.append('controls', '0');
        if (this.options.startTime) params.append('t', this.options.startTime);

        const queryString = params.toString() ? '&' + params.toString() : '';
        const embedUrl = `${this.options.baseUrl}/f_modules/m_frontend/m_player/embed.php?${this.options.fileType[0]}=${this.options.fileKey}${queryString}`;

        return `<div style="position: relative; padding-bottom: ${aspectRatio}%; height: 0; overflow: hidden;">
  <iframe style="position: absolute; top: 0; left: 0; width: 100%; height: 100%;" src="${embedUrl}" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>`;
    }

    // Generate direct link
    generateDirectLink() {
        return `${this.options.baseUrl}/watch?v=${this.options.fileKey}${this.options.startTime ? '&t=' + this.options.startTime : ''}`;
    }

    // Generate thumbnail URL
    generateThumbnailUrl(userKey) {
        return `${this.options.baseUrl}/f_data/data_userfiles/${userKey}/t/${this.options.fileKey}/0.jpg`;
    }

    // Show embed dialog
    showEmbedDialog() {
        const dialog = document.createElement('div');
        dialog.className = 'embed-dialog';
        dialog.innerHTML = `
            <div class="embed-dialog-overlay" onclick="this.parentElement.remove()"></div>
            <div class="embed-dialog-content">
                <h3>Embed Video</h3>

                <div class="embed-options">
                    <label>
                        <input type="number" id="embedWidth" value="${this.options.width}" min="200" max="1920">
                        Width (px)
                    </label>
                    <label>
                        <input type="number" id="embedHeight" value="${this.options.height}" min="200" max="1080">
                        Height (px)
                    </label>
                    <label>
                        <input type="checkbox" id="embedAutoplay" ${this.options.autoplay ? 'checked' : ''}>
                        Autoplay
                    </label>
                    <label>
                        <input type="checkbox" id="embedControls" ${this.options.controls ? 'checked' : ''}>
                        Show Controls
                    </label>
                    <label>
                        <input type="number" id="embedStartTime" value="${this.options.startTime}" min="0">
                        Start Time (seconds)
                    </label>
                </div>

                <div class="embed-preview">
                    <h4>Preview</h4>
                    <div id="embedPreview"></div>
                </div>

                <div class="embed-code">
                    <h4>Embed Code</h4>
                    <textarea id="embedCodeArea" readonly></textarea>
                    <button onclick="embedGenerator.copyEmbedCode()">Copy Code</button>
                </div>

                <div class="embed-code">
                    <h4>Responsive Embed Code</h4>
                    <textarea id="embedCodeResponsive" readonly></textarea>
                    <button onclick="embedGenerator.copyResponsiveCode()">Copy Code</button>
                </div>

                <button class="close-dialog" onclick="this.closest('.embed-dialog').remove()">×</button>
            </div>
        `;

        document.body.appendChild(dialog);

        // Update on option change
        ['embedWidth', 'embedHeight', 'embedAutoplay', 'embedControls', 'embedStartTime'].forEach(id => {
            document.getElementById(id).addEventListener('change', () => this.updateEmbedPreview());
        });

        this.updateEmbedPreview();
    }

    // Update embed preview
    updateEmbedPreview() {
        this.options.width = parseInt(document.getElementById('embedWidth').value);
        this.options.height = parseInt(document.getElementById('embedHeight').value);
        this.options.autoplay = document.getElementById('embedAutoplay').checked;
        this.options.controls = document.getElementById('embedControls').checked;
        this.options.startTime = parseInt(document.getElementById('embedStartTime').value);

        const iframeCode = this.generateIframeCode();
        const responsiveCode = this.generateResponsiveCode();

        document.getElementById('embedCodeArea').value = iframeCode;
        document.getElementById('embedCodeResponsive').value = responsiveCode;
        document.getElementById('embedPreview').innerHTML = iframeCode;
    }

    // Copy embed code
    copyEmbedCode() {
        const code = document.getElementById('embedCodeArea');
        code.select();
        document.execCommand('copy');
        alert('Embed code copied to clipboard!');
    }

    // Copy responsive code
    copyResponsiveCode() {
        const code = document.getElementById('embedCodeResponsive');
        code.select();
        document.execCommand('copy');
        alert('Responsive embed code copied!');
    }
}

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