/**
 * Schema Builder - Google Preview
 * 
 * Real-time Google search result preview
 * 
 * @package CustomSchemaSchemafy
 * @since 2.0.0
 */

(function ($) {
    'use strict';

    window.SchemafyBuilder = window.SchemafyBuilder || {};

    /**
     * Google Preview Handler
     */
    SchemafyBuilder.Preview = {

        /**
         * Desktop preview container
         */
        $desktopPreview: null,

        /**
         * Mobile preview container
         */
        $mobilePreview: null,

        /**
         * Initialize preview
         */
        init: function () {
            this.$desktopPreview = $('#schemafy-preview-desktop');
            this.$mobilePreview = $('#schemafy-preview-mobile');
        },

        /**
         * Update preview with field values
         */
        update: function (fieldValues) {
            if (!this.$desktopPreview || !this.$mobilePreview) {
                this.init();
            }

            // Extract relevant fields based on schema type
            const schemaType = SchemafyBuilder.App.currentSchemaType;

            switch (schemaType) {
                case 'Article':
                    this.renderArticlePreview(fieldValues);
                    break;

                case 'Product':
                    this.renderProductPreview(fieldValues);
                    break;

                case 'LocalBusiness':
                case 'Organization':
                    this.renderBusinessPreview(fieldValues);
                    break;

                default:
                    this.renderGenericPreview(fieldValues);
            }
        },

        /**
         * Render Article preview
         */
        renderArticlePreview: function (values) {
            const headline = values.headline || 'Article Headline';
            const description = values.description || 'Article description will appear here...';
            const authorName = values.authorName || 'Author Name';
            const datePublished = values.datePublished || new Date().toISOString();
            const image = values.image || '';

            // Format date
            const date = new Date(datePublished);
            const formattedDate = date.toLocaleDateString('en-US', {
                month: 'short',
                day: 'numeric',
                year: 'numeric'
            });

            // Desktop preview
            const desktopHTML = `
                <div class="schemafy-google-preview desktop">
                    <div class="preview-url">${schemafyBuilder.site_url.replace(/^https?:\/\//, '')}</div>
                    <h3 class="preview-title">${this.truncate(headline, 60)}</h3>
                    <div class="preview-meta">
                        <span>${authorName}</span> · 
                        <span>${formattedDate}</span>
                    </div>
                    <p class="preview-description">${this.truncate(description, 160)}</p>
                    ${image ? `<div class="preview-image"><img src="${image}" /></div>` : ''}
                </div>
            `;

            // Mobile preview
            const mobileHTML = `
                <div class="schemafy-google-preview mobile">
                    ${image ? `<div class="preview-image-top"><img src="${image}" /></div>` : ''}
                    <h3 class="preview-title">${this.truncate(headline, 50)}</h3>
                    <div class="preview-url">${schemafyBuilder.site_url.replace(/^https?:\/\//, '')}</div>
                    <p class="preview-description">${this.truncate(description, 120)}</p>
                </div>
            `;

            this.$desktopPreview.html(desktopHTML);
            this.$mobilePreview.html(mobileHTML);
        },

        /**
         * Render Product preview
         */
        renderProductPreview: function (values) {
            const name = values.productName || values.name || 'Product Name';
            const description = values.description || 'Product description...';
            const price = values.price || '';
            const currency = values.currency || 'USD';
            const rating = values.ratingValue || '';
            const image = values.image || '';

            const priceDisplay = price ? `${currency} ${price}` : '';
            const ratingDisplay = rating ? `⭐ ${rating}/5` : '';

            const desktopHTML = `
                <div class="schemafy-google-preview desktop">
                    <div class="preview-url">${schemafyBuilder.site_url.replace(/^https?:\/\//, '')}</div>
                    <h3 class="preview-title">${this.truncate(name, 60)}</h3>
                    ${priceDisplay ? `<div class="preview-price">${priceDisplay}</div>` : ''}
                    ${ratingDisplay ? `<div class="preview-rating">${ratingDisplay}</div>` : ''}
                    <p class="preview-description">${this.truncate(description, 160)}</p>
                    ${image ? `<div class="preview-image"><img src="${image}" /></div>` : ''}
                </div>
            `;

            this.$desktopPreview.html(desktopHTML);
            this.$mobilePreview.html(desktopHTML.replace('desktop', 'mobile'));
        },

        /**
         * Render Business preview
         */
        renderBusinessPreview: function (values) {
            const name = values.organizationName || values.name || 'Business Name';
            const description = values.description || 'Business description...';
            const address = values.addressLocality || '';
            const phone = values.telephone || '';
            const image = values.logo || values.image || '';

            const desktopHTML = `
                <div class="schemafy-google-preview desktop">
                    <div class="preview-url">${schemafyBuilder.site_url.replace(/^https?:\/\//, '')}</div>
                    <h3 class="preview-title">${this.truncate(name, 60)}</h3>
                    ${address ? `<div class="preview-address">📍 ${address}</div>` : ''}
                    ${phone ? `<div class="preview-phone">📞 ${phone}</div>` : ''}
                    <p class="preview-description">${this.truncate(description, 160)}</p>
                    ${image ? `<div class="preview-image"><img src="${image}" /></div>` : ''}
                </div>
            `;

            this.$desktopPreview.html(desktopHTML);
            this.$mobilePreview.html(desktopHTML.replace('desktop', 'mobile'));
        },

        /**
         * Render generic preview
         */
        renderGenericPreview: function (values) {
            const title = values.headline || values.name || values.title || 'Page Title';
            const description = values.description || 'Page description...';

            const html = `
                <div class="schemafy-google-preview desktop">
                    <div class="preview-url">${schemafyBuilder.site_url.replace(/^https?:\/\//, '')}</div>
                    <h3 class="preview-title">${this.truncate(title, 60)}</h3>
                    <p class="preview-description">${this.truncate(description, 160)}</p>
                </div>
            `;

            this.$desktopPreview.html(html);
            this.$mobilePreview.html(html.replace('desktop', 'mobile'));
        },

        /**
         * Truncate text to max length
         */
        truncate: function (text, maxLength) {
            if (!text || text.length <= maxLength) {
                return text;
            }

            return text.substring(0, maxLength) + '...';
        },

        /**
         * Escape HTML
         */
        // One escaping implementation for the whole admin, and one that
        // escapes quotes so attribute interpolation is safe too.
        escapeHtml: function (text) {
            return window.SchemafyUtilities.escapeHtml(text);
        }
    };

    // Initialize on document ready
    $(document).ready(function () {
        if (typeof schemafyBuilder !== 'undefined') {
            SchemafyBuilder.Preview.init();
        }
    });

})(jQuery);
