/**
 * Schema Builder - SEO Scoring
 * 
 * Real-time SEO score calculation and display
 * 
 * @package CustomSchemaSchemafy
 * @since 2.0.0
 */

(function ($) {
    'use strict';

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

    /**
     * SEO Scoring Handler
     */
    SchemafyBuilder.Scoring = {

        /**
         * Score display element
         */
        $scoreValue: null,
        $scoreFill: null,
        $scoreLabel: null,
        $checklist: null,

        /**
         * Current score
         */
        currentScore: 0,

        /**
         * Initialize scoring
         */
        init: function () {
            this.$scoreValue = $('#schemafy-seo-score-value');
            this.$scoreFill = $('#schemafy-seo-score-fill');
            this.$scoreLabel = $('#schemafy-seo-score-label');
            this.$checklist = $('#schemafy-seo-checklist');
        },

        /**
         * Calculate SEO score
         */
        calculate: function (fieldConfig, fieldValues) {
            if (!this.$scoreValue) {
                this.init();
            }

            if (!fieldConfig || !fieldConfig.fields) {
                return;
            }

            let score = 0;
            let maxScore = 0;
            const checklist = [];

            // Calculate score based on field weights
            fieldConfig.fields.forEach(function (field) {
                if (field.seoWeight && field.seoWeight > 0) {
                    maxScore += field.seoWeight;

                    const value = this.getFieldValue(fieldValues, field.name);
                    const hasValue = this.hasValue(value);

                    if (hasValue) {
                        let fieldScore = field.seoWeight;

                        // Bonus for meeting minimum length
                        if (field.validation && field.validation.minLength) {
                            if (String(value).length >= field.validation.minLength) {
                                fieldScore += 5;
                            }
                        }

                        // Penalty for exceeding max length
                        if (field.maxLength) {
                            if (String(value).length > field.maxLength * 0.9) {
                                fieldScore -= 3;
                            }
                        }

                        score += Math.max(0, fieldScore);

                        checklist.push({
                            label: field.label,
                            valid: true
                        });
                    } else if (field.required) {
                        checklist.push({
                            label: field.label,
                            valid: false
                        });
                    }
                }
            }.bind(this));

            // Calculate percentage
            const percentage = maxScore > 0 ? Math.min(100, Math.round((score / maxScore) * 100)) : 0;

            this.updateDisplay(percentage, checklist);
        },

        /**
         * Get field value from values object
         */
        getFieldValue: function (values, fieldName) {
            // Handle nested fields (e.g., "author.name")
            if (fieldName.includes('.')) {
                const parts = fieldName.split('.');
                let value = values;

                for (let i = 0; i < parts.length; i++) {
                    if (value && typeof value === 'object') {
                        value = value[parts[i]];
                    } else {
                        return null;
                    }
                }

                return value;
            }

            return values[fieldName];
        },

        /**
         * Check if value exists and is not empty
         */
        hasValue: function (value) {
            if (value === null || value === undefined) {
                return false;
            }

            if (typeof value === 'string') {
                return value.trim().length > 0;
            }

            if (Array.isArray(value)) {
                return value.length > 0;
            }

            if (typeof value === 'object') {
                return Object.keys(value).length > 0;
            }

            return true;
        },

        /**
         * Update score display
         */
        updateDisplay: function (score, checklist) {
            this.currentScore = score;

            // Update score value
            if (this.$scoreValue) {
                this.$scoreValue.text(score + '/100');
            }

            // Update progress bar
            if (this.$scoreFill) {
                this.$scoreFill.css('width', score + '%');

                // Update color based on score
                let level = 'poor';
                if (score >= 90) {
                    level = 'excellent';
                } else if (score >= 70) {
                    level = 'good';
                } else if (score >= 50) {
                    level = 'needs-work';
                }

                this.$scoreFill.attr('data-score', level);
            }

            // Update label
            if (this.$scoreLabel) {
                let labelText = schemafyBuilder.i18n.poor;

                if (score >= 90) {
                    labelText = '✅ ' + schemafyBuilder.i18n.excellent;
                } else if (score >= 70) {
                    labelText = '📘 ' + schemafyBuilder.i18n.good;
                } else if (score >= 50) {
                    labelText = '⚠️ ' + schemafyBuilder.i18n.needs_work;
                } else {
                    labelText = '❌ ' + schemafyBuilder.i18n.poor;
                }

                this.$scoreLabel.text(labelText);
            }

            // Update checklist
            if (this.$checklist && checklist) {
                this.$checklist.empty();

                checklist.forEach(function (item) {
                    const $item = $('<li>')
                        .addClass('schemafy-seo-checklist-item')
                        .addClass(item.valid ? 'valid' : 'invalid')
                        .html((item.valid ? '✓ ' : '⚠ ') + item.label);

                    this.$checklist.append($item);
                }.bind(this));
            }
        },

        /**
         * Get current score
         */
        getScore: function () {
            return this.currentScore;
        }
    };

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

})(jQuery);
