/**
 * Contentosapp Studio Admin — Sites settings/modal interactions.
 */
/* global CostudioData */
(function ($) {
    'use strict';

    var data = window.CostudioData || {};
    var ajax = data.ajax_url || '';
    var nonce = data.nonce || '';
    var i18n = data.i18n || {};
    function t(key, fallback) {
        return (typeof i18n[key] === 'string' && i18n[key].length) ? i18n[key] : fallback;
    }

    if (!$('#fos-sites-list, #fos-site-form, #fos-add-site-btn').length) {
        return;
    }

    function esc(str) {
        return $('<div>').text(str).html();
    }

    function fosReloadKeepTab() {
        var activeTab = $('.fos-tab-btn.is-active').data('tab') || '';
        if (activeTab) {
            sessionStorage.setItem('costudio_active_tab', activeTab);
        }
        window.location.reload();
    }

    // ── Sites: open add modal ─────────────────────────────────────────────────

    $(document).on('click', '#fos-add-site-btn, .fos-add-site-btn', function () {
        openSiteModal(null);
    });

    // ── Sites: open edit modal ────────────────────────────────────────────────

    $(document).on('click', '.fos-edit-site-btn', function () {
        var key = $(this).data('key');
        var sites = data.site_data || {};
        var site = sites[key] || null;
        openSiteModal(site, key);
    });

    // ── Sites: close modal ────────────────────────────────────────────────────

    $(document).on('click', '#fos-modal-close, #fos-modal-cancel, .fos-modal', function (e) {
        if (e.target === this) {
            closeSiteModal();
        }
    });

    $(document).on('keydown', function (e) {
        if (e.key === 'Escape') closeSiteModal();
    });

    // ── Category tag helpers ───────────────────────────────────────────────────

    function fosCatPromptHtml() {
        return '<span class="fos-cat-area__empty">' + t('categories_prompt', 'Click "Load from site" to fetch available categories.') + '</span>';
    }

    function renderFosCatTags( categories, preSelected ) {
        var $wrap    = $( '#fos-modal-cat-tags-wrap' );
        var selected = Array.isArray( preSelected ) ? preSelected : [];
        $wrap.empty();

        if ( ! categories || ! categories.length ) {
            $wrap.html( '<span class="fos-cat-area__empty">' + t('categories_empty', 'No categories found.') + '</span>' );
            return;
        }

        categories.forEach( function ( cat ) {
            var isSelected = selected.indexOf( cat ) !== -1;
            $( '<button type="button"></button>' )
                .addClass( 'fos-cat-tag' + ( isSelected ? ' fos-cat-tag--selected' : '' ) )
                .text( cat )
                .on( 'click', function () { $( this ).toggleClass( 'fos-cat-tag--selected' ); } )
                .appendTo( $wrap );
        } );
    }

    function fosCatGetSelected() {
        var names = [];
        $( '#fos-modal-cat-tags-wrap .fos-cat-tag--selected' ).each( function () {
            names.push( $( this ).text().trim() );
        } );
        return names.join( ', ' );
    }

    // ── Site modal: open / close ───────────────────────────────────────────────

    function openSiteModal(site, key) {
        var editing = !!site;

        $('#fos-modal-title').text(editing ? t('edit_site', 'Edit Site') : t('add_site', 'Add New Site'));
        $('#fos-site-old-key').val(key || '');
        $('#fos-site-name').val(site ? (site.name || site.label || '') : '');
        $('#fos-site-url').val(site ? site.url : '');
        $('#fos-site-user').val(site ? site.user : '');
        $('#fos-site-color').val(site ? (site.color || '#3b82f6') : '#3b82f6');
        $('#fos-site-password').val('').attr('placeholder', editing ? t('site_password_keep_current', '(leave blank to keep current)') : 'xxxx xxxx xxxx xxxx');

        var isLocal = key === '__local__';
        var $checkbox = $('#fos-site-is-local');
        
        if ($checkbox.length) {
            $checkbox.prop('checked', isLocal);
            // Hide the toggle if we are editing an existing site, to prevent changing a remote to local or vice-versa
            if (editing) {
                $('#fos-site-local-toggle-wrap').hide();
            } else {
                $('#fos-site-local-toggle-wrap').show();
            }
        }

        toggleLocalFields(isLocal, editing);

        // Reset connection result.
        $('#fos-modal-conn-result').hide().removeClass('is-testing is-success is-error').text('');

        // Reset / pre-populate categories.
        var savedCats = ( site && Array.isArray( site.categories ) ) ? site.categories : [];
        if ( savedCats.length ) {
            renderFosCatTags( savedCats, savedCats );
        } else {
            $( '#fos-modal-cat-tags-wrap' ).html( fosCatPromptHtml() );
        }
        $( '#fos-modal-load-cats-btn' ).prop( 'disabled', false )
            .text( '🔄 ' + t('load_from_site', 'Load from site') );

        $('#fos-site-modal').fadeIn(180);
        $('#fos-site-name').trigger('focus');
    }

    function toggleLocalFields(isLocal, editing) {
        var disableFields = isLocal;
        $('#fos-site-url, #fos-site-user, #fos-site-password').prop('disabled', disableFields);
        
        if (isLocal) {
            $('#fos-site-password').attr('placeholder', t('no_credentials', 'No credentials needed'));
            $('#fos-site-url').attr('placeholder', t('auto_detected', 'Auto-detected'));
            $('#fos-site-user').attr('placeholder', t('auto_detected', 'Auto-detected'));
            // Automatically set key to __local__ if checked during creation
            if (!editing) {
                $('#fos-site-old-key').val('__local__');
            }
        } else {
            $('#fos-site-password').attr('placeholder', editing ? t('site_password_keep_current', '(leave blank to keep current)') : 'xxxx xxxx xxxx xxxx');
            $('#fos-site-url').attr('placeholder', 'https://mysite.com');
            $('#fos-site-user').attr('placeholder', 'admin');
            // Reset key if unchecked during creation
            if (!editing && $('#fos-site-old-key').val() === '__local__') {
                $('#fos-site-old-key').val('');
            }
        }
    }

    $(document).on('change', '#fos-site-is-local', function() {
        var isLocal = $(this).is(':checked');
        toggleLocalFields(isLocal, false);
    });

    function closeSiteModal() {
        $('#fos-site-modal').fadeOut(150);
    }

    // ── Sites: save (create / update) ─────────────────────────────────────────

    $(document).on('submit', '#fos-site-form', function (e) {
        e.preventDefault();

        var $btn = $('#fos-site-save-btn');
        var orig = $btn.text();
        $btn.text('…').prop('disabled', true);

        // Include the old_key, but if it is empty and local is checked, it means they are creating local.
        var submittedKey = $('#fos-site-old-key').val() || '';
        if ($('#fos-site-is-local').is(':checked') && !submittedKey) {
            submittedKey = '__local__';
        }

        $.post(ajax, {
            action: 'costudio_save_site',
            nonce: nonce,
            name: $('#fos-site-name').val(),
            url: $('#fos-site-url').val(),
            user: $('#fos-site-user').val(),
            password: $('#fos-site-password').val(),
            color: $('#fos-site-color').val(),
            old_key: submittedKey,
            categories: fosCatGetSelected(),
        })
            .done(function (res) {
                if (res.success) {
                    closeSiteModal();
                    fosReloadKeepTab();
                } else {
                    $btn.text(orig).prop('disabled', false);
                    alert(res.data || t('error', 'Error'));
                }
            })
            .fail(function () {
                $btn.text(orig).prop('disabled', false);
            });
    });

    // ── Sites: delete ─────────────────────────────────────────────────────────

    $(document).on('click', '.fos-delete-site-btn', function () {
        if (!window.confirm(t('confirm_delete_site', 'Delete this site?'))) return;

        var key = $(this).data('key');
        var $row = $(this).closest('.fos-site-card');

        $.post(ajax, { action: 'costudio_delete_site', nonce: nonce, site_key: key })
            .done(function (res) {
                if (res.success) {
                    $row.fadeOut(250, function () { 
                        $(this).remove(); 
                        if ($('.fos-site-card').length === 0) {
                            fosReloadKeepTab();
                        }
                    });
                }
            });
    });

    // ── Sites: reset all ──────────────────────────────────────────────────────

    $(document).on('click', '#fos-reset-sites-btn', function () {
        if (!window.confirm(t('confirm_reset_sites', 'Delete ALL sites?'))) return;

        $.post(ajax, { action: 'costudio_reset_sites', nonce: nonce })
            .done(function (res) {
                if (res.success) {
                    $('#fos-sites-list').html(
                        '<p class="fos-sites-empty">' + esc(t('no_sites_configured', 'No sites configured.')) + '</p>'
                    );
                }
            });
    });

    // ── Sites: test connection (from card row) ────────────────────────────────

    $(document).on('click', '.fos-test-site-row-btn', function () {
        var key = $(this).data('key');
        var $status = $(this).closest('.fos-site-card').find('.fos-site-card__status');

        $status.text(t('testing', 'Testing…')).removeClass('is-ok is-error');

        $.post(ajax, { action: 'costudio_test_connection', nonce: nonce, site_key: key })
            .done(function (res) {
                $status
                    .text(res.success ? (res.data.message || t('connected', 'Connected')) : (res.data || t('error', 'Error')))
                    .addClass(res.success ? 'is-ok' : 'is-error');
            });
    });

    // ── Sites: load categories (from modal) ───────────────────────────────────

    $(document).on('click', '#fos-modal-load-cats-btn', function () {
        var $btn     = $(this);
        var $wrap    = $('#fos-modal-cat-tags-wrap');
        var url      = ($('#fos-site-url').val()      || '').trim();
        var user     = ($('#fos-site-user').val()     || '').trim();
        var password = $('#fos-site-password').val()  || '';
        var oldKey   = $('#fos-site-old-key').val()   || '';
        var isLocal  = $('#fos-site-is-local').is(':checked') || oldKey === '__local__';

        if (!url && !isLocal) {
            alert(t('site_url_required', 'Please enter the site URL first.'));
            return;
        }

        var reqKey = oldKey;
        if (isLocal && !reqKey) {
            reqKey = '__local__';
        }

        $btn.prop('disabled', true).text(t('loading', 'Loading…'));
        $wrap.html(
            '<span class="fos-cat-area__loading">' +
            '<span class="fos-conn-spinner"></span>' +
            t('categories_loading', 'Loading categories…') +
            '</span>'
        );

        $.post(ajax, {
            action:   'costudio_fetch_site_categories',
            nonce:    nonce,
            site_key: reqKey,
            url:      url,
            user:     user,
            password: password,
        })
        .done(function (res) {
            if (res && res.success && res.data && Array.isArray(res.data.categories)) {
                renderFosCatTags(res.data.categories, []);
            } else {
                var msg = (res && res.data && res.data.message) || t('categories_fetch_error', 'Could not load categories.');
                $wrap.html('<span class="fos-cat-area__empty">' + $('<span>').text(msg).html() + '</span>');
            }
        })
        .fail(function () {
            $wrap.html('<span class="fos-cat-area__empty">' + t('categories_fetch_error', 'Could not load categories.') + '</span>');
        })
        .always(function () {
            $btn.prop('disabled', false).text('🔄 ' + t('load_from_site', 'Load from site'));
        });
    });

    // ── Sites: test connection (from modal) ───────────────────────────────────

    $(document).on('click', '#fos-modal-test-btn', function () {
        var $btn    = $(this);
        var $result = $('#fos-modal-conn-result');
        var testingMsg = t('testing', 'Testing…');

        var oldKey  = $('#fos-site-old-key').val() || '';
        var isLocal = $('#fos-site-is-local').is(':checked') || oldKey === '__local__';
        var reqKey  = oldKey;
        if (isLocal && !reqKey) {
            reqKey = '__local__';
        }

        $btn.prop('disabled', true);
        $result.removeClass('is-success is-error')
               .addClass('is-testing')
               .html('<span class="fos-conn-spinner"></span> ' + testingMsg)
               .show();

        $.post(ajax, {
            action:   'costudio_test_connection',
            nonce:    nonce,
            site_key: reqKey,
            url:      $('#fos-site-url').val(),
            user:     $('#fos-site-user').val(),
            password: $('#fos-site-password').val(),
        })
            .done(function (res) {
                var ok  = !!res.success;
                var msg = ok ? (res.data.message || t('connection_success', 'Connection successful!')) : (res.data || t('error', 'Error'));

                $result.removeClass('is-testing is-success is-error')
                       .addClass(ok ? 'is-success' : 'is-error')
                       .text((ok ? '✓ ' : '✗ ') + msg);

                // Update the site card status dot in the list immediately.
                var siteKey = $('#fos-site-old-key').val() || '';
                if ( siteKey ) {
                    var $card = $('.fos-site-card[data-key="' + siteKey + '"] .fos-int-status');
                    $card.removeClass('fos-int-status--ok fos-int-status--warn fos-int-status--error')
                         .addClass(ok ? 'fos-int-status--ok' : 'fos-int-status--error');
                    $card.find('.fos-int-status__text')
                         .text(ok ? t('connected', 'Connected') : t('connection_error', 'Connection error'));
                }

                // Auto-hide after delay.
                clearTimeout($result.data('hideTimer'));
                $result.data('hideTimer', setTimeout(function () {
                    $result.fadeOut(200, function () {
                        $result.removeClass('is-success is-error').text('');
                    });
                }, ok ? 3200 : 4200));
            })
            .fail(function () {
                var errMsg = t('error', 'Error');
                $result.removeClass('is-testing is-success').addClass('is-error').text('✗ ' + errMsg);
                clearTimeout($result.data('hideTimer'));
                $result.data('hideTimer', setTimeout(function () {
                    $result.fadeOut(200, function () {
                        $result.removeClass('is-error').text('');
                    });
                }, 4200));
            })
            .always(function () {
                $btn.prop('disabled', false);
            });
    });


}(jQuery));
