/**
 * Niwa AI — Admin Autonomy founder runtime settings.
 *
 * Rebuilds the founder model selector when the founder auth mode changes.
 *
 * @package Niwa_AI
 */
(function () {
	'use strict';

	var config = window.niwaAdminAutonomySettings || {};
	var modeSelect = document.getElementById( 'niwa-founder-auth-mode' );
	var modelSelect = document.getElementById( 'niwa-founder-agent-model' );

	if ( ! modeSelect || ! modelSelect || ! config.modelSets ) {
		return;
	}

	var modelSets = config.modelSets;
	var defaults = modelSets.defaults || {};

	function rebuildModelOptions( mode ) {
		var models = ( mode === 'oauth' ) ? modelSets.codex : modelSets.api_key;
		var defaultModel = ( mode === 'oauth' ) ? defaults.codex_chat : defaults.api_key_chat;
		var currentValue = modelSelect.value;

		if ( ! models || Object.keys( models ).length === 0 ) {
			models = {};
			if ( defaultModel ) {
				models[ defaultModel ] = defaultModel;
			}
		}

		modelSelect.innerHTML = '';

		var keys = Object.keys( models );
		var hasCurrentValue = false;

		for ( var i = 0; i < keys.length; i++ ) {
			var option = document.createElement( 'option' );
			option.value = keys[ i ];
			option.textContent = models[ keys[ i ] ];
			modelSelect.appendChild( option );

			if ( keys[ i ] === currentValue ) {
				hasCurrentValue = true;
			}
		}

		if ( hasCurrentValue ) {
			modelSelect.value = currentValue;
		} else if ( defaultModel && models[ defaultModel ] ) {
			modelSelect.value = defaultModel;
		}
	}

	modeSelect.addEventListener( 'change', function () {
		rebuildModelOptions( modeSelect.value );
	} );
})();
