const STORAGE_KEYS = {
  API_KEYS: 'apiKeys',
  SETTINGS: 'settings',
  CONVERSATIONS: 'conversations',
  ACTIVE_CONVERSATION: 'activeConversation'
};

const DEFAULT_SETTINGS = {
  defaultProvider: 'openai',
  defaultModel: 'gpt-4o',
  uiMode: 'sidepanel',
  theme: 'dark',
  language: 'de',
  fontSize: 'medium',
  systemPrompt: '',
  googleSearchCx: '',
  googleSearchKey: '',
  customBaseUrls: {},
  maxTokens: 4096,
  temperature: 0.7,
  systemPromptTemplate: ''
};

async function getSettings() {
  const result = await chrome.storage.sync.get(STORAGE_KEYS.SETTINGS);
  return { ...DEFAULT_SETTINGS, ...(result[STORAGE_KEYS.SETTINGS] || {}) };
}

async function saveSettings(settings) {
  await chrome.storage.sync.set({ [STORAGE_KEYS.SETTINGS]: settings });
}

async function getApiKeys() {
  const result = await chrome.storage.sync.get(STORAGE_KEYS.API_KEYS);
  return result[STORAGE_KEYS.API_KEYS] || {};
}

async function saveApiKeys(keys) {
  await chrome.storage.sync.set({ [STORAGE_KEYS.API_KEYS]: keys });
}

async function getConversations() {
  const result = await chrome.storage.local.get(STORAGE_KEYS.CONVERSATIONS);
  return result[STORAGE_KEYS.CONVERSATIONS] || {};
}

async function saveConversation(id, conversation) {
  const conversations = await getConversations();
  conversations[id] = conversation;
  await chrome.storage.local.set({ [STORAGE_KEYS.CONVERSATIONS]: conversations });
}

async function deleteConversation(id) {
  const conversations = await getConversations();
  delete conversations[id];
  await chrome.storage.local.set({ [STORAGE_KEYS.CONVERSATIONS]: conversations });
}

async function getActiveConversationId() {
  const result = await chrome.storage.local.get(STORAGE_KEYS.ACTIVE_CONVERSATION);
  return result[STORAGE_KEYS.ACTIVE_CONVERSATION] || null;
}

async function setActiveConversationId(id) {
  await chrome.storage.local.set({ [STORAGE_KEYS.ACTIVE_CONVERSATION]: id });
}

function generateId() {
  return Date.now().toString(36) + Math.random().toString(36).substr(2, 9);
}

function formatTimestamp(ts) {
  const d = new Date(ts);
  return d.toLocaleTimeString('de-DE', { hour: '2-digit', minute: '2-digit' });
}

function truncateText(text, maxLen = 500) {
  if (!text || text.length <= maxLen) return text;
  return text.substring(0, maxLen) + '...';
}

function escapeHtml(str) {
  if (!str) return '';
  return str
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#039;');
}

function renderMarkdown(text) {
  if (!text) return '';
  let html = escapeHtml(text);
  html = html.replace(/```(\w*)\n([\s\S]*?)```/g, '<pre><code class="lang-$1">$2</code></pre>');
  html = html.replace(/`([^`]+)`/g, '<code>$1</code>');
  html = html.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>');
  html = html.replace(/\*(.+?)\*/g, '<em>$1</em>');
  html = html.replace(/^### (.+)$/gm, '<h3>$1</h3>');
  html = html.replace(/^## (.+)$/gm, '<h2>$1</h2>');
  html = html.replace(/^# (.+)$/gm, '<h1>$1</h1>');
  html = html.replace(/^- (.+)$/gm, '<li>$1</li>');
  html = html.replace(/(\d+)\. (.+)$/gm, '<li>$2</li>');
  html = html.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2" target="_blank">$1</a>');
  html = html.replace(/\n\n/g, '</p><p>');
  html = html.replace(/\n/g, '<br>');
  return '<p>' + html + '</p>';
}

export {
  STORAGE_KEYS, DEFAULT_SETTINGS,
  getSettings, saveSettings,
  getApiKeys, saveApiKeys,
  getConversations, saveConversation, deleteConversation,
  getActiveConversationId, setActiveConversationId,
  generateId, formatTimestamp, truncateText,
  escapeHtml, renderMarkdown
};
