/**
 * AI Configuration Management Module
 * Multi-tenant AI provider configuration with instance support
 */

console.log('AI Config.js loaded');

// Global variables
let aiConfigs = [];
let aiInstances = [];
let currentEditingConfig = null;
let aiSelectedInstanceId = null;

// Register page handler
if (!window.pageHandlers) {
  console.log('pageHandlers not defined, creating it');
  window.pageHandlers = {};
}

window.pageHandlers['ai-config'] = function () {
  console.log('AI Config handler called!');
  
  // Check feature and load page
  if (typeof checkFeatureEnabled === 'function') {
    checkFeatureEnabled('ai').then(enabled => {
      if (enabled) {
        loadAIConfigPage();
      }
    }).catch(err => {
      console.error('Error checking feature:', err);
      // Load anyway if check fails
      loadAIConfigPage();
    });
  } else {
    // If checkFeatureEnabled doesn't exist, load directly
    loadAIConfigPage();
  }
};

console.log('AI Config handler registered:', typeof window.pageHandlers['ai-config']);

// ===== PAGE INITIALIZATION =====

function loadAIConfigPage() {
  console.log('🤖 Loading AI Config page...');
  console.log('🤖 aiConfigsList element:', document.getElementById('aiConfigsList'));
  loadAIInstances();
  console.log('🤖 AI Config page initialization complete');
}

// ===== STATISTICS =====

async function loadAIStats() {
  try {
    const token = localStorage.getItem('token');
    const response = await fetch('/api/tenant/ai-config/stats', {
      headers: {
        Authorization: `Bearer ${token}`
      }
    });


    if (response.ok) {
      const stats = await response.json();
      document.getElementById('todayAIMessages').textContent = stats.today_ai_messages;
      document.getElementById('weekAIMessages').textContent = stats.week_ai_messages;
      document.getElementById('avgResponseTime').textContent = `${stats.avg_response_time.toFixed(2)}s`;
      document.getElementById('activeConfigName').textContent = stats.active_config
        ? stats.active_config.persona_name
        : 'None';
    }
  } catch (error) {
    console.error('Error loading AI stats:', error);
  }
}

// ===== INSTANCES =====

async function loadAIInstances() {
  try {
    console.log('🔍 Loading AI instances...');
    const token = localStorage.getItem('token');
    console.log('🔍 Token:', token ? 'exists' : 'missing');
    
    const response = await fetch('/api/tenant/ai-config/instances', {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });
    
    console.log('🔍 Response status:', response.status);
    
    if (response.ok) {
      const result = await response.json();
      console.log('🔍 Response data:', result);
      aiInstances = result.data || [];
      console.log('🔍 AI Instances loaded:', aiInstances.length, aiInstances);
      await loadAIConfigs();
      renderInstanceCards();
    } else {
      console.error('❌ Failed to load instances:', response.status);
      const errorText = await response.text();
      console.error('❌ Error response:', errorText);
      aiInstances = [];
      renderInstanceCards();
    }
  } catch (error) {
    console.error('❌ Error loading instances:', error);
    aiInstances = [];
    renderInstanceCards();
  }
}

// ===== CONFIGURATIONS LIST =====

async function loadAIConfigs() {
  try {
    const token = localStorage.getItem('token');
    const response = await fetch('/api/tenant/ai-config/settings', {
      headers: {
        Authorization: `Bearer ${token}`
      }
    });

    if (response.ok) {
      aiConfigs = await response.json();
      console.log('AI Configs loaded:', aiConfigs);
    }
  } catch (error) {
    console.error('Error loading AI configs:', error);
  }
}

function renderInstanceCards() {
  const container = document.getElementById('aiConfigsList');
  if (!container) return;

  container.innerHTML = '';

  if (aiInstances.length === 0) {
    container.innerHTML = `
      <div style="padding: 40px; text-align: center; background: #fff3cd; border: 1px solid #ffc107; border-radius: 8px;">
        <i class="fas fa-exclamation-triangle" style="color: #856404; font-size: 48px; margin-bottom: 15px;"></i>
        <h3 style="color: #856404; margin-bottom: 10px;" data-i18n="ai_config.no_instances_title">No Instances Found</h3>
        <p style="color: #856404; margin-bottom: 20px;" data-i18n="ai_config.no_instances_desc">
          Create a WhatsApp instance first to configure AI settings.
        </p>
        <a href="#whatsapp" onclick="navigateTo('whatsapp')" class="btn btn-primary">
          <i class="fas fa-plus"></i> <span data-i18n="ai_config.create_instance">Create Instance</span>
        </a>
      </div>
    `;
    if (window.applyTranslations) window.applyTranslations();
    return;
  }

  aiInstances.forEach(instance => {
    const config = aiConfigs.find(c => c.evolution_instance_id === instance.id);
    const hasConfig = !!config;

    const cardDiv = document.createElement('div');
    cardDiv.style.cssText = 'margin-bottom: 20px; border: 2px solid #e0e0e0; border-radius: 12px; overflow: hidden; background: white; box-shadow: 0 2px 8px rgba(0,0,0,0.1);';

    const statusColors = {
      connected: '#4CAF50',
      disconnected: '#f44336',
      connecting: '#FF9800',
      qr_code: '#2196F3',
      error: '#f44336'
    };

    const providerColors = {
      deepseek: '#4CAF50',
      gpt: '#2196F3',
      openai: '#2196F3'
    };

    const statusColor = statusColors[instance.status] || '#666';
    const providerColor = hasConfig ? (providerColors[config.provider] || '#666') : '#999';

    cardDiv.innerHTML = `
      <div style="padding: 20px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white;">
        <div style="display: flex; justify-content: space-between; align-items: start; margin-bottom: 15px;">
          <div style="flex: 1;">
            <h3 style="margin: 0 0 8px 0; font-size: 20px; display: flex; align-items: center; gap: 10px;">
              <i class="fas fa-mobile-alt"></i>
              ${escapeHtml(instance.instance_name)}
            </h3>
            <div style="font-size: 14px; opacity: 0.9;">
              ${instance.phone_number ? `📱 ${instance.phone_number}` : '<span data-i18n="ai_config.no_phone">No phone number</span>'}
            </div>
          </div>
          <div style="text-align: right;">
            <span style="background: ${statusColor}; padding: 6px 12px; border-radius: 20px; font-size: 12px; font-weight: bold; text-transform: uppercase; display: inline-block; margin-bottom: 8px;">
              ${instance.status}
            </span>
            ${hasConfig && config.active ? '<div style="background: rgba(255,255,255,0.3); padding: 4px 10px; border-radius: 15px; font-size: 11px; display: inline-block;"><i class="fas fa-check-circle"></i> <span data-i18n="ai_config.active">Active</span></div>' : ''}
          </div>
        </div>
      </div>

      <div style="padding: 20px;">
        ${hasConfig ? `
          <div style="margin-bottom: 20px;">
            <!-- Statistics for this instance -->
            <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 10px; margin-bottom: 15px;">
              <div style="background: #e3f2fd; padding: 12px; border-radius: 8px; text-align: center;">
                <div style="font-size: 11px; color: #1976d2; font-weight: 600; margin-bottom: 4px;" data-i18n="ai_config.today_messages">Today</div>
                <div style="font-size: 24px; font-weight: bold; color: #1976d2;">0</div>
              </div>
              <div style="background: #e8f5e9; padding: 12px; border-radius: 8px; text-align: center;">
                <div style="font-size: 11px; color: #388e3c; font-weight: 600; margin-bottom: 4px;" data-i18n="ai_config.week_messages">This Week</div>
                <div style="font-size: 24px; font-weight: bold; color: #388e3c;">0</div>
              </div>
            </div>

            <div style="display: flex; align-items: center; gap: 10px; margin-bottom: 15px;">
              <span style="background: ${providerColor}; color: white; padding: 6px 16px; border-radius: 6px; font-size: 13px; font-weight: bold; text-transform: uppercase;">
                ${config.provider}
              </span>
              <span style="color: #666; font-size: 14px;">${config.model_name}</span>
            </div>
            
            <div style="background: #f8f9fa; padding: 15px; border-radius: 8px; margin-bottom: 15px;">
              <div style="font-weight: bold; font-size: 16px; margin-bottom: 5px; color: #333;">
                ${escapeHtml(config.persona_name)}
              </div>
              ${config.persona_description ? `<div style="color: #666; font-size: 13px; margin-bottom: 10px;">${escapeHtml(config.persona_description)}</div>` : ''}
              
              <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 10px; margin-top: 10px; font-size: 12px;">
                <div>
                  <strong data-i18n="ai_config.temperature">Temperature:</strong> ${config.temperature}
                </div>
                <div>
                  <strong data-i18n="ai_config.max_tokens">Max Tokens:</strong> ${config.max_tokens}
                </div>
                <div>
                  <strong data-i18n="ai_config.response_delay">Delay:</strong> ${config.response_delay}s
                </div>
                <div>
                  <strong data-i18n="ai_config.api_key_status">API Key:</strong> 
                  <span style="color: ${config.api_key_status === 'configured' ? '#4CAF50' : '#f44336'};">
                    ${config.api_key_status === 'configured' ? '✓' : '✗'}
                  </span>
                </div>
              </div>
            </div>

            <div style="display: flex; gap: 8px; flex-wrap: wrap;">
              <button class="btn btn-sm btn-info" onclick="testAIConfig(${config.id})" title="${i18n.t('ai_config.test')}">
                <i class="fas fa-vial"></i> <span data-i18n="ai_config.test">Test</span>
              </button>
              <button class="btn btn-sm btn-primary" onclick="editAIConfig(${config.id})" title="${i18n.t('btn.edit')}">
                <i class="fas fa-edit"></i> <span data-i18n="btn.edit">Edit</span>
              </button>
              <button class="btn btn-sm ${config.active ? 'btn-warning' : 'btn-success'}" onclick="toggleAIConfig(${config.id}, ${!config.active})">
                <i class="fas fa-${config.active ? 'pause' : 'play'}"></i>
                <span data-i18n="${config.active ? 'btn.deactivate' : 'btn.activate'}">${config.active ? 'Deactivate' : 'Activate'}</span>
              </button>
              <button class="btn btn-sm btn-danger" onclick="deleteAIConfig(${config.id})" title="${i18n.t('btn.delete')}">
                <i class="fas fa-trash"></i> <span data-i18n="btn.delete">Delete</span>
              </button>
            </div>
          </div>
        ` : `
          <div style="text-align: center; padding: 30px; color: #999;">
            <i class="fas fa-robot" style="font-size: 48px; margin-bottom: 15px; opacity: 0.3;"></i>
            <p style="margin-bottom: 20px;" data-i18n="ai_config.no_config_for_instance">No AI configuration for this instance</p>
            <button class="btn btn-primary" onclick="showAddAIConfigModal(${instance.id})">
              <i class="fas fa-plus"></i> <span data-i18n="ai_config.add_config">Add Configuration</span>
            </button>
          </div>
        `}
      </div>
    `;

    container.appendChild(cardDiv);
  });

  if (window.applyTranslations) window.applyTranslations();
}

// ===== ADD/EDIT CONFIGURATION =====

function showAddAIConfigModal(instanceId) {
  aiSelectedInstanceId = instanceId;
  currentEditingConfig = null;
  showAIConfigModal();
}

function editAIConfig(configId) {
  const config = aiConfigs.find((c) => c.id === configId);
  if (!config) return;

  currentEditingConfig = config;
  aiSelectedInstanceId = config.evolution_instance_id;
  showAIConfigModal(config);
}

async function showAIConfigModal(config = null) {
  const modal = document.createElement('div');
  modal.id = 'aiConfigModal';
  modal.style.cssText = 'position: fixed; z-index: 1000; left: 0; top: 0; width: 100%; height: 100%; background-color: rgba(0,0,0,0.5); display: flex; align-items: center; justify-content: center; overflow-y: auto;';

  const instance = aiInstances.find(i => i.id === aiSelectedInstanceId);
  const instanceName = instance ? instance.instance_name : 'Unknown';

  let modelsHtml = '';
  if (config && config.provider) {
    const models = await loadModelsForProvider(config.provider);
    modelsHtml = models.map(m => 
      `<option value="${m.id}" ${config.model_name === m.id ? 'selected' : ''}>${m.name}</option>`
    ).join('');
  }

  modal.innerHTML = `
    <div style="background: white; padding: 0; border-radius: 12px; width: 90%; max-width: 800px; max-height: 90vh; overflow: hidden; display: flex; flex-direction: column;">
      <div style="padding: 25px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white;">
        <h2 style="margin: 0; font-size: 24px;">
          <i class="fas fa-robot"></i>
          <span data-i18n="ai_config.${config ? 'edit_config' : 'add_config'}">${config ? 'Edit AI Configuration' : 'Add AI Configuration'}</span>
        </h2>
        <p style="margin: 8px 0 0 0; opacity: 0.9; font-size: 14px;">
          <i class="fas fa-mobile-alt"></i> ${escapeHtml(instanceName)}
        </p>
      </div>
      
      <div style="padding: 25px; overflow-y: auto; flex: 1;">
        <form id="aiConfigForm" onsubmit="handleAIConfigSubmit(event)">
          
          <div class="form-group" style="margin-bottom: 20px;">
            <label style="display: block; margin-bottom: 8px; font-weight: 600; color: #333;">
              <span data-i18n="ai_config.provider">Provider</span> <span style="color: red;">*</span>
            </label>
            <select id="aiProvider" class="form-control" onchange="onProviderChange()" required style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px;">
              <option value="" data-i18n="ai_config.select_provider">Select provider...</option>
              <option value="deepseek" ${config?.provider === 'deepseek' ? 'selected' : ''}>DeepSeek</option>
              <option value="gpt" ${config?.provider === 'gpt' ? 'selected' : ''}>OpenAI GPT</option>
            </select>
          </div>

          <div class="form-group" style="margin-bottom: 20px;">
            <label style="display: block; margin-bottom: 8px; font-weight: 600; color: #333;">
              <span data-i18n="ai_config.model">Model</span> <span style="color: red;">*</span>
            </label>
            <select id="aiModel" class="form-control" required style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px;">
              <option value="" data-i18n="ai_config.select_model">Select model...</option>
              ${modelsHtml}
            </select>
          </div>

          <div class="form-group" style="margin-bottom: 20px;">
            <label style="display: block; margin-bottom: 8px; font-weight: 600; color: #333;">
              <span data-i18n="ai_config.api_key">API Key</span> <span style="color: red;">*</span>
            </label>
            <input type="password" id="aiApiKey" class="form-control" ${config ? '' : 'required'} 
              placeholder="${config ? '••••••••••••••••' : 'Enter API key'}"
              style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px;">
            ${config ? '<small style="color: #666;" data-i18n="ai_config.api_key_leave_blank">Leave blank to keep current key</small>' : ''}
          </div>

          <div class="form-group" style="margin-bottom: 20px;">
            <label style="display: block; margin-bottom: 8px; font-weight: 600; color: #333;">
              <span data-i18n="ai_config.persona_name">Persona Name</span> <span style="color: red;">*</span>
            </label>
            <input type="text" id="aiPersonaName" class="form-control" required 
              value="${config ? escapeHtml(config.persona_name) : ''}"
              placeholder="e.g., Customer Support Assistant"
              style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px;">
          </div>

          <div class="form-group" style="margin-bottom: 20px;">
            <label style="display: block; margin-bottom: 8px; font-weight: 600; color: #333;">
              <span data-i18n="ai_config.persona_description">Persona Description</span>
            </label>
            <textarea id="aiPersonaDescription" class="form-control" rows="2"
              placeholder="Brief description of the AI persona"
              style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px;">${config ? escapeHtml(config.persona_description || '') : ''}</textarea>
          </div>

          <div class="form-group" style="margin-bottom: 20px;">
            <label style="display: block; margin-bottom: 8px; font-weight: 600; color: #333;">
              <span data-i18n="ai_config.system_prompt">System Prompt</span> <span style="color: red;">*</span>
            </label>
            <textarea id="aiSystemPrompt" class="form-control" rows="4" required
              placeholder="You are a helpful customer support assistant..."
              style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px;">${config ? escapeHtml(config.system_prompt || '') : ''}</textarea>
          </div>

          <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px; margin-bottom: 20px;">
            <div class="form-group">
              <label style="display: block; margin-bottom: 8px; font-weight: 600; color: #333;">
                <span data-i18n="ai_config.temperature">Temperature</span>
              </label>
              <input type="number" id="aiTemperature" class="form-control" 
                value="${config ? config.temperature : 0.7}" 
                min="0" max="2" step="0.1"
                style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px;">
            </div>

            <div class="form-group">
              <label style="display: block; margin-bottom: 8px; font-weight: 600; color: #333;">
                <span data-i18n="ai_config.max_tokens">Max Tokens</span>
              </label>
              <input type="number" id="aiMaxTokens" class="form-control" 
                value="${config ? config.max_tokens : 1000}" 
                min="100" max="8000"
                style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px;">
            </div>
          </div>

          <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px; margin-bottom: 20px;">
            <div class="form-group">
              <label style="display: block; margin-bottom: 8px; font-weight: 600; color: #333;">
                <span data-i18n="ai_config.business_hours_start">Business Hours Start</span>
              </label>
              <input type="time" id="aiBusinessHoursStart" class="form-control" 
                value="${config ? config.business_hours_start : '08:00'}"
                style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px;">
            </div>

            <div class="form-group">
              <label style="display: block; margin-bottom: 8px; font-weight: 600; color: #333;">
                <span data-i18n="ai_config.business_hours_end">Business Hours End</span>
              </label>
              <input type="time" id="aiBusinessHoursEnd" class="form-control" 
                value="${config ? config.business_hours_end : '18:00'}"
                style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px;">
            </div>
          </div>

          <div class="form-group" style="margin-bottom: 20px;">
            <label style="display: block; margin-bottom: 8px; font-weight: 600; color: #333;">
              <span data-i18n="ai_config.business_days">Business Days</span>
            </label>
            <div style="display: flex; flex-wrap: wrap; gap: 10px;">
              ${['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'].map(day => {
                const checked = config && config.business_days && config.business_days.includes(day) ? 'checked' : (!config && day !== 'sunday' ? 'checked' : '');
                return `
                  <label style="display: flex; align-items: center; gap: 5px; padding: 8px 12px; background: #f8f9fa; border-radius: 6px; cursor: pointer;">
                    <input type="checkbox" class="business-day" value="${day}" ${checked}>
                    <span data-i18n="days.${day}">${day.charAt(0).toUpperCase() + day.slice(1)}</span>
                  </label>
                `;
              }).join('')}
            </div>
          </div>

          <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px; margin-bottom: 20px;">
            <div class="form-group">
              <label style="display: flex; align-items: center; gap: 8px; font-weight: 600; color: #333;">
                <input type="checkbox" id="aiAutoResponse" ${config?.auto_response_enabled !== false ? 'checked' : ''}>
                <span data-i18n="ai_config.auto_response_enabled">Auto Response Enabled</span>
              </label>
            </div>

            <div class="form-group">
              <label style="display: block; margin-bottom: 8px; font-weight: 600; color: #333;">
                <span data-i18n="ai_config.response_delay">Response Delay (seconds)</span>
              </label>
              <input type="number" id="aiResponseDelay" class="form-control" 
                value="${config ? config.response_delay : 2}" 
                min="0" max="60"
                style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px;">
            </div>
          </div>

          <div class="form-group" style="margin-bottom: 20px;">
            <label style="display: flex; align-items: center; gap: 8px; font-weight: 600; color: #333;">
              <input type="checkbox" id="aiActive" ${config?.active !== false ? 'checked' : ''}>
              <span data-i18n="ai_config.set_active">Set as Active</span>
            </label>
            <small style="color: #666; display: block; margin-top: 5px;" data-i18n="ai_config.active_note">
              Only one configuration can be active per instance
            </small>
          </div>

        </form>
      </div>

      <div style="padding: 20px; background: #f8f9fa; border-top: 1px solid #e0e0e0; display: flex; gap: 10px; justify-content: flex-end;">
        <button onclick="closeAIConfigModal()" class="btn btn-secondary">
          <span data-i18n="common.cancel">Cancel</span>
        </button>
        <button onclick="submitAIConfig()" class="btn btn-primary">
          <i class="fas fa-save"></i> <span data-i18n="btn.save">Save</span>
        </button>
      </div>
    </div>
  `;

  document.body.appendChild(modal);
  if (window.applyTranslations) window.applyTranslations();
}

function closeAIConfigModal() {
  const modal = document.getElementById('aiConfigModal');
  if (modal) {
    modal.remove();
  }
  currentEditingConfig = null;
  aiSelectedInstanceId = null;
}

async function onProviderChange() {
  const provider = document.getElementById('aiProvider').value;
  const modelSelect = document.getElementById('aiModel');
  
  if (!provider) {
    modelSelect.innerHTML = '<option value="" data-i18n="ai_config.select_model">Select model...</option>';
    return;
  }

  const models = await loadModelsForProvider(provider);
  modelSelect.innerHTML = '<option value="" data-i18n="ai_config.select_model">Select model...</option>' +
    models.map(m => `<option value="${m.id}">${m.name}</option>`).join('');
  
  if (window.applyTranslations) window.applyTranslations();
}

async function loadModelsForProvider(provider) {
  try {
    const token = localStorage.getItem('token');
    const response = await fetch(`/api/tenant/ai-config/models/${provider}`, {
      headers: { Authorization: `Bearer ${token}` }
    });

    if (response.ok) {
      return await response.json();
    }
  } catch (error) {
    console.error('Error loading models:', error);
  }
  return [];
}

async function submitAIConfig() {
  try {
    const provider = document.getElementById('aiProvider').value;
    const model = document.getElementById('aiModel').value;
    const apiKey = document.getElementById('aiApiKey').value;
    const personaName = document.getElementById('aiPersonaName').value;
    const personaDescription = document.getElementById('aiPersonaDescription').value;
    const systemPrompt = document.getElementById('aiSystemPrompt').value;
    const temperature = parseFloat(document.getElementById('aiTemperature').value);
    const maxTokens = parseInt(document.getElementById('aiMaxTokens').value);
    const businessHoursStart = document.getElementById('aiBusinessHoursStart').value;
    const businessHoursEnd = document.getElementById('aiBusinessHoursEnd').value;
    const autoResponse = document.getElementById('aiAutoResponse').checked;
    const responseDelay = parseInt(document.getElementById('aiResponseDelay').value);
    const active = document.getElementById('aiActive').checked;

    const businessDays = Array.from(document.querySelectorAll('.business-day:checked'))
      .map(cb => cb.value)
      .join(',');

    if (!provider || !model || (!currentEditingConfig && !apiKey) || !personaName || !systemPrompt) {
      showNotification(i18n.t('ai_config.required_fields') || 'Please fill all required fields', 'error');
      return;
    }

    const data = {
      evolution_instance_id: aiSelectedInstanceId,
      provider,
      model_name: model,
      persona_name: personaName,
      persona_description: personaDescription,
      system_prompt: systemPrompt,
      temperature,
      max_tokens: maxTokens,
      business_hours_start: businessHoursStart,
      business_hours_end: businessHoursEnd,
      business_days: businessDays,
      auto_response_enabled: autoResponse,
      response_delay: responseDelay,
      active
    };

    if (apiKey) {
      data.api_key = apiKey;
    }

    const token = localStorage.getItem('token');
    const url = currentEditingConfig
      ? `/api/tenant/ai-config/settings/${currentEditingConfig.id}`
      : '/api/tenant/ai-config/settings';
    const method = currentEditingConfig ? 'PUT' : 'POST';

    const response = await fetch(url, {
      method,
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${token}`
      },
      body: JSON.stringify(data)
    });

    if (response.ok) {
      showNotification(
        i18n.t(currentEditingConfig ? 'ai_config.updated_success' : 'ai_config.created_success') || 
        `Configuration ${currentEditingConfig ? 'updated' : 'created'} successfully`,
        'success'
      );
      closeAIConfigModal();
      // CRITICAL FIX: Reload instances and configs to show updated data
      await loadAIInstances();
    } else {
      const error = await response.json();
      showNotification(error.error || 'Error saving configuration', 'error');
    }
  } catch (error) {
    console.error('Error saving AI config:', error);
    showNotification('Error saving configuration', 'error');
  }
}

// ===== TOGGLE CONFIGURATION =====

async function toggleAIConfig(configId, newStatus) {
  try {
    const token = localStorage.getItem('token');
    const response = await fetch(`/api/tenant/ai-config/settings/${configId}/toggle`, {
      method: 'PATCH',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${token}`
      },
      body: JSON.stringify({ active: newStatus })
    });

    if (response.ok) {
      showNotification(
        i18n.t(newStatus ? 'ai_config.activated_success' : 'ai_config.deactivated_success') || 
        `Configuration ${newStatus ? 'activated' : 'deactivated'} successfully`,
        'success'
      );
      // CRITICAL FIX: Reload instances to show updated status
      await loadAIInstances();
    } else {
      const error = await response.json();
      showNotification(error.error || 'Error updating status', 'error');
    }
  } catch (error) {
    console.error('Error toggling config:', error);
    showNotification('Error updating status', 'error');
  }
}

// ===== DELETE CONFIGURATION =====

async function deleteAIConfig(configId) {
  const confirmed = await showCustomConfirm(
    i18n.t('ai_config.delete_confirm') || 'Are you sure you want to delete this AI configuration?'
  );
  
  if (!confirmed) return;

  try {
    const token = localStorage.getItem('token');
    const response = await fetch(`/api/tenant/ai-config/settings/${configId}`, {
      method: 'DELETE',
      headers: {
        Authorization: `Bearer ${token}`
      }
    });

    if (response.ok) {
      showNotification(i18n.t('ai_config.deleted_success') || 'Configuration deleted successfully', 'success');
      // CRITICAL FIX: Reload instances to show updated list
      await loadAIInstances();
    } else {
      const error = await response.json();
      showNotification(error.error || 'Error deleting configuration', 'error');
    }
  } catch (error) {
    console.error('Error deleting config:', error);
    showNotification('Error deleting configuration', 'error');
  }
}

// ===== TEST CONFIGURATION =====

async function testAIConfig(configId) {
  const modal = document.createElement('div');
  modal.id = 'testAIModal';
  modal.style.cssText = 'position: fixed; z-index: 1001; left: 0; top: 0; width: 100%; height: 100%; background-color: rgba(0,0,0,0.5); display: flex; align-items: center; justify-content: center;';

  modal.innerHTML = `
    <div style="background: white; padding: 30px; border-radius: 12px; width: 90%; max-width: 600px;">
      <h3 style="margin: 0 0 20px 0;">
        <i class="fas fa-vial"></i> <span data-i18n="ai_config.test">Test Configuration</span>
      </h3>
      
      <div class="form-group" style="margin-bottom: 20px;">
        <label style="display: block; margin-bottom: 8px; font-weight: 600;">
          <span data-i18n="ai_config.test_message">Test Message</span>
        </label>
        <textarea id="testMessage" class="form-control" rows="3" 
          placeholder="Hello, how can you help me?"
          style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px;">Hello, this is a connection test.</textarea>
      </div>

      <div id="testResult" style="display: none; padding: 15px; border-radius: 8px; margin-bottom: 20px;"></div>

      <div style="display: flex; gap: 10px; justify-content: flex-end;">
        <button onclick="closeTestModal()" class="btn btn-secondary">
          <span data-i18n="common.close">Close</span>
        </button>
        <button onclick="runAITest(${configId})" class="btn btn-primary" id="testButton">
          <i class="fas fa-play"></i> <span data-i18n="ai_config.run_test">Run Test</span>
        </button>
      </div>
    </div>
  `;

  document.body.appendChild(modal);
  if (window.applyTranslations) window.applyTranslations();
}

function closeTestModal() {
  const modal = document.getElementById('testAIModal');
  if (modal) modal.remove();
}

async function runAITest(configId) {
  const testButton = document.getElementById('testButton');
  const resultDiv = document.getElementById('testResult');
  const testMessage = document.getElementById('testMessage').value;

  testButton.disabled = true;
  testButton.innerHTML = '<i class="fas fa-spinner fa-spin"></i> <span data-i18n="ai_config.testing">Testing...</span>';
  resultDiv.style.display = 'none';

  try {
    const token = localStorage.getItem('token');
    const response = await fetch(`/api/tenant/ai-config/test/${configId}`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${token}`
      },
      body: JSON.stringify({ test_message: testMessage })
    });

    const result = await response.json();

    if (result.success) {
      resultDiv.style.cssText = 'display: block; padding: 15px; border-radius: 8px; margin-bottom: 20px; background: #d4edda; border: 1px solid #c3e6cb; color: #155724;';
      resultDiv.innerHTML = `
        <div style="font-weight: bold; margin-bottom: 10px;">
          <i class="fas fa-check-circle"></i> <span data-i18n="ai_config.test_success">✓ Connection successful!</span>
        </div>
        <div style="margin-bottom: 10px;">
          <strong data-i18n="ai_config.ai_response">AI Response:</strong>
          <div style="background: white; padding: 10px; border-radius: 6px; margin-top: 5px; color: #333;">
            ${escapeHtml(result.response)}
          </div>
        </div>
        ${result.usage ? `
          <div style="font-size: 12px; opacity: 0.8;">
            <strong data-i18n="ai_config.usage">Usage:</strong> 
            ${result.usage.prompt_tokens} prompt + ${result.usage.completion_tokens} completion = ${result.usage.total_tokens} tokens
          </div>
        ` : ''}
      `;
    } else {
      resultDiv.style.cssText = 'display: block; padding: 15px; border-radius: 8px; margin-bottom: 20px; background: #f8d7da; border: 1px solid #f5c6cb; color: #721c24;';
      resultDiv.innerHTML = `
        <div style="font-weight: bold; margin-bottom: 10px;">
          <i class="fas fa-times-circle"></i> <span data-i18n="ai_config.test_failed">✗ Test failed</span>
        </div>
        <div>${escapeHtml(result.error)}</div>
      `;
    }
  } catch (error) {
    console.error('Error testing config:', error);
    resultDiv.style.cssText = 'display: block; padding: 15px; border-radius: 8px; margin-bottom: 20px; background: #f8d7da; border: 1px solid #f5c6cb; color: #721c24;';
    resultDiv.innerHTML = `<i class="fas fa-times-circle"></i> ${escapeHtml(error.message)}`;
  } finally {
    testButton.disabled = false;
    testButton.innerHTML = '<i class="fas fa-play"></i> <span data-i18n="ai_config.run_test">Run Test</span>';
    if (window.applyTranslations) window.applyTranslations();
  }
}

// ===== UTILITY FUNCTIONS =====

function escapeHtml(text) {
  if (!text) return '';
  const div = document.createElement('div');
  div.textContent = text;
  return div.innerHTML;
}

async function showCustomConfirm(message) {
  return new Promise((resolve) => {
    const modal = document.createElement('div');
    modal.style.cssText = 'position: fixed; z-index: 2000; left: 0; top: 0; width: 100%; height: 100%; background-color: rgba(0,0,0,0.5); display: flex; align-items: center; justify-content: center;';
    
    modal.innerHTML = `
      <div style="background: white; padding: 30px; border-radius: 12px; max-width: 400px; text-align: center;">
        <i class="fas fa-exclamation-triangle" style="font-size: 48px; color: #ff9800; margin-bottom: 15px;"></i>
        <p style="margin-bottom: 25px; font-size: 16px;">${message}</p>
        <div style="display: flex; gap: 10px; justify-content: center;">
          <button onclick="this.closest('div[style*=fixed]').remove()" class="btn btn-secondary" data-i18n="common.cancel">Cancel</button>
          <button onclick="this.closest('div[style*=fixed]').remove(); window.confirmCallback(true)" class="btn btn-danger" data-i18n="common.confirm">Confirm</button>
        </div>
      </div>
    `;
    
    window.confirmCallback = (result) => {
      resolve(result);
      delete window.confirmCallback;
    };
    
    document.body.appendChild(modal);
    if (window.applyTranslations) window.applyTranslations();
    
    modal.querySelector('.btn-secondary').onclick = () => {
      modal.remove();
      resolve(false);
      delete window.confirmCallback;
    };
  });
}
