/**
 * Consolety Partner Selection JavaScript
 *
 * Supports both Context Mode (pre-selected) and Selection Mode (dropdown)
 *
 * @package Consolety
 * @since 1.0.0
 */

/* global jQuery, consoletyPartnerSelection */

(function($) {
    'use strict';

    // Use dedicated localized data with fallbacks
    const VPS = typeof consoletyPartnerSelection !== 'undefined' ? consoletyPartnerSelection : { i18n: {} };

    window.ConsoletyPartnerCards = {
        selectedPartnerId: null,
        partnersData: [],
        partnerRequirements: {},
        isContextMode: false,

        init: function(partners, targetContainer) {
            this.partnersData = partners || [];

            // Store requirements by partner ID (always as string for consistent lookup)
            this.partnerRequirements = {};
            partners.forEach((p) => {
                const siteId = String(p.site_id || p.id);
                this.partnerRequirements[siteId] = p.requirements || null;
            });

            if (!partners || partners.length === 0) {
                $('#partner-selection-wrap').hide();
                $('#partner-context-wrap').hide();
                $('#partner-empty').show();
                $('#partner-requirements-display').hide();
                return;
            }

            $('#partner-empty').hide();

            // Check for URL parameters first (from Network page)
            this.initPartnerSelection();
        },

        initPartnerSelection: function() {
            const urlParams = new URLSearchParams(window.location.search);
            const partnerId = urlParams.get('partner_id');
            const partnerDomain = urlParams.get('partner_domain');
            const partnerClicks = urlParams.get('partner_clicks') || 0;

            if (partnerId && partnerDomain) {
                // Context Mode - partner pre-selected from Network
                this.showContextMode(partnerId, partnerDomain, partnerClicks);
            } else {
                // Selection Mode - show dropdown
                this.showSelectionMode();
            }

            this.bindEvents();
        },

        showContextMode: function(partnerId, partnerDomain, partnerClicks) {
            this.isContextMode = true;
            this.selectedPartnerId = partnerId;

            // Set hidden input
            $('#gp-partner').val(partnerId);

            // Update context display
            $('#context-partner-domain').text(partnerDomain);
            $('#context-partner-stats').text(this.formatNumber(partnerClicks) + ' clicks/maand');

            // KRITIEK: Verberg "Select Partner Site" label in context mode
            $('#partner-label-wrap').hide();

            // Show context, hide dropdown
            $('#partner-context-wrap').show();
            $('#partner-selection-wrap').hide();

            // Also render dropdown in background (for when user clicks "Change")
            this.renderDropdown();

            // Display requirements for pre-selected partner
            this.displayRequirements(partnerId);
        },

        showSelectionMode: function() {
            this.isContextMode = false;
            this.selectedPartnerId = null;

            // Clear hidden input
            $('#gp-partner').val('');

            // KRITIEK: Toon "Select Partner Site" label weer in selection mode
            $('#partner-label-wrap').show();

            // Show dropdown, hide context and requirements
            $('#partner-context-wrap').hide();
            $('#partner-selection-wrap').show();
            $('#partner-requirements-display').hide();

            this.renderDropdown();
        },

        renderDropdown: function() {
            const $dropdown = $('#partner-dropdown');

            // Clear existing options except placeholder
            $dropdown.find('option:not(:first)').remove();

            // Sort by traffic (most traffic first)
            const sorted = [...this.partnersData].sort((a, b) => {
                return (b.monthly_clicks || 0) - (a.monthly_clicks || 0);
            });

            // Add options
            sorted.forEach((partner) => {
                const clicks = partner.monthly_clicks || 0;
                const trafficLabel = clicks >= 10000 ? '10K+' : (clicks >= 1000 ? '1K+' : 'Nieuw');
                const langWarning = partner.language_match === false ? ' [Different language]' : '';
                const label = `${partner.domain} (${trafficLabel} traffic)${langWarning}`;
                const siteId = partner.site_id || partner.id;

                $dropdown.append(`<option value="${siteId}">${this.escapeHtml(label)}</option>`);
            });

            // If in context mode, pre-select the partner in dropdown too
            if (this.selectedPartnerId) {
                $dropdown.val(this.selectedPartnerId);
            }
        },

        bindEvents: function() {
            const self = this;

            // Dropdown change
            $('#partner-dropdown').off('change.partnerDropdown').on('change.partnerDropdown', function() {
                const siteId = $(this).val();
                self.selectedPartnerId = siteId || null;
                $('#gp-partner').val(siteId).trigger('change');

                // Update requirements display
                if (siteId) {
                    self.displayRequirements(siteId);
                } else {
                    $('#partner-requirements-display').hide();
                }
            });

            // "Change" button in context mode
            $('#btn-change-partner').off('click.changePartner').on('click.changePartner', function() {
                self.showSelectionMode();
            });
        },

        displayRequirements: function(partnerId) {
            // Always lookup with string key for consistency
            const req = this.partnerRequirements[String(partnerId)];

            if (!req) {
                // No requirements found - log warning and show defaults
                console.warn('[Consolety] No requirements found for partner:', partnerId);
                $('#req-min-words-display').text('500');
                $('#req-ai-policy-display').text(VPS.i18n?.aiAllowed || 'AI content allowed');
                $('#req-max-links-display').text('3');
                $('#req-forbidden-item').hide();
                $('#req-note-item').hide();
                $('#partner-requirements-display').show();
                return;
            }

            // Min words
            $('#req-min-words-display').text(req.min_words || 500);

            // AI policy
            const aiText = {
                'ai_allowed': VPS.i18n?.aiContentAllowed || 'AI content is allowed',
                'human_only': VPS.i18n?.humanOnly || 'Human written content only - no AI',
                'ai_with_edits': VPS.i18n?.aiWithEdits || 'AI content allowed if human edited'
            };
            $('#req-ai-policy-display').text(aiText[req.ai_policy] || aiText.ai_allowed);

            // Max links
            $('#req-max-links-display').text(req.max_dofollow_links || 3);

            // Forbidden niches
            if (req.forbidden_niches && req.forbidden_niches.length > 0) {
                const nicheLabels = {
                    'casino': VPS.i18n?.casinoGambling || 'Casino/Gambling',
                    'adult': VPS.i18n?.adult18 || 'Adult/18+',
                    'cbd': VPS.i18n?.cbdDrugs || 'CBD/Drugs',
                    'crypto': VPS.i18n?.cryptocurrency || 'Cryptocurrency',
                    'payday': VPS.i18n?.paydayLoans || 'Payday Loans'
                };
                const labels = req.forbidden_niches.map(n => nicheLabels[n] || n);
                $('#req-forbidden-list').text(labels.join(', '));
                $('#req-forbidden-item').show();
            } else {
                $('#req-forbidden-item').hide();
            }

            // Custom note
            if (req.custom_note) {
                $('#req-custom-note-display').text(req.custom_note);
                $('#req-note-item').show();
            } else {
                $('#req-note-item').hide();
            }

            $('#partner-requirements-display').show();
        },

        getSelectedPartner: function() {
            return this.selectedPartnerId;
        },

        formatNumber: function(num) {
            if (!num || num === 0) return '0';
            num = parseInt(num, 10);
            if (num >= 1000000) return (num / 1000000).toFixed(1) + 'M';
            if (num >= 1000) return (num / 1000).toFixed(1) + 'K';
            return num.toString();
        },

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