/**
 * Cast Conductor Proprietary License v5
 * SPDX-License-Identifier: LicenseRef-CastConductor-Proprietary-v5
 * 
 * Copyright (c) 2025 CastConductor.com. All Rights Reserved.
 * 
 * qr-code-generator.js
 * Client-side QR code generation for content blocks
 */

// QR Code Generator Module - v1.0.1

export function attachQrCodeGenerator(editor) {
    
    if (editor.__qrCodeGeneratorAttached) return;
    editor.__qrCodeGeneratorAttached = true;

    /**
     * Open QR Code Generator Modal
     */
    editor.openQrCodeGenerator = function() {
        // Create modal backdrop
        const backdrop = document.createElement('div');
        backdrop.id = 'ccve-qr-modal-backdrop';
        backdrop.style.cssText = `
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0,0,0,0.7);
            z-index: 100000;
            display: flex;
            align-items: center;
            justify-content: center;
        `;

        // Create modal container
        const modal = document.createElement('div');
        modal.id = 'ccve-qr-modal';
        modal.style.cssText = `
            background: #1e293b;
            border-radius: 12px;
            padding: 24px;
            max-width: 600px;
            width: 90%;
            max-height: 90vh;
            overflow-y: auto;
            box-shadow: 0 20px 60px rgba(0,0,0,0.5);
        `;

        modal.innerHTML = `
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
                <h2 style="margin: 0; color: #f1f5f9; font-size: 24px;">QR Code Generator</h2>
                <button id="ccve-qr-close" style="background: none; border: none; color: #94a3b8; font-size: 28px; cursor: pointer; padding: 0; width: 32px; height: 32px; line-height: 1;">&times;</button>
            </div>

            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 24px;">
                <!-- Left Column: Inputs -->
                <div>
                    <div style="margin-bottom: 16px;">
                        <label style="display: block; color: #cbd5e1; margin-bottom: 6px; font-weight: 500;">URL or Text</label>
                        <input type="text" id="ccve-qr-url" placeholder="https://example.com" style="width: 100%; padding: 10px; background: #0f172a; border: 1px solid #334155; border-radius: 6px; color: #f1f5f9; font-size: 14px;" />
                        <small style="color: #64748b; display: block; margin-top: 4px;">Enter the URL or text to encode</small>
                    </div>

                    <div style="margin-bottom: 16px;">
                        <label style="display: block; color: #cbd5e1; margin-bottom: 6px; font-weight: 500;">Size (pixels)</label>
                        <input type="number" id="ccve-qr-size" value="256" min="128" max="1024" step="64" style="width: 100%; padding: 10px; background: #0f172a; border: 1px solid #334155; border-radius: 6px; color: #f1f5f9; font-size: 14px;" />
                    </div>

                    <div style="margin-bottom: 16px;">
                        <label style="display: block; color: #cbd5e1; margin-bottom: 6px; font-weight: 500;">Foreground Color</label>
                        <div style="display: flex; gap: 8px; align-items: center;">
                            <input type="color" id="ccve-qr-fg-color" value="#000000" style="width: 60px; height: 40px; border: 1px solid #334155; border-radius: 6px; background: #0f172a; cursor: pointer;" />
                            <input type="text" id="ccve-qr-fg-text" value="#000000" style="flex: 1; padding: 10px; background: #0f172a; border: 1px solid #334155; border-radius: 6px; color: #f1f5f9; font-size: 14px;" />
                        </div>
                    </div>

                    <div style="margin-bottom: 16px;">
                        <label style="display: block; color: #cbd5e1; margin-bottom: 6px; font-weight: 500;">Background Color</label>
                        <div style="display: flex; gap: 8px; align-items: center;">
                            <input type="color" id="ccve-qr-bg-color" value="#ffffff" style="width: 60px; height: 40px; border: 1px solid #334155; border-radius: 6px; background: #0f172a; cursor: pointer;" />
                            <input type="text" id="ccve-qr-bg-text" value="#ffffff" style="flex: 1; padding: 10px; background: #0f172a; border: 1px solid #334155; border-radius: 6px; color: #f1f5f9; font-size: 14px;" />
                        </div>
                    </div>

                    <div style="margin-bottom: 16px;">
                        <label style="display: block; color: #cbd5e1; margin-bottom: 6px; font-weight: 500;">Error Correction</label>
                        <select id="ccve-qr-error-level" style="width: 100%; padding: 10px; background: #0f172a; border: 1px solid #334155; border-radius: 6px; color: #f1f5f9; font-size: 14px;">
                            <option value="L">Low (7%)</option>
                            <option value="M" selected>Medium (15%)</option>
                            <option value="Q">Quartile (25%)</option>
                            <option value="H">High (30%)</option>
                        </select>
                        <small style="color: #64748b; display: block; margin-top: 4px;">Higher = more damage resistant</small>
                    </div>
                </div>

                <!-- Right Column: Preview -->
                <div>
                    <label style="display: block; color: #cbd5e1; margin-bottom: 6px; font-weight: 500;">Preview</label>
                    <div id="ccve-qr-preview-container" style="background: #0f172a; border: 1px solid #334155; border-radius: 8px; padding: 20px; display: flex; align-items: center; justify-content: center; min-height: 300px;">
                        <div style="color: #64748b; text-align: center;">
                            <svg style="width: 48px; height: 48px; margin: 0 auto 12px; opacity: 0.5;" fill="currentColor" viewBox="0 0 20 20">
                                <path fill-rule="evenodd" d="M4 3a2 2 0 00-2 2v10a2 2 0 002 2h12a2 2 0 002-2V5a2 2 0 00-2-2H4zm3 2h6v4H7V5zm8 8v2h1v-2h-1zm-2-2H7v4h6v-4zm2 0h1V9h-1v2zm1-4V5h-1v2h1zM5 9H4v2h1V9zm0 4H4v2h1v-2zM5 5H4v2h1V5z" clip-rule="evenodd"/>
                            </svg>
                            <p style="margin: 0;">Enter URL to generate QR code</p>
                        </div>
                    </div>
                    <div id="ccve-qr-error" style="color: #ef4444; margin-top: 8px; font-size: 13px; display: none;"></div>
                </div>
            </div>

            <div style="display: flex; gap: 12px; margin-top: 24px; justify-content: flex-end;">
                <button id="ccve-qr-cancel" class="button" style="padding: 10px 20px;">Cancel</button>
                <button id="ccve-qr-add-to-block" class="button button-primary" style="padding: 10px 20px;" disabled>Add to Content Block</button>
            </div>
        `;

        backdrop.appendChild(modal);
        document.body.appendChild(backdrop);

        // Bind events
        const urlInput = document.getElementById('ccve-qr-url');
        const sizeInput = document.getElementById('ccve-qr-size');
        const fgColorPicker = document.getElementById('ccve-qr-fg-color');
        const fgColorText = document.getElementById('ccve-qr-fg-text');
        const bgColorPicker = document.getElementById('ccve-qr-bg-color');
        const bgColorText = document.getElementById('ccve-qr-bg-text');
        const errorLevel = document.getElementById('ccve-qr-error-level');
        const previewContainer = document.getElementById('ccve-qr-preview-container');
        const errorDiv = document.getElementById('ccve-qr-error');
        const addButton = document.getElementById('ccve-qr-add-to-block');
        const closeButton = document.getElementById('ccve-qr-close');
        const cancelButton = document.getElementById('ccve-qr-cancel');

        let currentQrDataUrl = null;

        // Sync color pickers with text inputs
        fgColorPicker.addEventListener('input', () => fgColorText.value = fgColorPicker.value);
        fgColorText.addEventListener('input', () => {
            if (/^#[0-9A-Fa-f]{6}$/.test(fgColorText.value)) {
                fgColorPicker.value = fgColorText.value;
            }
        });
        bgColorPicker.addEventListener('input', () => bgColorText.value = bgColorPicker.value);
        bgColorText.addEventListener('input', () => {
            if (/^#[0-9A-Fa-f]{6}$/.test(bgColorText.value)) {
                bgColorPicker.value = bgColorText.value;
            }
        });

        // Generate QR code
        function generateQr() {
            const url = urlInput.value.trim();
            if (!url) {
                previewContainer.innerHTML = `
                    <div style="color: #64748b; text-align: center;">
                        <svg style="width: 48px; height: 48px; margin: 0 auto 12px; opacity: 0.5;" fill="currentColor" viewBox="0 0 20 20">
                            <path fill-rule="evenodd" d="M4 3a2 2 0 00-2 2v10a2 2 0 002 2h12a2 2 0 002-2V5a2 2 0 00-2-2H4zm3 2h6v4H7V5zm8 8v2h1v-2h-1zm-2-2H7v4h6v-4zm2 0h1V9h-1v2zm1-4V5h-1v2h1zM5 9H4v2h1V9zm0 4H4v2h1v-2zM5 5H4v2h1V5z" clip-rule="evenodd"/>
                        </svg>
                        <p style="margin: 0;">Enter URL to generate QR code</p>
                    </div>
                `;
                errorDiv.style.display = 'none';
                addButton.disabled = true;
                currentQrDataUrl = null;
                return;
            }

            try {
                // Clear previous QR code
                previewContainer.innerHTML = '';
                errorDiv.style.display = 'none';

                // Create temporary div for QR code generation
                const tempDiv = document.createElement('div');
                
                // Generate QR code using QRCode.js
                if (typeof QRCode === 'undefined') {
                    throw new Error('QRCode library not loaded');
                }

                const size = parseInt(sizeInput.value) || 256;
                const qr = new QRCode(tempDiv, {
                    text: url,
                    width: size,
                    height: size,
                    colorDark: fgColorPicker.value,
                    colorLight: bgColorPicker.value,
                    correctLevel: QRCode.CorrectLevel[errorLevel.value]
                });

                // Wait a bit for QR code to render
                setTimeout(() => {
                    const canvas = tempDiv.querySelector('canvas');
                    if (canvas) {
                        currentQrDataUrl = canvas.toDataURL('image/png');
                        const img = document.createElement('img');
                        img.src = currentQrDataUrl;
                        img.style.maxWidth = '100%';
                        img.style.height = 'auto';
                        img.style.borderRadius = '4px';
                        previewContainer.innerHTML = '';
                        previewContainer.appendChild(img);
                        addButton.disabled = false;
                    }
                }, 100);

            } catch (error) {
                console.error('QR generation error:', error);
                errorDiv.textContent = 'Error generating QR code: ' + error.message;
                errorDiv.style.display = 'block';
                addButton.disabled = true;
                currentQrDataUrl = null;
            }
        }

        // Debounced generation
        let generateTimeout;
        function debouncedGenerate() {
            clearTimeout(generateTimeout);
            generateTimeout = setTimeout(generateQr, 300);
        }

        urlInput.addEventListener('input', debouncedGenerate);
        sizeInput.addEventListener('input', debouncedGenerate);
        fgColorPicker.addEventListener('input', debouncedGenerate);
        fgColorText.addEventListener('change', debouncedGenerate);
        bgColorPicker.addEventListener('input', debouncedGenerate);
        bgColorText.addEventListener('change', debouncedGenerate);
        errorLevel.addEventListener('change', generateQr);

        // Close handlers
        function closeModal() {
            backdrop.remove();
        }
        closeButton.addEventListener('click', closeModal);
        cancelButton.addEventListener('click', closeModal);
        backdrop.addEventListener('click', (e) => {
            if (e.target === backdrop) closeModal();
        });

        // Helper function to upload QR code to WordPress media library
        async function uploadQrCodeToWordPress(dataUrl, sourceUrl) {
            // Convert data URL to Blob
            const response = await fetch(dataUrl);
            const blob = await response.blob();
            
            // Create a unique filename based on source URL
            const urlHash = sourceUrl.replace(/[^a-z0-9]/gi, '_').slice(0, 30);
            const timestamp = Date.now();
            const filename = `qr-code-${urlHash}-${timestamp}.png`;
            
            // Create FormData for upload
            const formData = new FormData();
            formData.append('file', blob, filename);
            
            // Upload to WordPress REST API
            const uploadResponse = await fetch('/wp-json/wp/v2/media', {
                method: 'POST',
                headers: {
                    'X-WP-Nonce': window.wpApiSettings?.nonce || window.ccEditorData?.nonce || ''
                },
                body: formData
            });
            
            if (!uploadResponse.ok) {
                throw new Error(`Upload failed: ${uploadResponse.status} ${uploadResponse.statusText}`);
            }
            
            const mediaItem = await uploadResponse.json();
            return mediaItem.source_url; // Return the actual URL
        }

        // Add to content block
        addButton.addEventListener('click', async () => {
            if (!currentQrDataUrl) return;

            try {
                // Disable button during upload
                addButton.disabled = true;
                addButton.textContent = 'Uploading...';
                
                // Upload QR code to WordPress media library (required for Roku compatibility)
                let finalUrl;
                try {
                    finalUrl = await uploadQrCodeToWordPress(currentQrDataUrl, urlInput.value);
                    console.log('[QR Generator] Uploaded QR code to WordPress:', finalUrl);
                } catch (uploadError) {
                    console.warn('[QR Generator] Failed to upload QR to media library, falling back to data URL:', uploadError);
                    // Fallback to data URL (will work on web but not Roku)
                    finalUrl = currentQrDataUrl;
                }
                
                // Add as draggable image layer (similar to token-image but with static URL)
                if (!editor.currentConfig) editor.currentConfig = editor.getDefaultConfig();
                if (!Array.isArray(editor.currentConfig.layers)) editor.currentConfig.layers = [];
                
                const layers = editor.currentConfig.layers;
                const existingQrs = layers.filter(l=>l && l.kind==='qr-image').length;
                const id = 'qr_' + Math.random().toString(36).slice(2,9);
                const size = parseInt(sizeInput.value) || 256;
                
                // Get container bounds for proper positioning (container-relative coords)
                const layout = editor.currentConfig?.layout;
                const containerW = layout?.width || 1280;
                const containerH = layout?.height || 720;
                
                // Position QR code within container bounds (container-relative)
                let qrX = 60 + (existingQrs * (size + 12));
                let qrY = 0; // Start at top of container (not 200 which is outside lower-third)
                
                // Clamp to container bounds
                qrX = Math.max(0, Math.min(containerW - size, qrX));
                qrY = Math.max(0, Math.min(containerH - size, qrY));
                
                const layerObj = {
                    id,
                    kind: 'qr-image',
                    url: finalUrl,  // Use uploaded URL (not data URL)
                    sourceUrl: urlInput.value,
                    x: qrX,  // Container-relative X
                    y: qrY,  // Container-relative Y
                    width: size,
                    height: size,
                    visible: true,
                    lock: false
                };
                
                layers.push(layerObj);
                
                // Create DOM element using unified renderer for consistency
                const stage = document.getElementById('block-stage');
                if (stage) {
                    // Get container offset for canvas-absolute positioning
                    const offsetX = layout?.position?.x || layout?._originalPosition?.x || 0;
                    const offsetY = layout?.position?.y || layout?._originalPosition?.y || 0;
                    const canvasX = layerObj.x + offsetX;
                    const canvasY = layerObj.y + offsetY;
                    
                    const node = document.createElement('div');
                    // IMPORTANT: Include unified-layer class for drag handlers to attach!
                    node.className = 'canvas-container unified-layer unified-layer--qr-image';
                    node.setAttribute('data-layer-id', id);
                    node.setAttribute('data-layer-kind', 'qr-image');
                    node.style.cssText = `
                        position: absolute;
                        left: ${canvasX}px;
                        top: ${canvasY}px;
                        width: ${layerObj.width}px;
                        height: ${layerObj.height}px;
                        display: flex;
                        align-items: center;
                        justify-content: center;
                        overflow: hidden;
                        border-radius: 8px;
                        background: #fff;
                        cursor: move;
                        z-index: 10;
                    `;
                    
                    const img = document.createElement('img');
                    img.src = finalUrl;  // Use uploaded URL
                    img.alt = `QR Code: ${urlInput.value}`;
                    img.style.cssText = 'width: 100%; height: 100%; object-fit: contain; display: block;';
                    node.appendChild(img);
                    stage.appendChild(node);
                }
                
                editor.unsavedChanges = true;
                try { editor.updateSaveButton && editor.updateSaveButton(); } catch(_) {}
                try { editor.buildLayersPanel && editor.buildLayersPanel(); } catch(_) {}
                
                editor.showNotification && editor.showNotification('QR code added as image layer!', 'success');
                closeModal();
            } catch (error) {
                console.error('Error adding QR code:', error);
                errorDiv.textContent = 'Error adding QR code: ' + error.message;
                errorDiv.style.display = 'block';
                addButton.disabled = false;
                addButton.textContent = 'Add to Content Block';
            }
        });

        // Focus URL input
        setTimeout(() => urlInput.focus(), 100);
    };

    // Attach click handler to button
    const qrButton = document.getElementById('ccve-qr-code-tab-btn');
    
    if (qrButton) {
        qrButton.addEventListener('click', (e) => {
            e.preventDefault();
            e.stopPropagation();
            editor.openQrCodeGenerator();
        });
    } else {
        // Retry if button not immediately available
        setTimeout(() => {
            const btn = document.getElementById('ccve-qr-code-tab-btn');
            if (btn) {
                btn.addEventListener('click', (e) => {
                    e.preventDefault();
                    e.stopPropagation();
                    editor.openQrCodeGenerator();
                });
            }
        }, 100);
    }
}

export default { attachQrCodeGenerator };
