/**
 * WP Bootstrap Studio — Admin
 * Settings page functionality
 */
(function($) {
    'use strict';
    
    // Test Anthropic API key button
    $('#wpbs-test-anthropic').on('click', function() {
        var $btn = $(this);
        var $result = $('#wpbs-anthropic-result');
        var key = $('#wpbs-anthropic-key').val();

        if (!key) {
            $result.css('color', 'red').text('Enter an API key first.');
            return;
        }

        $btn.prop('disabled', true).text('Testing…');
        $result.text('');

        $.post(wpbs.ajaxUrl, {
            action: 'wpbs_test_anthropic',
            nonce: wpbs.settingsNonce,
            api_key: key,
        }).done(function(res) {
            if (res.success) {
                $result.css('color', 'green').text('✓ ' + res.data);
            } else {
                $result.css('color', 'red').text('✗ ' + res.data);
            }
        }).fail(function() {
            $result.css('color', 'red').text('✗ Request failed.');
        }).always(function() {
            $btn.prop('disabled', false).text('Test Key');
        });
    });

    // Re-index media library button — saves the key first
    $('#wpbs-reindex-media').on('click', function() {
        var $btn = $(this);
        var $status = $('#wpbs-anthropic-result');
        var key = $('#wpbs-anthropic-key').val();

        if (!key) {
            $status.css('color', 'red').text('Enter an Anthropic API key first.');
            return;
        }

        if (!confirm('This will clear the existing media index and re-scan all images using Haiku vision. Continue?')) return;

        $btn.prop('disabled', true);
        $status.css('color', '#0073aa').text('Saving key & starting re-index…');

        // Save the key first, then trigger re-index
        $.post(wpbs.ajaxUrl, {
            action: 'wpbs_save_anthropic_key',
            nonce: wpbs.settingsNonce,
            api_key: key,
        }).done(function() {
            $.post(wpbs.ajaxUrl, {
                action: 'wpbs_reindex_media',
                nonce: wpbs.settingsNonce,
            }).done(function() {
                $status.css('color', '#0073aa').text('Re-indexing in progress…');
                pollIndexProgress($btn, $status);
            }).fail(function() {
                $status.css('color', 'red').text('Failed to start re-index.');
                $btn.prop('disabled', false);
            });
        });
    });

    function pollIndexProgress($btn, $status) {
        $.post(wpbs.ajaxUrl, {
            action: 'wpbs_index_progress',
            nonce: wpbs.settingsNonce,
        }).done(function(res) {
            if (res.success && res.data) {
                var d = res.data;
                if (d.complete) {
                    $status.css('color', 'green').text('✓ Complete! ' + d.total + ' images indexed with Haiku vision.');
                    $btn.prop('disabled', false);
                } else {
                    $status.css('color', '#0073aa').text('Indexing… ' + d.done + '/' + d.total);
                    setTimeout(function() { pollIndexProgress($btn, $status); }, 3000);
                }
            }
        });
    }

    // Test connection button
    $('#wpbs-test-connection').on('click', async function() {
        const $btn = $(this);
        const $result = $('#wpbs-connection-result');
        
        $btn.prop('disabled', true).text('Testing...');
        $result.text('');
        
        try {
            const response = await $.ajax({
                url: wpbs.restUrl + 'test-connection',
                method: 'GET',
                headers: { 'X-WP-Nonce': wpbs.nonce },
            });
            
            if (response.connected) {
                $result.css('color', 'green').text('✓ Connected! ' + response.service + ' v' + response.version);
            } else {
                $result.css('color', 'red').text('✗ Failed: ' + (response.error || 'Unknown error'));
            }
        } catch (err) {
            $result.css('color', 'red').text('✗ Connection failed: ' + (err.statusText || 'Check your API URL'));
        } finally {
            $btn.prop('disabled', false).text('Test Connection');
        }
    });
    
})(jQuery);
