import QRCode from 'qrcode';

// Import WordPress i18n function
const { __ } = wp.i18n;

(function($) {
    'use strict';

    /**
     * QR Code Modal functionality
     */
    class LinkCentralQRModal {
        constructor() {
            this.modal = null;
            this.canvas = null;
            this.currentUrl = '';
            this.svgData = '';
            this.init();
        }

        init() {
            this.modal = $('#linkcentral-qr-modal');
            this.canvas = document.getElementById('linkcentral-qr-canvas');
            
            // Only proceed if modal exists
            if (!this.modal.length || !this.canvas) {
                return;
            }

            this.bindEvents();
        }

        bindEvents() {
            // Generate QR Code button
            $(document).on('click', '#linkcentral-generate-qr', (e) => {
                e.preventDefault();
                this.openModal();
            });

            // Close modal
            $(document).on('click', '.linkcentral-qr-modal-close', (e) => {
                e.preventDefault();
                this.closeModal();
            });

            // Close modal when clicking outside
            $(document).on('click', '#linkcentral-qr-modal', (e) => {
                if (e.target === this.modal[0]) {
                    this.closeModal();
                }
            });

            // Download QR code PNG
            $(document).on('click', '#linkcentral-qr-download-png', (e) => {
                e.preventDefault();
                this.downloadQRCode('png');
            });

            // Download QR code SVG
            $(document).on('click', '#linkcentral-qr-download-svg', (e) => {
                e.preventDefault();
                this.downloadQRCode('svg');
            });



            // Close modal with escape key
            $(document).on('keydown', (e) => {
                if (e.keyCode === 27 && this.modal.is(':visible')) {
                    this.closeModal();
                }
            });
        }

        openModal() {
            const url = this.generateShortUrl();
            if (!url) {
                alert(__('Please enter a slug first to generate a QR code.', 'linkcentral'));
                return;
            }

            this.currentUrl = url;
            this.generateQRCode(url);
            this.updateUrlDisplay(url);
            this.modal.show();
        }

        closeModal() {
            this.modal.hide();
        }

        generateShortUrl() {
            // Get the slug from the slug input
            const slug = $('#post_name').val();
            if (!slug) {
                return null;
            }

            // Check the current prefix toggle state
            const isPrefixDisabled = $('#linkcentral_disable_slug_prefix').val() === '1';
            
            if (isPrefixDisabled) {
                // Prefix is disabled, get just the home URL without prefix
                const $prefixElement = $('#linkcentral-url-prefix');
                const homeUrl = $prefixElement.data('home-url'); // Use data attribute for clean URL
                return homeUrl + slug;
            } else {
                // Prefix is enabled, use the full content including prefix
                const urlPrefix = $('#linkcentral-url-prefix').text().trim();
                return urlPrefix + slug;
            }
        }

        async generateQRCode(url) {
            try {
                // Clear previous QR code
                const ctx = this.canvas.getContext('2d');
                ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);

                // Set canvas size
                this.canvas.width = 256;
                this.canvas.height = 256;

                // Get custom colors from settings
                const bgColor = this.getQRColorSetting('linkcentral_qr_background_color', '#FFFFFF');
                const frontColor = this.getQRColorSetting('linkcentral_qr_front_color', '#000000');
                const isBgTransparent = this.getQRSetting('linkcentral_qr_background_transparent', false) === true || this.getQRSetting('linkcentral_qr_background_transparent', false) === '1';

                // Convert to hex with alpha (QR library expects hex, not rgba())
                const bgHex = this.hexWithAlpha(bgColor, isBgTransparent ? 0 : 1);
                const frontHex = this.hexWithAlpha(frontColor, 1);

                // Generate QR code options
                const qrOptions = {
                    width: 256,
                    margin: 2,
                    color: {
                        dark: frontHex,
                        light: bgHex
                    }
                };

                // Generate both canvas and SVG simultaneously for instant downloads
                const [canvasResult, svgResult] = await Promise.all([
                    QRCode.toCanvas(this.canvas, url, qrOptions),
                    new Promise((resolve, reject) => {
                        QRCode.toString(url, { ...qrOptions, type: 'svg' }, (err, string) => {
                            if (err) reject(err);
                            else resolve(string);
                        });
                    })
                ]);

                this.svgData = svgResult;
                console.log('QR Code generated successfully');
            } catch (err) {
                console.error('Error generating QR code:', err);
                alert(__('Error generating QR code. Please try again.', 'linkcentral'));
            }
        }

        updateUrlDisplay(url) {
            $('#linkcentral-qr-url').text(url);
        }

        downloadQRCode(format = 'png') {
            if (!this.canvas && format === 'png') return;
            if (!this.svgData && format === 'svg') return;

            try {
                // Create download link
                const link = document.createElement('a');

                if (format === 'svg') {
                    // Download SVG
                    const blob = new Blob([this.svgData], { type: 'image/svg+xml' });
                    link.download = `qr-code-${this.getSlugForFilename()}.svg`;
                    link.href = URL.createObjectURL(blob);
                } else {
                    // Download PNG (default)
                    link.download = `qr-code-${this.getSlugForFilename()}.png`;
                    link.href = this.canvas.toDataURL('image/png');
                }

                // Trigger download
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);

                // Clean up blob URL for SVG
                if (format === 'svg') {
                    URL.revokeObjectURL(link.href);
                }
            } catch (err) {
                console.error('Error downloading QR code:', err);
                alert(__('Error downloading QR code. Please try again.', 'linkcentral'));
            }
        }



        getSlugForFilename() {
            const slug = $('#post_name').val() || 'qr-code';
            return slug.replace(/[^a-z0-9]/gi, '-').toLowerCase();
        }
        
        /**
         * Get QR color setting from WordPress options
         * @param {string} optionName - The option name to retrieve
         * @param {string} defaultValue - Default value if option doesn't exist
         * @returns {string} The color value
         */
        getQRColorSetting(optionName, defaultValue) {
            // Try to get from localized data first (if available)
            if (window.linkcentral_qr_settings && window.linkcentral_qr_settings[optionName]) {
                return window.linkcentral_qr_settings[optionName];
            }
            
            // Fallback to default value
            return defaultValue;
        }
        
        /**
         * Get QR setting from WordPress options
         * @param {string} optionName - The option name to retrieve
         * @param {any} defaultValue - Default value if option doesn't exist
         * @returns {any} The setting value
         */
        getQRSetting(optionName, defaultValue) {
            if (window.linkcentral_qr_settings && optionName in window.linkcentral_qr_settings) {
                return window.linkcentral_qr_settings[optionName];
            }
            return defaultValue;
        }
        
        /**
         * Return #RRGGBB or #RRGGBBAA depending on alpha
         * @param {string} hex - Color like #RGB or #RRGGBB
         * @param {number} alpha - 0..1
         * @returns {string}
         */
        hexWithAlpha(hex, alpha) {
            if (!hex) return '#000000';
            // Normalize to 6-digit
            let h = hex.trim();
            if (h[0] === '#') h = h.slice(1);
            if (h.length === 3) {
                h = h.split('').map(c => c + c).join('');
            }
            if (h.length !== 6) {
                // Fallback
                h = '000000';
            }
            // Map alpha 0..1 to 00..FF
            const a = Math.round(Math.max(0, Math.min(1, alpha)) * 255);
            const aHex = a.toString(16).padStart(2, '0').toUpperCase();
            if (aHex === 'FF') {
                return `#${h.toUpperCase()}`;
            }
            return `#${h.toUpperCase()}${aHex}`;
        }
    }

    // Initialize when document is ready
    $(document).ready(function() {
        new LinkCentralQRModal();
    });

})(jQuery);
