const PROVIDERS = new Set(['gemini', 'claude']);

export function createAiPreferences(storage) {
  const keyName = provider => `${provider}_api_key`;
  return {
    getProvider() {
      const provider = storage.getItem('ai_provider');
      return PROVIDERS.has(provider) ? provider : 'gemini';
    },
    setProvider(provider) {
      if (!PROVIDERS.has(provider)) throw new Error(`Unsupported AI provider: ${provider}`);
      storage.setItem('ai_provider', provider);
    },
    getKey(provider) {
      if (!PROVIDERS.has(provider)) return '';
      return storage.getItem(keyName(provider)) || '';
    },
    setKey(provider, key) {
      if (!PROVIDERS.has(provider)) throw new Error(`Unsupported AI provider: ${provider}`);
      storage.setItem(keyName(provider), key);
    },
    getCurrentKey() {
      return this.getKey(this.getProvider());
    },
    hasCurrentKey() {
      return !!this.getCurrentKey();
    },
  };
}

export function createAiStatusPresenter({ container, textarea }) {
  const text = container.querySelector('.ai-status-text');
  const icon = container.querySelector('.ai-status-icon');
  const progressBar = container.querySelector('.ai-progress-fill');
  const stream = container.querySelector('.ai-streaming-text');

  const restoreTextarea = () => {
    textarea?.classList.remove('ai-generating');
    if (textarea?.dataset.originalValue) {
      textarea.value = textarea.dataset.originalValue;
      delete textarea.dataset.originalValue;
    }
  };

  return {
    show(message, type = 'info', progress = null, streamText = null) {
      container.style.display = 'block';
      container.className = `ai-status-container${type === 'info' ? '' : ` ${type}`}`;
      text.textContent = message;
      if (type === 'info' && textarea) {
        textarea.classList.add('ai-generating');
        textarea.dataset.originalValue ||= textarea.value;
        textarea.value = message;
      } else {
        restoreTextarea();
      }
      icon.textContent = type === 'error' ? '❌' : type === 'success' ? '✓' : '';
      if (progress !== null) progressBar.style.width = `${Math.min(100, Math.max(0, progress))}%`;
      if (streamText !== null) {
        stream.style.display = 'block';
        stream.textContent = streamText;
        stream.scrollTop = stream.scrollHeight;
      } else if (type === 'error' || type === 'success') {
        stream.style.display = 'none';
      }
    },
    hide() {
      container.style.display = 'none';
      stream.style.display = 'none';
      stream.textContent = '';
      restoreTextarea();
    },
  };
}
