// ═══════════════════════════════════════════════════════
//  CVC Dashboard — Settings Module
//  (Compiled from ts/settings.ts — edit TypeScript source)
// ═══════════════════════════════════════════════════════
"use strict";

let _settingsDirty = false;
let _settingsCache = null;

function _escSettings(s) {
  const d = document.createElement('div');
  d.textContent = s;
  return d.innerHTML;
}

// ── Collapsible sections ────────────────────────────
function setupCollapsible() {
  document.querySelectorAll('.card-header.collapsible').forEach(header => {
    header.addEventListener('click', () => {
      const targetId = header.dataset.target;
      if (!targetId) return;
      const body = document.getElementById(targetId);
      if (!body) return;
      const arrow = header.querySelector('.collapse-arrow');
      if (body.classList.contains('collapsed')) {
        body.classList.remove('collapsed');
        body.style.display = '';
        if (arrow) arrow.textContent = '▼';
      } else {
        body.classList.add('collapsed');
        body.style.display = 'none';
        if (arrow) arrow.textContent = '▶';
      }
    });
  });
}

// ── Level tabs ──────────────────────────────────────
function setupSettingsLevelTabs() {
  document.querySelectorAll('.settings-level-tab').forEach(btn => {
    btn.addEventListener('click', () => {
      document.querySelectorAll('.settings-level-tab').forEach(b => b.classList.remove('active'));
      btn.classList.add('active');
    });
  });
}

// ── Search ──────────────────────────────────────────
function setupSettingsSearch() {
  const input = document.getElementById('settings-search');
  if (!input) return;
  input.addEventListener('input', () => {
    const q = input.value.toLowerCase();
    document.querySelectorAll('.settings-section').forEach(section => {
      const text = section.textContent?.toLowerCase() || '';
      section.style.display = !q || text.includes(q) ? '' : 'none';
    });
  });
}

// ── Mark dirty ──────────────────────────────────────
function markSettingsDirty() {
  _settingsDirty = true;
  const bar = document.getElementById('settings-save-bar');
  if (bar) bar.style.display = '';
}

// ── Helpers ─────────────────────────────────────────
function _setVal(id, value) {
  const el = document.getElementById(id);
  if (el) el.value = value;
}
function _setChecked(id, checked) {
  const el = document.getElementById(id);
  if (el) el.checked = checked;
}
function _parseCSV(id) {
  const el = document.getElementById(id);
  if (!el || !el.value) return [];
  return el.value.split(',').map(s => s.trim()).filter(Boolean);
}

// ── API Keys ────────────────────────────────────────
var _apiKeyPlaceholders = {
  anthropic: 'sk-ant-api03-…',
  openai:    'sk-proj-…',
  google:    'AIza…',
  openrouter:'sk-or-v1-…',
};

function renderApiKeys(keys) {
  const container = document.getElementById('api-keys-container');
  if (!container) return;
  const providers = ['anthropic', 'openai', 'google', 'openrouter'];
  container.innerHTML = providers.map(p => {
    const has = !!keys[p];
    const ph = _apiKeyPlaceholders[p] || 'API key…';
    return `<div class="api-key-row">
      <span class="api-key-provider">${_escSettings(p)}</span>
      <input type="password" class="input input-sm api-key-input" data-provider="${_escSettings(p)}"
        value="${has ? '••••••••' : ''}" placeholder="${_escSettings(ph)}" style="width:200px" />
      <button class="btn btn-sm ${has ? 'btn-green' : ''}" onclick="setApiKeyUI('${_escSettings(p)}')">${has ? '✓ Set' : 'Set'}</button>
      ${has ? `<button class="btn btn-sm btn-red" onclick="removeApiKeyUI('${_escSettings(p)}')">✕</button>` : ''}
    </div>`;
  }).join('');
}

function setApiKeyUI(provider) {
  const input = document.querySelector(`.api-key-input[data-provider="${provider}"]`);
  const val = input?.value;
  if (!val || val.startsWith('••')) {
    CvcApi.testApiKey(provider)
      .then(r => toast(r.valid ? `${provider}: OK` : `${provider}: ${r.error || 'invalid'}`, r.valid ? 'success' : 'error'))
      .catch(e => toast(e.message, 'error'));
    return;
  }
  CvcApi.setApiKey(provider, val)
    .then(() => {
      toast(`${provider} key saved`, 'success');
      return CvcApi.testApiKey(provider);
    })
    .then(r => {
      if (r && r.valid) toast(`${provider}: OK`, 'success');
      else if (r) toast(`${provider}: ${r.error || 'key may be invalid'}`, 'error');
      loadSettingsData();
    })
    .catch(e => toast(e.message, 'error'));
}
window.setApiKeyUI = setApiKeyUI;

function removeApiKeyUI(provider) {
  CvcApi.removeApiKey(provider)
    .then(() => { toast(`${provider} key removed`, 'success'); loadSettingsData(); })
    .catch(e => toast(e.message, 'error'));
}
window.removeApiKeyUI = removeApiKeyUI;

// ── Hooks ───────────────────────────────────────────
function renderHooks(hooks) {
  const container = document.getElementById('hooks-list');
  if (!container) return;
  const entries = Object.entries(hooks);
  if (!entries.length) {
    container.innerHTML = '<p class="text-muted">No hooks configured.</p>';
    return;
  }
  container.innerHTML = entries.map(([event, cmds]) =>
    cmds.map((cmd, i) =>
      `<div class="hook-row">
        <span class="tag tag-blue">${_escSettings(event)}</span>
        <code>${_escSettings(String(cmd))}</code>
        <button class="btn btn-sm btn-red" onclick="removeHookUI('${_escSettings(event)}', ${i})">✕</button>
      </div>`
    ).join('')
  ).join('');
}

function removeHookUI(event, index) {
  CvcApi.removeHook(event, index)
    .then(() => { toast('Hook removed', 'success'); loadSettingsData(); })
    .catch(e => toast(e.message, 'error'));
}
window.removeHookUI = removeHookUI;

// ── Env Vars ────────────────────────────────────────
function renderEnvVars(env) {
  const container = document.getElementById('env-vars-list');
  if (!container) return;
  const entries = Object.entries(env);
  if (!entries.length) {
    container.innerHTML = '<p class="text-muted">No environment variables configured.</p>';
    return;
  }
  container.innerHTML = `<table class="data-table"><thead><tr><th>Key</th><th>Value</th></tr></thead><tbody>` +
    entries.map(([k, v]) => `<tr><td><code>${_escSettings(k)}</code></td><td>${_escSettings(v)}</td></tr>`).join('') +
    '</tbody></table>';
}

// ── Plugins ─────────────────────────────────────────
function renderPlugins(plugins) {
  const container = document.getElementById('plugins-list');
  if (!container) return;
  const entries = Object.entries(plugins);
  if (!entries.length) {
    container.innerHTML = '<p class="text-muted">No plugins configured.</p>';
    return;
  }
  container.innerHTML = entries.map(([name, enabled]) =>
    `<div class="plugin-row"><label class="toggle-label"><input type="checkbox" ${enabled ? 'checked' : ''} data-plugin="${_escSettings(name)}" class="plugin-toggle" /> ${_escSettings(name)}</label></div>`
  ).join('');
}

// ── Populate form ───────────────────────────────────
function populateSettingsForm(data) {
  const g = data.global || {};
  const p = data.project || {};

  _setVal('setting-provider', g.provider || 'anthropic');
  _setVal('setting-model', g.model || '');
  renderApiKeys(g.api_keys || {});
  _setVal('setting-output-style', p.outputStyle || p.output_style || 'concise');
  _setChecked('setting-always-thinking', p.alwaysThinkingEnabled ?? p.always_thinking_enabled ?? false);
  _setChecked('setting-auto-memory', p.autoMemoryEnabled ?? p.auto_memory_enabled ?? true);
  _setVal('setting-compact-threshold', String(p.autoCompactThreshold ?? p.auto_compact_threshold ?? 50));
  _setVal('setting-plan-display', p.plan_display || 'full');
  _setVal('setting-trust-mode', p.trust_mode || 'balanced');
  _setVal('setting-tools-allow', (p.permissions?.allow || []).join(', '));
  _setVal('setting-tools-deny', (p.permissions?.deny || []).join(', '));
  _setVal('setting-trusted-cmds', (p.trusted_commands || []).join(', '));
  _setVal('setting-blocked-cmds', (p.blocked_commands || []).join(', '));
  renderHooks(p.hooks || {});
  renderEnvVars(p.env || {});
  renderPlugins(p.enabledPlugins ?? p.enabled_plugins ?? {});
}

// ── Save ────────────────────────────────────────────
async function saveSettingsAll() {
  try {
    const provider = document.getElementById('setting-provider')?.value;
    const model = document.getElementById('setting-model')?.value;

    const keyInputs = document.querySelectorAll('.api-key-input');
    for (const input of keyInputs) {
      const prov = input.dataset.provider;
      const val = input.value;
      if (prov && val && !val.startsWith('••')) {
        await CvcApi.setApiKey(prov, val);
      }
    }
    await CvcApi.updateGlobalSettings({ provider, model });

    const projectData = {
      output_style: document.getElementById('setting-output-style')?.value,
      always_thinking_enabled: document.getElementById('setting-always-thinking')?.checked,
      auto_memory_enabled: document.getElementById('setting-auto-memory')?.checked,
      auto_compact_threshold: parseInt(document.getElementById('setting-compact-threshold')?.value || '50'),
      plan_display: document.getElementById('setting-plan-display')?.value,
      trust_mode: document.getElementById('setting-trust-mode')?.value,
      trusted_commands: _parseCSV('setting-trusted-cmds'),
      blocked_commands: _parseCSV('setting-blocked-cmds'),
      permission_allow: _parseCSV('setting-tools-allow'),
      permission_deny: _parseCSV('setting-tools-deny'),
    };
    await CvcApi.updateProjectSettings(projectData);

    _settingsDirty = false;
    const bar = document.getElementById('settings-save-bar');
    if (bar) bar.style.display = 'none';
    toast('Settings saved', 'success');
  } catch (e) {
    toast(e.message, 'error');
  }
}

// ── Main loader ─────────────────────────────────────
async function loadSettingsData() {
  try {
    const [settings, vcs, auditResp] = await Promise.all([
      CvcApi.getSettings().catch(() => ({ global: {}, project: {}, schema: { sections: [] } })),
      CvcApi.getVCSStatus().catch(() => ({ provider: '—', has_repo: false })),
      CvcApi.getAudit().catch(() => ({ entries: [] })),
    ]);

    _settingsCache = settings;
    populateSettingsForm(settings);

    const vcsEl = document.getElementById('settings-vcs');
    if (vcsEl) {
      vcsEl.innerHTML = `<div class="detail-grid">
        <div><span class="label">Provider</span><span class="value">${_escSettings(vcs.provider || '—')}</span></div>
        <div><span class="label">Has Repo</span><span class="value">${vcs.has_repo ? '<span class="tag tag-green">Yes</span>' : '<span class="tag tag-red">No</span>'}</span></div>
        <div><span class="label">Repo Root</span><span class="value code">${_escSettings(vcs.repo_root || '—')}</span></div>
        <div><span class="label">Branch</span><span class="value">${_escSettings(vcs.current_branch || '—')}</span></div>
      </div>`;
    }

    const auditEl = document.getElementById('settings-audit');
    if (auditEl) {
      const auditList = auditResp.entries || (Array.isArray(auditResp) ? auditResp : []);
      if (!auditList.length) {
        auditEl.innerHTML = '<p class="text-muted">No audit entries.</p>';
      } else {
        auditEl.innerHTML = `<table class="data-table"><thead><tr><th>Time</th><th>Action</th><th>Details</th></tr></thead><tbody>` +
          auditList.slice(0, 50).map(e =>
            `<tr><td>${formatDate(e.created_at || e.timestamp)}</td><td><code>${_escSettings(e.event_type || e.action || '')}</code></td><td>${_escSettings(e.action_detail ? JSON.stringify(e.action_detail) : (e.details || ''))}</td></tr>`
          ).join('') + '</tbody></table>';
      }
    }
  } catch { /* ignore */ }
}

// ── Init ────────────────────────────────────────────
function initSettings() {
  setupCollapsible();
  setupSettingsLevelTabs();
  setupSettingsSearch();

  document.getElementById('settings-save-btn')?.addEventListener('click', saveSettingsAll);
  document.getElementById('settings-discard-btn')?.addEventListener('click', () => {
    _settingsDirty = false;
    const bar = document.getElementById('settings-save-bar');
    if (bar) bar.style.display = 'none';
    if (_settingsCache) populateSettingsForm(_settingsCache);
  });

  document.getElementById('hook-add-btn')?.addEventListener('click', async () => {
    const event = document.getElementById('hook-event-select')?.value;
    const command = document.getElementById('hook-command-input')?.value.trim();
    if (!event || !command) return;
    try {
      await CvcApi.addHook(event, command);
      toast('Hook added', 'success');
      document.getElementById('hook-command-input').value = '';
      loadSettingsData();
    } catch (e) { toast(e.message, 'error'); }
  });

  document.getElementById('tab-settings')?.addEventListener('change', markSettingsDirty);
  document.getElementById('tab-settings')?.addEventListener('input', markSettingsDirty);
}
