(function($) {
    'use strict';

    // Bumped from 'sitestaffr_agent_type' so the new Knowledge-first default
    // wins over any tab a returning user had remembered under the old layout.
    var AGENT_STORAGE_KEY = 'sitestaffr_agent_section';

    // Component-styled replacement for the native alert().
    function notify(message) {
        if (window.SiteStaffrModal) {
            window.SiteStaffrModal.alertDialog({ message: message });
        }
    }

    function initAgentSelector() {
        var $selector = $('.sitestaffr-agent-selector');
        if (!$selector.length) return;

        var $cards = $selector.find('.sitestaffr-agent-type-card:not(.is-disabled)');
        var $panels = $('.sitestaffr-agent-panel');

        // Deep link (?agent=blog&tab=settings or #sitestaffr-knowledge) wins
        // over the remembered agent.
        var params = new URLSearchParams(window.location.search);
        var urlAgent = params.get('agent');
        if (!urlAgent && window.location.hash === '#sitestaffr-knowledge') {
            urlAgent = 'knowledge';
        }
        var initial = null;
        if (urlAgent && $cards.filter('[data-agent="' + urlAgent + '"]').length) {
            initial = urlAgent;
        } else {
            initial = localStorage.getItem(AGENT_STORAGE_KEY);
        }
        if (initial) {
            var $initialCard = $cards.filter('[data-agent="' + initial + '"]');
            if ($initialCard.length) {
                activateAgent($initialCard, $cards, $panels);
            }
        }

        // Deep-linked tab inside the active panel: match the panel id exactly
        // or by suffix (tab=settings matches aria-controls="blog-tab-settings").
        var urlTab = params.get('tab');
        if (urlTab && window.SiteStaffrTabs) {
            var $activePanel = $panels.filter(':visible');
            var $tab = $activePanel.find('.sitestaffr-agent-tab').filter(function() {
                var controls = this.getAttribute('aria-controls') || '';
                return controls === urlTab || controls.endsWith('-' + urlTab);
            }).first();
            if ($tab.length) {
                $tab.trigger('click');
            }
        }

        $cards.on('click', function() {
            var $card = $(this);
            if ($card.hasClass('is-disabled')) return;
            activateAgent($card, $cards, $panels);
            localStorage.setItem(AGENT_STORAGE_KEY, $card.data('agent'));

            // Keep the URL addressable/shareable without adding history entries.
            var url = new URL(window.location.href);
            url.searchParams.set('agent', $card.data('agent'));
            url.searchParams.delete('tab');
            window.history.replaceState(null, '', url.toString());
        });
    }

    function activateAgent($card, $allCards, $panels) {
        var agent = $card.data('agent');
        $allCards.removeClass('is-active').attr('aria-checked', 'false');
        $card.addClass('is-active').attr('aria-checked', 'true');
        $panels.each(function() {
            var $panel = $(this);
            if ($panel.data('agent') === agent) {
                $panel.show();
            } else {
                $panel.hide();
            }
        });
    }

    // Tab behavior lives in the shared SiteStaffrTabs component
    // (admin/js/sitestaffr-tabs.js) — the tablist carries data-tab-storage.

    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';
            // Instant-save: status feedback only, no dirty tracking.
            var status = SiteStaffrSaveUX.status($input.closest('.sitestaffr-toggle-row').find('.sitestaffr-toggle-status'));

            status.saving();

            $.post(ajaxurl, {
                action: 'sitestaffr_save_agent_instruction',
                nonce: sitestaffrAgentData.nonces.agent,
                setting_key: settingKey,
                value: value
            }, function(response) {
                if (response.success) {
                    status.saved();
                } else {
                    status.error();
                    $input.prop('checked', !$input.is(':checked'));
                }
            }).fail(function() {
                status.error();
                $input.prop('checked', !$input.is(':checked'));
            });
        });
    }

    function initVoiceSave() {
        // Greeting + tone only persist via the Save button, so they carry the
        // unsaved-changes guard. The voice select instant-saves on change
        // (sitestaffr-settings-voice.js), so it is deliberately not tracked.
        var greetingDirty = SiteStaffrSaveUX.trackDirty('.sitestaffr-agent-greeting-field');

        $('#sitestaffr-save-agent-voice').on('click', function() {
            var $btn = $(this);
            var status = SiteStaffrSaveUX.status('#sitestaffr-agent-voice-save-status');
            $btn.prop('disabled', true);
            status.saving();

            $.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.saved();
                    greetingDirty.markClean();
                } else {
                    status.error(response.data?.message);
                }
            }).fail(function() {
                $btn.prop('disabled', false);
                status.error();
            });
        });
    }

    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 {
                    notify(response.data?.message || sitestaffrAgentData.i18n.saveFailed);
                    $saveBtn.prop('disabled', false);
                }
            }).fail(function() {
                notify(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';
            // Instant-save: status feedback only, no dirty tracking.
            var status = SiteStaffrSaveUX.status($card.find('.sitestaffr-ci-status'));

            $card.toggleClass('is-disabled', value === '0');
            status.saving();

            $.post(ajaxurl, {
                action: 'sitestaffr_toggle_custom_instruction',
                nonce: sitestaffrAgentData.nonces.agent,
                id: id,
                value: value
            }, function(response) {
                if (response.success) {
                    status.saved();
                } else {
                    status.error();
                    $input.prop('checked', !$input.is(':checked'));
                    $card.toggleClass('is-disabled', !$input.is(':checked'));
                }
            }).fail(function() {
                status.error();
                $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() {
            var $card = $(this).closest('.sitestaffr-ci-card');
            var id = $card.data('ci-id');
            window.SiteStaffrModal.confirm({
                message: sitestaffrAgentData.i18n.confirmDelete,
                danger: true
            }).then(function(ok) {
                if (!ok) return;
                $.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 {
                        notify(response.data?.message || sitestaffrAgentData.i18n.saveFailed);
                    }
                }).fail(function() {
                    notify(sitestaffrAgentData.i18n.saveFailed);
                });
            });
        });
    }

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