/**
 * Consolety Dashboard JavaScript
 *
 * @package Consolety
 * @since 1.0.0
 */

/* global jQuery, consoletyDashboard */

(function($) {
    'use strict';

    const VP = {
        ajaxUrl: consoletyDashboard.ajaxUrl,
        nonce: consoletyDashboard.nonce,
        i18n: consoletyDashboard.i18n
    };

    let categoriesCache = [];

    // Language is auto-detected from WordPress locale (get_locale())
    // No hardcoded language list needed anymore

    function loadPointsHistory() {
        $.post(VP.ajaxUrl, {
            action: 'consolety_fetch_points_history',
            nonce: VP.nonce,
            limit: 10
        }, function(response) {
            var container = $('#points-history-container');
            var transactions = [];

            if (!response || !response.success) {
                container.html('<p class="vp-points-empty">' + VP.i18n.failedToLoad + '</p>');
                return;
            }

            // Support multiple payload shapes from Hub/API wrappers
            if (Array.isArray(response.data)) {
                transactions = response.data;
            } else if (response.data && Array.isArray(response.data.transactions)) {
                transactions = response.data.transactions;
            } else if (response.data && Array.isArray(response.data.data)) {
                transactions = response.data.data;
            }

            if (transactions.length === 0) {
                container.html('<p class="vp-points-empty">' + VP.i18n.noHistory + '</p>');
                return;
            }

            var html = '<table class="vp-points-table"><thead><tr>';
            html += '<th>' + VP.i18n.activity + '</th>';
            html += '<th>' + VP.i18n.points + '</th>';
            html += '<th>' + VP.i18n.date + '</th>';
            html += '</tr></thead><tbody>';

            transactions.forEach(function(tx) {
                var amount = parseInt(tx.amount, 10) || 0;
                var pointsClass = amount >= 0 ? 'vp-points-positive' : 'vp-points-negative';
                var sign = amount >= 0 ? '+' : '';
                var dateObj = new Date(tx.created_at);
                var date = isNaN(dateObj.getTime()) ? '-' : dateObj.toLocaleDateString();
                var description = tx.description || tx.type_description || tx.type || 'Transaction';

                html += '<tr>';
                html += '<td>' + escapeHtml(description) + '</td>';
                html += '<td class="' + pointsClass + '">' + sign + amount + '</td>';
                html += '<td class="vp-points-date">' + date + '</td>';
                html += '</tr>';
            });

            html += '</tbody></table>';
            container.html(html);
        }).fail(function() {
            $('#points-history-container').html('<p class="vp-points-empty">' + VP.i18n.failedToLoad + '</p>');
        });
    }

    /**
     * Fetch live points balance from Hub and update header.
     * This prevents stale cached balances after actions on partner sites.
     */
    function refreshPointsBalance() {
        $.post(VP.ajaxUrl, {
            action: 'consolety_fetch_points_balance',
            nonce: VP.nonce
        }, function(response) {
            if (!response || !response.success) {
                return;
            }

            var balance = 0;
            if (response.data && (response.data.balance !== undefined || response.data.credits !== undefined)) {
                var rawBalance = response.data.balance !== undefined ? response.data.balance : response.data.credits;
                balance = parseInt(rawBalance, 10) || 0;
            }

            var $credits = $('.vp-credits-value');
            if ($credits.length) {
                $credits.text(balance);
            }
        });
    }

    function escapeHtml(text) {
        if (!text) return '';
        var div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    function loadRecentActivity() {
        $.ajax({
            url: VP.ajaxUrl,
            type: 'POST',
            data: {
                action: 'consolety_fetch_activity',
                nonce: VP.nonce
            },
            timeout: 8000,
            success: function(response) {
                var container = $('#activity-feed-container');
                var activities = [];

                if (!response || !response.success) {
                    container.html('<p class="vp-points-empty">' + VP.i18n.failedToLoadActivity + '</p>');
                    return;
                }

                if (Array.isArray(response.data)) {
                    activities = response.data;
                }

                if (activities.length === 0) {
                    container.html('<p class="vp-points-empty">' + VP.i18n.noActivity + '</p>');
                    return;
                }

                var html = '<div class="vp-activity-list">';

                activities.forEach(function(item) {
                    var icon = item.icon || 'dashicons-info-outline';
                    var message = item.message || '';
                    var timeAgo = item.time_ago || VP.i18n.justNow;

                    html += '<div class="vp-activity-item">';
                    html += '<span class="dashicons ' + escapeHtml(icon) + ' vp-activity-icon"></span>';
                    html += '<span class="vp-activity-message">' + escapeHtml(message) + '</span>';
                    html += '<span class="vp-activity-time">' + escapeHtml(timeAgo) + '</span>';
                    html += '</div>';
                });

                html += '</div>';
                container.html(html);
            },
            error: function() {
                $('#activity-feed-container').html('<p class="vp-points-empty">' + VP.i18n.failedToLoadActivity + '</p>');
            }
        });
    }

    // Load feeds when page is ready
    if ($('#activity-feed-container').length) {
        loadRecentActivity();
    }
    if ($('#points-history-container').length) {
        // Refresh live balance first so header is not stale.
        refreshPointsBalance();
        loadPointsHistory();
    }

    // ==========================================
    // Site Profile Form
    // ==========================================

    function setDetectedLanguage() {
        var locale = consoletyDashboard.locale || {};
        var code = locale.languageCode || 'en';
        var name = locale.nativeName || code.toUpperCase();

        $('#profile-language').val(code);
        $('#profile-language-display').text(name + ' (' + code.toUpperCase() + ')');
    }

    function populateSubcategories(mainCategoryId, selectedSubcategoryId) {
        var subSelect = $('#profile-subcategory');
        subSelect.find('option:not(:first)').remove();

        if (!mainCategoryId) {
            subSelect.val('').prop('disabled', true);
            $('#dashboard-subcategory-helper').text(VP.i18n.selectMainFirst || 'Select a main category first').show();
            return;
        }

        var parent = categoriesCache.find(function(cat) {
            return parseInt(cat.id, 10) === parseInt(mainCategoryId, 10);
        });
        var children = [];
        if (parent && Array.isArray(parent.children)) {
            children = parent.children;
        }

        if (!children.length) {
            subSelect.val('').prop('disabled', true);
            $('#dashboard-subcategory-helper').text(VP.i18n.noSubcategories || 'No subcategories available').show();
            return;
        }

        children.forEach(function(sub) {
            var label = sub.icon ? sub.icon + ' ' + sub.name : sub.name;
            if (sub.is_sensitive) label += ' (18+)';
            subSelect.append('<option value="' + sub.id + '">' + escapeHtml(label) + '</option>');
        });

        subSelect.prop('disabled', false);
        $('#dashboard-subcategory-helper').hide();
        if (selectedSubcategoryId) {
            subSelect.val(String(selectedSubcategoryId));
        }
    }

    // Load categories for dropdown
    function loadCategories() {
        $.post(VP.ajaxUrl, {
            action: 'consolety_get_categories',
            nonce: VP.nonce
        }, function(response) {
            var mainSelect = $('#profile-category');
            mainSelect.find('option:not(:first)').remove();

            if (response.success && response.data && response.data.categories) {
                categoriesCache = response.data.categories;
                response.data.categories.forEach(function(cat) {
                    // Only show top-level categories in main selector
                    if (cat.parent_id) return;
                    var label = cat.icon ? cat.icon + ' ' + cat.name : cat.name;
                    if (cat.is_sensitive) label += ' (18+)';
                    mainSelect.append('<option value="' + cat.id + '">' + escapeHtml(label) + '</option>');
                });
            }

            // Load current profile after categories are loaded
            loadCurrentProfile();
        });
    }

    // Load current site profile
    function loadCurrentProfile() {
        $.post(VP.ajaxUrl, {
            action: 'consolety_get_site_profile',
            nonce: VP.nonce
        }, function(response) {
            if (response.success && response.data) {
                // Language is auto-detected from WP locale, not from stored profile
                setDetectedLanguage();

                if (response.data.category_id) {
                    $('#profile-category').val(response.data.category_id);
                }
                populateSubcategories(response.data.category_id || '', response.data.subcategory_id || '');
                if (response.data.bio) {
                    $('#profile-bio').val(response.data.bio);
                    $('#bio-char-count').text(response.data.bio.length);
                }
            }
        });
    }

    $('#profile-category').on('change', function() {
        populateSubcategories($(this).val(), '');
    });

    // Character counter for bio
    $('#profile-bio').on('input', function() {
        var len = $(this).val().length;
        $('#bio-char-count').text(len);
    });

    // Save profile form
    $('#site-profile-form').on('submit', function(e) {
        e.preventDefault();

        var $btn = $('#save-profile-btn');
        var $status = $('#profile-save-status');

        $btn.prop('disabled', true).text(VP.i18n.saving);
        $status.removeClass('success error').text('');

        $.post(VP.ajaxUrl, {
            action: 'consolety_save_site_profile',
            nonce: VP.nonce,
            category_id: $('#profile-category').val(),
            subcategory_id: $('#profile-subcategory').val(),
            language: $('#profile-language').val(),
            bio: $('#profile-bio').val()
        }, function(response) {
            if (response.success) {
                $status.addClass('success').text(VP.i18n.saved);
                setTimeout(function() { $status.text(''); }, 3000);
            } else {
                var profileError = (response && response.data && response.data.message) ? response.data.message : VP.i18n.failedToSave;
                $status.addClass('error').text(profileError);
            }
        }).fail(function() {
            $status.addClass('error').text(VP.i18n.connectionError);
        }).always(function() {
            $btn.prop('disabled', false).text(VP.i18n.saveProfile);
        });
    });

    // Initialize
    if ($('#profile-category').length) {
        setDetectedLanguage();
        loadCategories();
    }

    // ==========================================
    // Guest Post Requirements Form
    // ==========================================

    // Load current requirements
    function loadRequirements() {
        $.post(VP.ajaxUrl, {
            action: 'consolety_get_requirements',
            nonce: VP.nonce
        }, function(response) {
            if (response.success && response.data) {
                var req = response.data;

                // Min words
                if (req.min_words) {
                    $('#req-min-words').val(req.min_words);
                }

                // AI policy
                if (req.ai_policy) {
                    $('input[name="ai_policy"][value="' + req.ai_policy + '"]').prop('checked', true);
                }

                // Max links
                if (req.max_dofollow_links) {
                    $('#req-max-links').val(req.max_dofollow_links);
                }

                // Forbidden niches
                if (req.forbidden_niches && req.forbidden_niches.length > 0) {
                    req.forbidden_niches.forEach(function(niche) {
                        $('input[name="forbidden_niches[]"][value="' + niche + '"]').prop('checked', true);
                    });
                }

                // Custom note
                if (req.custom_note) {
                    $('#req-custom-note').val(req.custom_note);
                    $('#note-char-count').text(req.custom_note.length);
                }
            }
        });
    }

    // Character counter for custom note
    $('#req-custom-note').on('input', function() {
        $('#note-char-count').text($(this).val().length);
    });

    // Save requirements form
    $('#guest-post-requirements-form').on('submit', function(e) {
        e.preventDefault();

        var $btn = $('#save-requirements-btn');
        var $status = $('#requirements-save-status');

        $btn.prop('disabled', true);
        $btn.find('.dashicons').removeClass('dashicons-saved').addClass('dashicons-update spin');
        $status.removeClass('success error').text('');

        // Collect forbidden niches
        var forbiddenNiches = [];
        $('input[name="forbidden_niches[]"]:checked').each(function() {
            forbiddenNiches.push($(this).val());
        });

        var requirements = {
            min_words: parseInt($('#req-min-words').val()),
            ai_policy: $('input[name="ai_policy"]:checked').val(),
            max_dofollow_links: parseInt($('#req-max-links').val()),
            forbidden_niches: forbiddenNiches,
            custom_note: $('#req-custom-note').val().trim()
        };

        $.post(VP.ajaxUrl, {
            action: 'consolety_save_requirements',
            nonce: VP.nonce,
            requirements: JSON.stringify(requirements)
        }, function(response) {
            if (response.success) {
                $status.addClass('success').text(VP.i18n.saved);
                setTimeout(function() { $status.text(''); }, 3000);
            } else {
                var reqError = (response && response.data && response.data.message) ? response.data.message : VP.i18n.failedToSave;
                $status.addClass('error').text(reqError);
            }
        }).fail(function() {
            $status.addClass('error').text(VP.i18n.connectionError);
        }).always(function() {
            $btn.prop('disabled', false);
            $btn.find('.dashicons').removeClass('dashicons-update spin').addClass('dashicons-saved');
        });
    });

    // Load requirements on page load
    if ($('#guest-post-requirements-form').length) {
        loadRequirements();
    }

})(jQuery);
