'use strict';
// Review Chat Module — AI chat sidebar for Code Review and Transcript panels
// Uses WALL-E chat API with channel "review", SSE streaming, findings/feedback loop
(function() {

var RC = {};
var rcState = {
  sessionId: null,
  projectPath: null,
  branch: null,
  chatSessionId: null,   // "review-<sessionId>"
  messages: [],           // [{role, text, id}]
  findings: [],           // [{id, text, file, summary, severity}]
  isStreaming: false,
  thinkingLogs: [],
  controller: null,
  contextSent: false,
  activePanel: null,      // 'codereview' or 'transcript'
};

var _nextMsgId = 1;
function genMsgId() { return 'rc-' + (_nextMsgId++); }

function getWalleBase() {
  return (typeof WALLE_BASE !== 'undefined' ? WALLE_BASE : '') || '';
}
function getToken() {
  return (window._ctmState && window._ctmState.token) || '';
}

// --- Init / Teardown ---

RC.init = function(sessionId, projectPath, opts) {
  opts = opts || {};
  rcState.sessionId = sessionId;
  rcState.projectPath = projectPath;
  rcState.branch = opts.branch || '';
  rcState.chatSessionId = 'review-' + sessionId;
  rcState.messages = [];
  rcState.findings = [];
  rcState.isStreaming = false;
  rcState.thinkingLogs = [];
  rcState.contextSent = false;
  rcState.activePanel = opts.panel || 'codereview';
  RC.render();  // Show input immediately, don't wait for async history load
  RC.loadHistory();
};

RC.destroy = function() {
  if (rcState.controller) {
    rcState.controller.abort();
    rcState.controller = null;
  }
  rcState.isStreaming = false;
};

// --- Load chat history ---

RC.loadHistory = function() {
  var token = getToken();
  var base = getWalleBase();
  fetch(base + '/api/wall-e/chat/history?session_id=' + encodeURIComponent(rcState.chatSessionId) + '&limit=50&token=' + token)
    .then(function(r) { return r.json(); })
    .then(function(json) {
      if (json.data && json.data.length > 0) {
        rcState.messages = json.data.map(function(m) {
          return { role: m.role, text: m.content, id: genMsgId() };
        });
      }
      RC.render();
    })
    .catch(function() {
      // Render even on error so the input field is visible
      RC.render();
    });
};

// --- Send message ---

RC.sendMessage = function(text) {
  if (!text || !text.trim() || rcState.isStreaming) return;
  text = text.trim();

  rcState.messages.push({ role: 'user', text: text, id: genMsgId() });
  RC.render();
  RC._scrollToBottom();

  var context = null;
  if (!rcState.contextSent) {
    context = RC._gatherContext();
    rcState.contextSent = true;
  }

  rcState.isStreaming = true;
  rcState.thinkingLogs = [];
  rcState.controller = new AbortController();
  RC.render();

  var body = { message: text, channel: 'review', session_id: rcState.chatSessionId };
  if (context) body.context = context;

  var token = getToken();
  var base = getWalleBase();

  fetch(base + '/api/wall-e/chat?stream=1&token=' + token, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json', 'Accept': 'text/event-stream' },
    body: JSON.stringify(body),
    signal: rcState.controller.signal,
  }).then(function(response) {
    var reader = response.body.getReader();
    var decoder = new TextDecoder();
    var buffer = '';
    function readChunk() {
      reader.read().then(function(result) {
        if (result.done) { RC._finishStream(null); return; }
        buffer += decoder.decode(result.value, { stream: true });
        var lines = buffer.split('\n');
        buffer = lines.pop();
        for (var i = 0; i < lines.length; i++) {
          if (lines[i].startsWith('data: ')) {
            try {
              var event = JSON.parse(lines[i].slice(6));
              if (event.type === 'done') {
                RC._finishStream(event.reply || 'No response');
                reader.cancel();
                return;
              } else if (event.type === 'error') {
                RC._finishStream('Error: ' + (event.error || 'Unknown'));
                reader.cancel();
                return;
              } else {
                RC._handleProgress(event);
              }
            } catch (e) { /* ignore */ }
          }
        }
        readChunk();
      }).catch(function(err) {
        if (err.name !== 'AbortError') RC._finishStream('Error: ' + err.message);
      });
    }
    readChunk();
  }).catch(function(err) {
    rcState.isStreaming = false;
    rcState.controller = null;
    if (err.name !== 'AbortError') {
      rcState.messages.push({ role: 'assistant', text: 'Error: ' + err.message, id: genMsgId() });
    }
    RC.render();
  });
};

RC._handleProgress = function(event) {
  if (event.type === 'tool_call') {
    var icon = event.tool === 'read_project_file' ? '\uD83D\uDCC4'
      : event.tool === 'search_project' ? '\uD83D\uDD0D'
      : event.tool === 'think' ? '\uD83E\uDDE0'
      : event.tool === 'search_memories' ? '\uD83D\uDD0D'
      : '\uD83D\uDD27';
    rcState.thinkingLogs.push({ icon: icon, text: event.summary || event.tool });
  } else if (event.type === 'tool_result' || event.type === 'tool_done') {
    rcState.thinkingLogs.push({ icon: '\u2705', text: event.summary || 'Done' });
  }
  RC.render();
  RC._scrollToBottom();
};

RC._finishStream = function(reply) {
  rcState.isStreaming = false;
  rcState.controller = null;
  rcState.thinkingLogs = [];
  if (reply) {
    rcState.messages.push({ role: 'assistant', text: reply, id: genMsgId() });
  }
  RC.render();
  RC._scrollToBottom();
};

RC.cancel = function() {
  if (rcState.controller) { rcState.controller.abort(); rcState.controller = null; }
  rcState.isStreaming = false;
  rcState.thinkingLogs = [];
  RC.render();
};

// --- Context gathering ---

RC._gatherContext = function() {
  var ctx = {};
  if (rcState.projectPath) ctx.projectPath = rcState.projectPath;
  if (rcState.branch) ctx.branch = rcState.branch;
  if (typeof CR !== 'undefined' && CR._getState) {
    var crS = CR._getState();
    if (crS && crS.files && crS.files.length > 0) {
      ctx.changedFiles = crS.files.map(function(f) {
        return f.path + ' (+' + (f.additions || 0) + '/-' + (f.deletions || 0) + ')';
      }).join(', ');
    }
  }
  return ctx;
};

// --- Findings ---

RC.pinFinding = function(msgId) {
  var msg = null;
  for (var i = 0; i < rcState.messages.length; i++) {
    if (rcState.messages[i].id === msgId) { msg = rcState.messages[i]; break; }
  }
  if (!msg || msg.role !== 'assistant') return;
  for (var j = 0; j < rcState.findings.length; j++) {
    if (rcState.findings[j].id === msgId) return;
  }
  var fileMatch = msg.text.match(/`([^`]+\.[a-z]+)`/);
  var summary = msg.text.replace(/[#*`]/g, '').slice(0, 80);
  rcState.findings.push({ id: msgId, text: msg.text, file: fileMatch ? fileMatch[1] : '', summary: summary, severity: 'suggestion' });
  RC.render();
};

RC.unpinFinding = function(msgId) {
  rcState.findings = rcState.findings.filter(function(f) { return f.id !== msgId; });
  RC.render();
};

RC.sendFindings = function() {
  if (rcState.findings.length === 0) return;
  var sessionId = rcState.sessionId;
  if (!sessionId) return;
  var prompt = '## Code Review Findings\n\n';
  rcState.findings.forEach(function(f, i) {
    prompt += '### Finding ' + (i + 1);
    if (f.file) prompt += ' (' + f.file + ')';
    prompt += '\n' + f.text + '\n\n';
  });
  prompt += '\nPlease address the findings above.';
  if (typeof window.send === 'function') {
    window.send({ type: 'input', id: sessionId, data: prompt });
    setTimeout(function() { window.send({ type: 'input', id: sessionId, data: '\r' }); }, 100);
    if (typeof window.clearWaitingState === 'function') window.clearWaitingState(sessionId);
    if (typeof window.toast === 'function') window.toast('Sent ' + rcState.findings.length + ' finding(s) to session', { type: 'success' });
    rcState.findings = [];
    RC.render();
  }
};

// --- Rendering (safe DOM construction) ---

RC.render = function() {
  var sidebarId = rcState.activePanel === 'transcript' ? 'review-chat-sidebar' : 'cr-chat-sidebar';
  var sidebar = document.getElementById(sidebarId);
  if (!sidebar) return;

  // Clear and rebuild DOM safely
  sidebar.textContent = '';

  // Messages area
  var messagesDiv = document.createElement('div');
  messagesDiv.className = 'rc-messages';
  messagesDiv.id = 'rc-messages';

  if (rcState.messages.length === 0 && !rcState.isStreaming) {
    var empty = document.createElement('div');
    empty.className = 'rc-empty';
    empty.textContent = 'Ask questions about the code changes, or use a quick action below.';
    messagesDiv.appendChild(empty);
  }

  for (var i = 0; i < rcState.messages.length; i++) {
    var m = rcState.messages[i];
    messagesDiv.appendChild(RC._buildMsgEl(m));
  }

  // Thinking state
  if (rcState.isStreaming) {
    var thinkEl = document.createElement('div');
    thinkEl.className = 'rc-msg rc-msg-assistant rc-thinking';
    var dots = document.createElement('div');
    dots.className = 'rc-thinking-dots';
    dots.appendChild(document.createElement('span'));
    dots.appendChild(document.createElement('span'));
    dots.appendChild(document.createElement('span'));
    thinkEl.appendChild(dots);
    for (var j = 0; j < rcState.thinkingLogs.length; j++) {
      var logEl = document.createElement('div');
      logEl.className = 'rc-thinking-log';
      logEl.textContent = rcState.thinkingLogs[j].icon + ' ' + rcState.thinkingLogs[j].text;
      thinkEl.appendChild(logEl);
    }
    messagesDiv.appendChild(thinkEl);
  }

  sidebar.appendChild(messagesDiv);

  // Quick actions
  var quickDiv = document.createElement('div');
  quickDiv.className = 'rc-quick-actions';
  var quickActions = RC._getQuickActions();
  for (var k = 0; k < quickActions.length; k++) {
    (function(qa) {
      var btn = document.createElement('button');
      btn.className = 'rc-quick-btn';
      btn.textContent = qa.label;
      btn.onclick = function() { RC.sendMessage(qa.prompt); };
      quickDiv.appendChild(btn);
    })(quickActions[k]);
  }
  sidebar.appendChild(quickDiv);

  // Findings list
  if (rcState.findings.length > 0) {
    var findingsDiv = document.createElement('div');
    findingsDiv.className = 'rc-findings';

    var header = document.createElement('div');
    header.className = 'rc-findings-header';
    header.textContent = 'Findings (' + rcState.findings.length + ')';
    findingsDiv.appendChild(header);

    for (var l = 0; l < rcState.findings.length; l++) {
      (function(f) {
        var item = document.createElement('div');
        item.className = 'rc-finding-item';
        var summary = document.createElement('span');
        summary.className = 'rc-finding-summary';
        summary.textContent = f.summary;
        item.appendChild(summary);
        if (f.file) {
          var file = document.createElement('span');
          file.className = 'rc-finding-file';
          file.textContent = f.file;
          item.appendChild(file);
        }
        var removeBtn = document.createElement('button');
        removeBtn.className = 'rc-finding-remove';
        removeBtn.textContent = '\u00D7';
        removeBtn.onclick = function() { RC.unpinFinding(f.id); };
        item.appendChild(removeBtn);
        findingsDiv.appendChild(item);
      })(rcState.findings[l]);
    }

    var sendBtn = document.createElement('button');
    sendBtn.className = 'rc-send-findings-btn';
    sendBtn.textContent = 'Send All Findings \u2192';
    sendBtn.onclick = RC.sendFindings;
    findingsDiv.appendChild(sendBtn);

    sidebar.appendChild(findingsDiv);
  }

  // Input row
  var inputRow = document.createElement('div');
  inputRow.className = 'rc-input-row';
  var textarea = document.createElement('textarea');
  textarea.className = 'rc-input';
  textarea.id = 'rc-input';
  textarea.placeholder = 'Ask about the code...';
  textarea.rows = 2;
  textarea.disabled = rcState.isStreaming;
  textarea.onkeydown = function(e) {
    if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); RC._sendFromInput(); }
  };
  inputRow.appendChild(textarea);

  var actionBtn = document.createElement('button');
  if (rcState.isStreaming) {
    actionBtn.className = 'rc-send-btn rc-cancel-btn';
    actionBtn.title = 'Cancel';
    actionBtn.textContent = '\u25A0';
    actionBtn.onclick = RC.cancel;
  } else {
    actionBtn.className = 'rc-send-btn';
    actionBtn.title = 'Send';
    actionBtn.textContent = '\u2191';
    actionBtn.onclick = RC._sendFromInput;
  }
  inputRow.appendChild(actionBtn);
  sidebar.appendChild(inputRow);
};

RC._buildMsgEl = function(m) {
  var div = document.createElement('div');
  div.className = 'rc-msg ' + (m.role === 'user' ? 'rc-msg-user' : 'rc-msg-assistant');
  div.setAttribute('data-msg-id', m.id);

  var textDiv = document.createElement('div');
  textDiv.className = 'rc-msg-text';
  if (m.role === 'assistant') {
    // Render markdown and sanitize with DOMPurify
    var html = RC._renderMarkdown(m.text);
    if (typeof DOMPurify !== 'undefined') html = DOMPurify.sanitize(html);
    textDiv.innerHTML = html;
  } else {
    textDiv.textContent = m.text;
  }
  div.appendChild(textDiv);

  // Action buttons for assistant messages
  if (m.role === 'assistant') {
    var actions = document.createElement('div');
    actions.className = 'rc-msg-actions';

    var copyBtn = document.createElement('button');
    copyBtn.className = 'rc-action-btn';
    copyBtn.textContent = 'Copy';
    copyBtn.onclick = function() { RC.copyMessage(m.id); };
    actions.appendChild(copyBtn);

    var isPinned = false;
    for (var i = 0; i < rcState.findings.length; i++) {
      if (rcState.findings[i].id === m.id) { isPinned = true; break; }
    }
    var pinBtn = document.createElement('button');
    pinBtn.className = 'rc-action-btn' + (isPinned ? ' pinned' : '');
    pinBtn.textContent = isPinned ? '\uD83D\uDCCC Pinned' : '\uD83D\uDCCC Pin';
    pinBtn.onclick = function() { isPinned ? RC.unpinFinding(m.id) : RC.pinFinding(m.id); };
    actions.appendChild(pinBtn);

    div.appendChild(actions);
  }
  return div;
};

RC._getQuickActions = function() {
  if (rcState.activePanel === 'transcript') {
    return [
      { label: 'Summarize', prompt: 'Summarize what this session accomplished, what changed and why.' },
      { label: 'Key Decisions', prompt: 'What were the key decisions made in this session?' },
      { label: 'What Changed', prompt: 'What files and functionality changed in this session?' },
      { label: 'Next Steps', prompt: 'What are the logical next steps after this session?' },
      { label: 'TODOs', prompt: 'Extract any TODOs, FIXMEs, or action items from this session.' },
    ];
  }
  return [
    { label: 'Summarize', prompt: 'Summarize what this session accomplished, what changed and why.' },
    { label: 'Find Bugs', prompt: 'Review the code changes for potential bugs, edge cases, and error handling issues.' },
    { label: 'Security', prompt: 'Check the changes for security vulnerabilities.' },
    { label: 'Tests', prompt: 'Evaluate test coverage. What is missing? What edge cases are not tested?' },
    { label: 'Explain', prompt: 'Explain the architecture and design decisions in these changes.' },
    { label: 'Perf', prompt: 'Review for performance issues (N+1 queries, memory leaks, unnecessary work).' },
  ];
};

RC._sendFromInput = function() {
  var input = document.getElementById('rc-input');
  if (!input) return;
  var text = input.value;
  if (!text.trim()) return;
  RC.sendMessage(text);
};

RC._scrollToBottom = function() {
  var el = document.getElementById('rc-messages');
  if (el) el.scrollTop = el.scrollHeight;
};

RC.copyMessage = function(msgId) {
  var msg = null;
  for (var i = 0; i < rcState.messages.length; i++) {
    if (rcState.messages[i].id === msgId) { msg = rcState.messages[i]; break; }
  }
  if (msg) {
    navigator.clipboard.writeText(msg.text).then(function() {
      if (typeof window.toast === 'function') window.toast('Copied', { type: 'success', duration: 1500 });
    });
  }
};

// Lightweight markdown renderer (reuse from walle.js if available)
RC._renderMarkdown = function(s) {
  if (!s) return '';
  if (typeof window.renderMarkdown === 'function') return window.renderMarkdown(s);
  // Minimal fallback
  var str = s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
  str = str.replace(/```(\w*)\n?([\s\S]*?)```/g, function(_, lang, code) {
    return '<pre class="rc-code-block"><code>' + code.replace(/\n$/, '') + '</code></pre>';
  });
  str = str.replace(/`([^`]+)`/g, '<code class="rc-inline-code">$1</code>');
  str = str.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>');
  str = str.replace(/^- (.+)$/gm, '<li>$1</li>');
  str = str.replace(/((?:<li>[\s\S]*?<\/li>\n?)+)/g, '<ul>$1</ul>');
  str = str.replace(/\n/g, '<br>');
  return str;
};

RC.toggle = function(panel) {
  var sidebarId = panel === 'transcript' ? 'review-chat-sidebar' : 'cr-chat-sidebar';
  var sidebar = document.getElementById(sidebarId);
  if (!sidebar) return;
  sidebar.classList.toggle('rc-collapsed');
};

// Expose state for context gathering by CR module
RC._getState = function() { return rcState; };

window.RC = RC;
})();
