/**
 * TamRank™ Total Score Widget JavaScript
 *
 * Live score updates die de Meta Score (30%) en Content Score (70%)
 * combineren tot één TamRank™ Score.
 *
 * @package TamRank
 * @since 6.3.0
 */

(function ($) {
    'use strict';

    // Score drempelwaarden en kleuren
    const THRESHOLDS = {
        EXCELLENT: 80,
        GOOD: 60,
        FAIR: 40
    };

    const COLORS = {
        GREEN: '#25AC75',
        BLUE: '#3b82f6',
        ORANGE: '#FAA530',
        PINK: '#DC7EA0'
    };

    const WEIGHTS = {
        META: 0.30,
        CONTENT: 0.70
    };

    /**
     * TamRank Total Score Controller
     */
    const TamRankTotalScore = {
        // Cached elements
        $widget: null,
        $totalScoreValue: null,
        $totalScoreLabel: null,
        $totalScoreBadge: null,
        $metaScoreValue: null,
        $metaProgress: null,
        $contentScoreValue: null,
        $contentProgress: null,

        // Current scores
        currentMetaScore: 0,
        currentContentScore: 0,
        currentTotalScore: 0,

        // Debounce timer
        updateTimer: null,
        debounceDelay: 300,

        /**
         * Initialize the controller
         */
        init: function () {
            this.cacheElements();

            if (!this.$widget.length) {
                return;
            }

            this.bindEvents();
            this.initializeScores();

            // Listen for content score updates from content-tab.js
            $(document).on('tamrank:contentScoreUpdated', this.onContentScoreUpdated.bind(this));
        },

        /**
         * Cache DOM elements
         */
        cacheElements: function () {
            this.$widget = $('#tamrank-total-score-widget');
            this.$totalScoreValue = $('#tamrank-total-score-value');
            this.$totalScoreLabel = $('#tamrank-total-score-label');
            this.$totalScoreBadge = this.$widget.find('.tamrank-score-badge');
            this.$metaScoreValue = $('#tamrank-meta-score-value');
            this.$metaProgress = $('#tamrank-meta-progress');
            this.$contentScoreValue = $('#tamrank-content-score-value');
            this.$contentProgress = $('#tamrank-content-progress');
        },

        /**
         * Bind event listeners
         */
        bindEvents: function () {
            // Meta fields that affect score
            const $metaTitle = $('#_tam_rank_meta_title');
            const $metaDesc = $('#_tam_rank_meta_description');
            const $focusKeyword = $('#_tam_rank_focus_keyword');
            const $customSlug = $('#_tam_rank_custom_slug');

            // Listen for input changes
            $metaTitle.on('input', this.debounceMetaUpdate.bind(this));
            $metaDesc.on('input', this.debounceMetaUpdate.bind(this));
            $focusKeyword.on('input', this.debounceMetaUpdate.bind(this));
            $customSlug.on('input', this.debounceMetaUpdate.bind(this));

            // Toggle details button
            $('#tamrank-toggle-details').on('click', this.toggleDetails.bind(this));

            // Listen for tab changes
            $('.tam-meta-tab').on('click', this.onTabChange.bind(this));
        },

        /**
         * Initialize scores from server data
         */
        initializeScores: function () {
            // Get initial scores from data attributes or calculated values
            const initialMetaScore = parseInt(this.$metaScoreValue.text()) || 0;
            const initialContentScore = parseInt(this.$contentScoreValue.text()) || 0;

            this.currentMetaScore = initialMetaScore;
            this.currentContentScore = initialContentScore;
            this.currentTotalScore = this.calculateTotalScore(initialMetaScore, initialContentScore);
        },

        /**
         * Debounce meta score updates
         */
        debounceMetaUpdate: function () {
            clearTimeout(this.updateTimer);
            this.updateTimer = setTimeout(this.updateMetaScore.bind(this), this.debounceDelay);
        },

        /**
         * Calculate and update meta score
         */
        updateMetaScore: function () {
            const metaTitle = $('#_tam_rank_meta_title').val() || '';
            const metaDesc = $('#_tam_rank_meta_description').val() || '';
            const focusKeyword = $('#_tam_rank_focus_keyword').val() || '';
            const customSlug = $('#_tam_rank_custom_slug').val() || '';

            // Ensure tamRankMeta is available
            if (typeof tamRankMeta === 'undefined' || !tamRankMeta.ajaxUrl) {
                console.warn('TamRank: tamRankMeta not defined');
                return;
            }

            // AJAX call to central score service
            $.ajax({
                url: tamRankMeta.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'tam_rank_calculate_score',
                    nonce: tamRankMeta.nonce,
                    title: metaTitle,
                    description: metaDesc,
                    focus_keyword: focusKeyword,
                    slug: customSlug
                },
                success: function (response) {
                    if (response.success && typeof response.data.score !== 'undefined') {
                        this.currentMetaScore = parseInt(response.data.score);
                        this.updateDisplay();
                    }
                }.bind(this),
                error: function (xhr, status, error) {
                    console.error('TamRank: Score calculation failed', error);
                }
            });
        },

        /* Client-side calculation removed in favor of AJAX service */

        /**
         * Simple slugify function
         *
         * @param {string} text Text to slugify
         * @return {string} Slugified text
         */
        slugify: function (text) {
            if (!text) return '';
            return text.toLowerCase()
                .replace(/[^a-z0-9]+/g, '-')
                .replace(/^-+|-+$/g, '');
        },

        /**
         * Calculate total score
         *
         * @param {number} metaScore Meta score (0-100)
         * @param {number} contentScore Content score (0-100)
         * @return {number} Total score (0-100)
         */
        calculateTotalScore: function (metaScore, contentScore) {
            return Math.round(metaScore * WEIGHTS.META + contentScore * WEIGHTS.CONTENT);
        },

        /**
         * Get color for a score
         *
         * @param {number} score Score (0-100)
         * @return {string} Hex color
         */
        getScoreColor: function (score) {
            if (score >= THRESHOLDS.EXCELLENT) {
                return COLORS.GREEN;
            } else if (score >= THRESHOLDS.GOOD) {
                return COLORS.BLUE;
            } else if (score >= THRESHOLDS.FAIR) {
                return COLORS.ORANGE;
            }
            return COLORS.PINK;
        },

        /**
         * Get label for a score
         *
         * @param {number} score Score (0-100)
         * @return {string} Label
         */
        getScoreLabel: function (score) {
            if (score >= THRESHOLDS.EXCELLENT) {
                return tamRankTotalScore.strings.score_excellent;
            } else if (score >= THRESHOLDS.GOOD) {
                return tamRankTotalScore.strings.score_good;
            } else if (score >= THRESHOLDS.FAIR) {
                return tamRankTotalScore.strings.score_fair;
            }
            return tamRankTotalScore.strings.score_poor;
        },

        /**
         * Update the display with current scores
         */
        updateDisplay: function () {
            const totalScore = this.calculateTotalScore(this.currentMetaScore, this.currentContentScore);
            const totalColor = this.getScoreColor(totalScore);
            const totalLabel = this.getScoreLabel(totalScore);

            const metaColor = this.getScoreColor(this.currentMetaScore);
            const contentColor = this.getScoreColor(this.currentContentScore);

            // Animate badge
            this.$totalScoreBadge.addClass('updating');

            // Update total score
            this.$totalScoreValue.text(totalScore);
            this.$totalScoreBadge.css('background', totalColor);
            this.$totalScoreLabel.text(totalLabel).css('color', totalColor);

            // Update meta score
            this.$metaScoreValue.text(this.currentMetaScore + '%').css('color', metaColor);
            this.$metaProgress.css({
                'width': this.currentMetaScore + '%',
                'background': metaColor
            });

            // Update content score
            this.$contentScoreValue.text(this.currentContentScore + '%').css('color', contentColor);
            this.$contentProgress.css({
                'width': this.currentContentScore + '%',
                'background': contentColor
            });

            // Remove animation class after animation completes
            setTimeout(function () {
                this.$totalScoreBadge.removeClass('updating');
            }.bind(this), 300);

            // Also update the existing live score display in SEO tab (if present)
            this.updateLegacyScoreDisplay(this.currentMetaScore);

            // Store current total
            this.currentTotalScore = totalScore;

            // Trigger event for other scripts
            $(document).trigger('tamrank:totalScoreUpdated', {
                total: totalScore,
                meta: this.currentMetaScore,
                content: this.currentContentScore
            });
        },

        /**
         * Update legacy score display (compatibility)
         *
         * @param {number} metaScore Meta score
         */
        updateLegacyScoreDisplay: function (metaScore) {
            const $legacyValue = $('#live-score-value-main');
            const $legacyBar = $('#live-score-bar-main');

            if ($legacyValue.length) {
                const color = this.getScoreColor(metaScore);
                $legacyValue.text(metaScore + '%').css('color', color);
                $legacyBar.css({
                    'width': metaScore + '%',
                    'background': color
                });
            }
        },

        /**
         * Handle content score updates from content-tab.js
         *
         * @param {Event} event jQuery event
         * @param {Object} data Score data
         */
        onContentScoreUpdated: function (event, data) {
            if (data && typeof data.score !== 'undefined') {
                this.currentContentScore = parseInt(data.score) || 0;
                this.updateDisplay();
            }
        },

        /**
         * Handle tab changes
         *
         * @param {Event} e Click event
         */
        onTabChange: function (e) {
            const $tab = $(e.currentTarget);
            const tabId = $tab.data('tab');

            // When switching to Content tab, trigger a content analysis
            if (tabId === 'content') {
                // Check if content analysis should be triggered
                setTimeout(function () {
                    const $analyzeBtn = $('#tam-content-analyze-btn');
                    if ($analyzeBtn.length && !$analyzeBtn.prop('disabled')) {
                        // Optionally auto-analyze
                        // $analyzeBtn.trigger('click');
                    }
                }, 100);
            }
        },

        /**
         * Toggle details panel
         *
         * @param {Event} e Click event
         */
        toggleDetails: function (e) {
            e.preventDefault();
            const $btn = $(e.currentTarget);
            const $text = $btn.find('.tamrank-toggle-text');

            $btn.toggleClass('active');

            if ($btn.hasClass('active')) {
                $text.text(tamRankTotalScore.strings.hide_details);
                // Trigger event to show detailed breakdown
                $(document).trigger('tamrank:showScoreDetails');
            } else {
                $text.text(tamRankTotalScore.strings.view_details);
                $(document).trigger('tamrank:hideScoreDetails');
            }
        },

        /**
         * Set content score externally
         *
         * @param {number} score Content score (0-100)
         */
        setContentScore: function (score) {
            this.currentContentScore = parseInt(score) || 0;
            this.updateDisplay();
        },

        /**
         * Get current scores
         *
         * @return {Object} Current scores
         */
        getScores: function () {
            return {
                total: this.currentTotalScore,
                meta: this.currentMetaScore,
                content: this.currentContentScore
            };
        },

        /**
         * Refresh scores from server
         */
        refreshFromServer: function () {
            const postId = this.$widget.data('post-id');

            if (!postId || !tamRankTotalScore || !tamRankTotalScore.ajaxUrl) {
                return;
            }

            $.ajax({
                url: tamRankTotalScore.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'tamrank_get_total_score',
                    nonce: tamRankTotalScore.nonce,
                    post_id: postId
                },
                success: function (response) {
                    if (response.success && response.data) {
                        this.currentMetaScore = parseInt(response.data.meta.score) || 0;
                        this.currentContentScore = parseInt(response.data.content.score) || 0;
                        this.updateDisplay();
                    }
                }.bind(this)
            });
        }
    };

    // Initialize on document ready
    $(document).ready(function () {
        TamRankTotalScore.init();
    });

    // Expose for external use
    window.TamRankTotalScore = TamRankTotalScore;

})(jQuery);
