(function($) {
    'use strict';

    var STORAGE_KEY = 'sitestaffr_agent_tab';

    function initTabs() {
        var $tablist = $('.sitestaffr-agent-tabs');
        var $tabs = $tablist.find('.sitestaffr-agent-tab');

        var saved = localStorage.getItem(STORAGE_KEY);
        if (saved) {
            var $savedTab = $tabs.filter('[aria-controls="' + saved + '"]');
            if ($savedTab.length) {
                activateTab($savedTab, $tabs);
            }
        }

        $tabs.on('click', function() {
            var $tab = $(this);
            activateTab($tab, $tabs);
            localStorage.setItem(STORAGE_KEY, $tab.attr('aria-controls'));
        });

        $tabs.on('keydown', function(e) {
            var index = $tabs.index(this);
            var newIndex = -1;
            if (e.key === 'ArrowRight' || e.key === 'ArrowDown') {
                newIndex = (index + 1) % $tabs.length;
            } else if (e.key === 'ArrowLeft' || e.key === 'ArrowUp') {
                newIndex = (index - 1 + $tabs.length) % $tabs.length;
            }
            if (newIndex >= 0) {
                e.preventDefault();
                $tabs.eq(newIndex).trigger('click').focus();
            }
        });
    }

    function activateTab($tab, $allTabs) {
        $allTabs.each(function() {
            $(this).removeClass('is-active').attr({'aria-selected': 'false', 'tabindex': '-1'});
            $('#' + $(this).attr('aria-controls')).attr('hidden', true);
        });
        $tab.addClass('is-active').attr({'aria-selected': 'true', 'tabindex': '0'});
        $('#' + $tab.attr('aria-controls')).removeAttr('hidden');
    }

    function initToggles() {
        $('.sitestaffr-ai-instruction-toggle').on('change', function() {
            var $input = $(this);
            var settingKey = $input.data('setting-key');
            var value = $input.is(':checked') ? '1' : '0';
            var $status = $input.closest('.sitestaffr-toggle-row').find('.sitestaffr-toggle-status');

            $status.text(sitestaffrAgentData.i18n.saving).css('color', '#666');

            $.post(ajaxurl, {
                action: 'sitestaffr_save_agent_instruction',
                nonce: sitestaffrAgentData.nonces.agent,
                setting_key: settingKey,
                value: value
            }, function(response) {
                if (response.success) {
                    $status.text(sitestaffrAgentData.i18n.saved).css('color', '#10b981');
                    setTimeout(function() { $status.text(''); }, 2000);
                } else {
                    $status.text(sitestaffrAgentData.i18n.saveFailed).css('color', '#991b1b');
                    $input.prop('checked', !$input.is(':checked'));
                }
            }).fail(function() {
                $status.text(sitestaffrAgentData.i18n.saveFailed).css('color', '#991b1b');
                $input.prop('checked', !$input.is(':checked'));
            });
        });
    }

    function initVoiceSave() {
        $('#sitestaffr-save-agent-voice').on('click', function() {
            var $btn = $(this);
            var $status = $('#sitestaffr-agent-voice-save-status');
            $btn.prop('disabled', true);
            $status.text(sitestaffrAgentData.i18n.saving).css('color', '#666');

            $.post(ajaxurl, {
                action: 'sitestaffr_save_agent_voice',
                nonce: sitestaffrAgentData.nonces.agent,
                ai_voice: $('#sitestaffr-voice-select').val(),
                custom_greeting: $('#custom_greeting').val() || '',
                custom_greeting_tone: $('#custom_greeting_tone').val() || 'warm_neutral'
            }, function(response) {
                $btn.prop('disabled', false);
                if (response.success) {
                    $status.text(sitestaffrAgentData.i18n.saved).css('color', '#10b981');
                    setTimeout(function() { $status.text(''); }, 2000);
                } else {
                    $status.text(response.data?.message || sitestaffrAgentData.i18n.saveFailed).css('color', '#991b1b');
                }
            }).fail(function() {
                $btn.prop('disabled', false);
                $status.text(sitestaffrAgentData.i18n.saveFailed).css('color', '#991b1b');
            });
        });
    }

    function initGreetingCounter() {
        var $input = $('#custom_greeting');
        if (!$input.length) return;
        $input.on('input', function() {
            var len = this.value.length;
            $input.siblings('.sitestaffr-char-count').find('.sitestaffr-char-current').text(len);
        });
    }

    function initCustomInstructions() {
        var $list = $('#sitestaffr-ci-list');
        var $form = $('#sitestaffr-ci-form');
        var $textarea = $('#sitestaffr-ci-text');
        var $editId = $('#sitestaffr-ci-edit-id');
        var $saveBtn = $('#sitestaffr-ci-save');
        var $addBtn = $('#sitestaffr-add-ci');
        var $charCount = $form.find('.sitestaffr-ci-char-current');
        var $charWrap = $form.find('.sitestaffr-ci-char-count');
        var limit = (sitestaffrAgentData.customInstructions || {}).limit || 0;

        function getCount() {
            return $list.find('.sitestaffr-ci-card').length;
        }

        function updateBadge() {
            $('.sitestaffr-ci-count-badge').text(getCount() + ' / ' + limit);
            $addBtn.prop('disabled', getCount() >= limit);
        }

        function resetForm() {
            $form.hide();
            $textarea.val('');
            $editId.val('');
            $charCount.text('0');
            $charWrap.removeClass('is-over');
            $saveBtn.prop('disabled', true);
        }

        function buildCard(data) {
            var checked = data.enabled ? ' checked' : '';
            var disabledClass = data.enabled ? '' : ' is-disabled';
            return '<div class="sitestaffr-ci-card' + disabledClass + '" data-ci-id="' + data.id + '">' +
                '<label class="sitestaffr-toggle-switch">' +
                '<input type="checkbox" class="sitestaffr-ci-toggle"' + checked + ' />' +
                '<span class="sitestaffr-toggle-slider"></span></label>' +
                '<span class="sitestaffr-ci-text">' + $('<span>').text(data.text).html() + '</span>' +
                '<span class="sitestaffr-ci-char-badge">' + data.text.length + ' / 200</span>' +
                '<span class="sitestaffr-ci-status"></span>' +
                '<div class="sitestaffr-ci-actions">' +
                '<button type="button" class="sitestaffr-ci-edit" title="Edit"><span class="dashicons dashicons-edit-page"></span></button>' +
                '<button type="button" class="sitestaffr-ci-delete" title="Delete"><span class="dashicons dashicons-trash"></span></button>' +
                '</div></div>';
        }

        $textarea.on('input', function() {
            var len = this.value.length;
            $charCount.text(len);
            $charWrap.toggleClass('is-over', len > 200);
            $saveBtn.prop('disabled', len === 0 || len > 200);
        });

        $addBtn.on('click', function() {
            if (getCount() >= limit) return;
            resetForm();
            $form.show();
            $textarea.focus();
        });

        $('#sitestaffr-ci-cancel').on('click', function() {
            resetForm();
        });

        $saveBtn.on('click', function() {
            var text = $textarea.val().trim();
            if (!text || text.length > 200) return;
            var id = $editId.val();
            $saveBtn.prop('disabled', true);

            $.post(ajaxurl, {
                action: 'sitestaffr_save_custom_instruction',
                nonce: sitestaffrAgentData.nonces.agent,
                id: id,
                text: text
            }, function(response) {
                if (response.success) {
                    if (id) {
                        var $card = $list.find('[data-ci-id="' + id + '"]');
                        $card.find('.sitestaffr-ci-text').text(response.data.text);
                        $card.find('.sitestaffr-ci-char-badge').text(response.data.text.length + ' / 200');
                    } else {
                        $list.append(buildCard(response.data));
                    }
                    resetForm();
                    updateBadge();
                } else {
                    alert(response.data?.message || sitestaffrAgentData.i18n.saveFailed);
                    $saveBtn.prop('disabled', false);
                }
            }).fail(function() {
                alert(sitestaffrAgentData.i18n.saveFailed);
                $saveBtn.prop('disabled', false);
            });
        });

        $list.on('change', '.sitestaffr-ci-toggle', function() {
            var $input = $(this);
            var $card = $input.closest('.sitestaffr-ci-card');
            var id = $card.data('ci-id');
            var value = $input.is(':checked') ? '1' : '0';
            var $status = $card.find('.sitestaffr-ci-status');

            $card.toggleClass('is-disabled', value === '0');
            $status.text(sitestaffrAgentData.i18n.saving).css('color', '#666');

            $.post(ajaxurl, {
                action: 'sitestaffr_toggle_custom_instruction',
                nonce: sitestaffrAgentData.nonces.agent,
                id: id,
                value: value
            }, function(response) {
                if (response.success) {
                    $status.text(sitestaffrAgentData.i18n.saved).css('color', '#10b981');
                    setTimeout(function() { $status.text(''); }, 2000);
                } else {
                    $status.text(sitestaffrAgentData.i18n.saveFailed).css('color', '#991b1b');
                    $input.prop('checked', !$input.is(':checked'));
                    $card.toggleClass('is-disabled', !$input.is(':checked'));
                }
            }).fail(function() {
                $status.text(sitestaffrAgentData.i18n.saveFailed).css('color', '#991b1b');
                $input.prop('checked', !$input.is(':checked'));
                $card.toggleClass('is-disabled', !$input.is(':checked'));
            });
        });

        $list.on('click', '.sitestaffr-ci-edit', function() {
            var $card = $(this).closest('.sitestaffr-ci-card');
            var id = $card.data('ci-id');
            var text = $card.find('.sitestaffr-ci-text').text();
            resetForm();
            $editId.val(id);
            $textarea.val(text);
            $charCount.text(text.length);
            $saveBtn.prop('disabled', false);
            $form.show();
            $textarea.focus();
        });

        $list.on('click', '.sitestaffr-ci-delete', function() {
            if (!confirm(sitestaffrAgentData.i18n.confirmDelete)) return;
            var $card = $(this).closest('.sitestaffr-ci-card');
            var id = $card.data('ci-id');

            $.post(ajaxurl, {
                action: 'sitestaffr_delete_custom_instruction',
                nonce: sitestaffrAgentData.nonces.agent,
                id: id
            }, function(response) {
                if (response.success) {
                    $card.remove();
                    updateBadge();
                    if ($editId.val() === id) resetForm();
                } else {
                    alert(response.data?.message || sitestaffrAgentData.i18n.saveFailed);
                }
            }).fail(function() {
                alert(sitestaffrAgentData.i18n.saveFailed);
            });
        });
    }

    $(document).ready(function() {
        initTabs();
        initToggles();
        initVoiceSave();
        initGreetingCounter();
        initCustomInstructions();
    });
})(jQuery);
