// PRE — RAG Panel
// Extracted from app.js: openRagPanel(), renderRagPanel(), window.RAG
(() => {
  async function openRagPanel() {
    const content = PRE.openPanel('RAG Indexes');
    try {
      const res = await fetch('/api/rag');
      const data = await res.json();
      renderRagPanel(content, data.text);
    } catch {
      content.innerHTML = '<p style="color:var(--danger)">Failed to load RAG indexes</p>';
    }
  }

  function renderRagPanel(container, ragText) {
    let html = '<div class="settings-section">';
    html += '<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px">';
    html += '<div class="settings-section-title" style="margin:0">Document Indexes</div>';
    html += '<button class="btn btn-primary btn-sm" onclick="window.RAG.showIndex()">+ Index Directory</button>';
    html += '</div>';

    // Parse the text output to display indexes
    if (ragText.includes('No indexes')) {
      html += '<p style="color:var(--text-muted);font-size:0.85rem">No RAG indexes yet. Index a directory to enable semantic search over your documents.</p>';
    } else {
      // Display the raw formatted text from the tool
      html += `<div style="font-size:0.85rem;white-space:pre-wrap;line-height:1.6;padding:12px;background:var(--surface-2, var(--surface));border-radius:6px;border:1px solid var(--border)">${PRE.escapeHtml(ragText)}</div>`;
    }

    // Search form
    html += `<div style="margin-top:16px">
      <div class="settings-section-title">Semantic Search</div>
      <div style="display:flex;gap:8px">
        <input id="rag-search-query" type="text" placeholder="Search your indexed documents..." style="flex:1;padding:7px 10px;background:var(--surface);border:1px solid var(--border);border-radius:6px;color:var(--text);font-size:0.85rem" onkeydown="if(event.key==='Enter')window.RAG.search()">
        <input id="rag-search-index" type="text" placeholder="Index name (optional)" style="width:160px;padding:7px 10px;background:var(--surface);border:1px solid var(--border);border-radius:6px;color:var(--text);font-size:0.85rem">
        <button class="btn btn-primary btn-sm" onclick="window.RAG.search()">Search</button>
      </div>
      <div id="rag-search-results" style="margin-top:10px"></div>
    </div>`;

    // Index form
    html += `<div id="rag-index-form" style="display:none;margin-top:16px">
      <div class="settings-section-title">Index a Directory</div>
      <div style="display:flex;flex-direction:column;gap:10px">
        <div>
          <label style="font-size:0.75rem;color:var(--text-muted);display:block;margin-bottom:4px">Directory path</label>
          <input id="rag-index-path" type="text" placeholder="/Users/you/project" style="width:100%;padding:7px 10px;background:var(--surface);border:1px solid var(--border);border-radius:6px;color:var(--text);font-size:0.85rem">
        </div>
        <div>
          <label style="font-size:0.75rem;color:var(--text-muted);display:block;margin-bottom:4px">Index name (optional — defaults to directory name)</label>
          <input id="rag-index-name" type="text" placeholder="my-project" style="width:100%;padding:7px 10px;background:var(--surface);border:1px solid var(--border);border-radius:6px;color:var(--text);font-size:0.85rem">
        </div>
        <div style="display:flex;gap:8px">
          <button class="btn btn-primary btn-sm" onclick="window.RAG.doIndex()">Index</button>
          <button class="btn btn-ghost btn-sm" onclick="window.RAG.hideIndex()">Cancel</button>
        </div>
        <div id="rag-index-status" style="font-size:0.82rem"></div>
      </div>
    </div>`;

    // Delete section
    html += `<div style="margin-top:16px">
      <div class="settings-section-title">Manage</div>
      <div style="display:flex;gap:8px;align-items:center">
        <input id="rag-delete-name" type="text" placeholder="Index name to delete" style="flex:1;padding:7px 10px;background:var(--surface);border:1px solid var(--border);border-radius:6px;color:var(--text);font-size:0.85rem">
        <button class="btn btn-ghost btn-sm" onclick="window.RAG.del()" style="color:var(--danger)">Delete</button>
      </div>
    </div>`;

    html += '</div>';
    container.innerHTML = html;
  }

  // Bind sidebar button
  const btn = document.getElementById('rag-btn');
  if (btn) btn.addEventListener('click', openRagPanel);

  window.RAG = {
    showIndex() {
      const form = document.getElementById('rag-index-form');
      if (form) form.style.display = 'block';
    },
    hideIndex() {
      const form = document.getElementById('rag-index-form');
      if (form) form.style.display = 'none';
    },
    async doIndex() {
      const dirPath = document.getElementById('rag-index-path')?.value.trim();
      const indexName = document.getElementById('rag-index-name')?.value.trim();
      const statusEl = document.getElementById('rag-index-status');
      if (!dirPath) return alert('Directory path is required.');
      if (statusEl) statusEl.innerHTML = '<span style="color:var(--primary)">Indexing... this may take a moment.</span>';
      try {
        const body = { path: dirPath };
        if (indexName) body.index_name = indexName;
        const res = await fetch('/api/rag/index', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(body),
        });
        const data = await res.json();
        if (statusEl) statusEl.innerHTML = `<div style="white-space:pre-wrap;padding:8px;background:var(--surface-2, var(--surface));border-radius:6px;border:1px solid var(--border);margin-top:8px">${PRE.escapeHtml(data.text)}</div>`;
        // Refresh the index list after a short delay
        setTimeout(() => openRagPanel(), 2000);
      } catch (e) {
        if (statusEl) statusEl.innerHTML = `<span style="color:var(--danger)">Error: ${e.message}</span>`;
      }
    },
    async search() {
      const query = document.getElementById('rag-search-query')?.value.trim();
      const indexName = document.getElementById('rag-search-index')?.value.trim();
      const resultsEl = document.getElementById('rag-search-results');
      if (!query) return;
      if (resultsEl) resultsEl.innerHTML = '<span style="color:var(--text-muted);font-size:0.82rem">Searching...</span>';
      try {
        const body = { query };
        if (indexName) body.index_name = indexName;
        const res = await fetch('/api/rag/search', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(body),
        });
        const data = await res.json();
        if (resultsEl) resultsEl.innerHTML = `<div style="white-space:pre-wrap;font-size:0.82rem;padding:10px;background:var(--surface-2, var(--surface));border-radius:6px;border:1px solid var(--border);max-height:400px;overflow-y:auto">${PRE.escapeHtml(data.text)}</div>`;
      } catch (e) {
        if (resultsEl) resultsEl.innerHTML = `<span style="color:var(--danger);font-size:0.82rem">Error: ${e.message}</span>`;
      }
    },
    async del() {
      const name = document.getElementById('rag-delete-name')?.value.trim();
      if (!name) return alert('Enter an index name to delete.');
      if (!confirm(`Delete RAG index "${name}"? This cannot be undone.`)) return;
      try {
        await fetch(`/api/rag/${encodeURIComponent(name)}`, { method: 'DELETE' });
        openRagPanel();
      } catch {}
    },
  };
})();
