'use strict';
(function() {
  function install(WE, deps) {
    const api = deps.api;
    const esc = deps.esc;
    const safeSetHtml = deps.safeSetHtml;

    WE.renderMcp = function() {
      var body = document.getElementById('walle-body');
      safeSetHtml(body, '<div style="padding:16px;color:var(--fg-dim)">Loading MCP servers...</div>');
      api('/mcp/servers').then(function(data) {
        var servers = data.data || [];
        var meta = data.meta || {};
        var html = '';
        html += '<div style="padding:12px 16px;display:flex;align-items:center;gap:8px;border-bottom:1px solid var(--border,#333)">';
        html += '<h3 style="margin:0;font-size:14px;flex:1">MCP Servers</h3>';
        var connected = servers.filter(function(s) { return s.status === 'connected' || s.status === 'cached'; }).length;
        html += '<span style="font-size:11px;color:var(--fg-dim)">' + connected + '/' + servers.length + ' connected</span>';
        if (meta.last_scan) html += '<span style="font-size:10px;color:var(--fg-dim)">Last scan: ' + esc(new Date(meta.last_scan).toLocaleString()) + '</span>';
        html += '<button class="walle-btn" onclick="WE._scanMcp()">Scan All</button>';
        html += '</div>';

        if (servers.length === 0) {
          html += '<div style="padding:24px;text-align:center;color:var(--fg-dim)">No MCP servers found.<br><span style="font-size:11px">Configure MCP servers in Claude Code (Settings > MCP Servers) and they will appear here.</span></div>';
        } else {
          for (var i = 0; i < servers.length; i++) {
            var s = servers[i];
            var dotColor = '#666';
            var statusLabel = 'disconnected';
            var statusColor = '#666';
            if (s.status === 'connected') { dotColor = '#5c940d'; statusLabel = 'connected'; statusColor = '#5c940d'; }
            else if (s.status === 'cached') { dotColor = '#228be6'; statusLabel = 'cached'; statusColor = '#228be6'; }
            else if (s.status === 'authenticated') { dotColor = '#fab005'; statusLabel = 'authenticated'; statusColor = '#fab005'; }

            html += '<div style="border-bottom:1px solid var(--border,#333);padding:10px 16px;" id="mcp-server-' + esc(s.name) + '">';
            html += '<div style="display:flex;align-items:center;gap:8px;margin-bottom:4px;">';
            html += '<span style="display:inline-block;width:8px;height:8px;border-radius:50%;background:' + dotColor + ';flex-shrink:0"></span>';
            html += '<strong style="font-size:13px;">' + esc(s.name) + '</strong>';
            html += '<span style="font-size:10px;color:var(--fg-dim);background:var(--bg-lighter,#2a2a3e);padding:1px 6px;border-radius:8px;">' + esc(s.type) + '</span>';
            html += '<span style="font-size:10px;color:' + statusColor + '">' + statusLabel + '</span>';
            html += '<span style="flex:1"></span>';
            html += '<span style="font-size:10px;color:var(--fg-dim)">' + s.tool_count + ' tools</span>';
            if (s.status === 'connected' || s.status === 'cached') {
              html += '<button class="walle-btn" style="font-size:10px;padding:2px 8px;" onclick="WE._connectMcp(\'' + esc(s.name) + '\',this)">Refresh</button>';
            } else {
              html += '<button class="walle-btn primary" style="font-size:10px;padding:2px 8px;" onclick="WE._connectMcp(\'' + esc(s.name) + '\',this)">Connect</button>';
            }
            html += '</div>';
            if (s.url) html += '<div style="font-size:10px;color:var(--fg-dim);margin-left:16px;margin-bottom:4px;font-family:monospace;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">' + esc(String(s.url)) + '</div>';
            if (s.tools.length > 0) {
              var showAll = s.tools.length <= 10;
              html += '<div style="margin-left:16px;display:flex;flex-wrap:wrap;gap:4px;">';
              var displayTools = showAll ? s.tools : s.tools.slice(0, 8);
              for (var j = 0; j < displayTools.length; j++) {
                var t = displayTools[j];
                html += '<span title="' + esc(t.description || '') + '" style="font-size:10px;background:var(--bg-lighter,#2a2a3e);padding:2px 6px;border-radius:4px;cursor:default;border:1px solid transparent;" onmouseover="this.style.borderColor=\'var(--accent)\'" onmouseout="this.style.borderColor=\'transparent\'">' + esc(t.name) + '</span>';
              }
              if (!showAll) {
                html += '<span style="font-size:10px;color:var(--fg-dim);padding:2px 6px;cursor:pointer;" onclick="this.parentElement.style.display=\'none\';this.parentElement.nextElementSibling.style.display=\'flex\'">+' + (s.tools.length - 8) + ' more</span>';
              }
              html += '</div>';
              if (!showAll) {
                html += '<div style="margin-left:16px;display:none;flex-wrap:wrap;gap:4px;">';
                for (var k = 0; k < s.tools.length; k++) {
                  var t2 = s.tools[k];
                  html += '<span title="' + esc(t2.description || '') + '" style="font-size:10px;background:var(--bg-lighter,#2a2a3e);padding:2px 6px;border-radius:4px;cursor:default;border:1px solid transparent;" onmouseover="this.style.borderColor=\'var(--accent)\'" onmouseout="this.style.borderColor=\'transparent\'">' + esc(t2.name) + '</span>';
                }
                html += '</div>';
              }
            }
            html += '</div>';
          }
        }
        safeSetHtml(body, html);
      }).catch(function(e) {
        safeSetHtml(body, '<div style="padding:16px;color:var(--red)">Failed to load MCP servers: ' + esc(e.message) + '</div>');
      });
    };

    WE._connectMcp = function(serverName, btnEl) {
      if (btnEl) {
        btnEl.disabled = true;
        btnEl.textContent = 'Connecting...';
      }
      api('/mcp/connect/' + encodeURIComponent(serverName), { method: 'POST' }).then(function(data) {
        if (typeof window.toast === 'function') window.toast(serverName + ' connected - ' + data.tools + ' tools', { type: 'success' });
        setTimeout(function() { WE.renderMcp(); }, 300);
      }).catch(function(e) {
        var msg = e.message || '';
        if (msg.includes('401') || msg.includes('Unauthorized') || msg.includes('auth')) {
          if (btnEl) {
            btnEl.textContent = 'Authenticate';
            btnEl.style.color = '#fab005';
            btnEl.disabled = false;
            btnEl.onclick = function() { WE._authMcp(serverName, btnEl); };
          }
          if (typeof window.toast === 'function') window.toast(serverName + ' needs authentication - click Authenticate to log in.', { type: 'warning' });
        } else {
          if (btnEl) { btnEl.textContent = 'Retry'; btnEl.disabled = false; }
          if (typeof window.toast === 'function') window.toast(serverName + ': ' + msg.slice(0, 100), { type: 'error' });
        }
      });
    };

    WE._authMcp = function(serverName, btnEl) {
      if (btnEl) {
        btnEl.disabled = true;
        btnEl.textContent = 'Opening browser...';
      }
      api('/mcp/auth/' + encodeURIComponent(serverName), { method: 'POST' }).then(function() {
        if (typeof window.toast === 'function') window.toast('Check your browser - log in to ' + serverName, { type: 'info' });
        if (btnEl) btnEl.textContent = 'Waiting for login...';
        var attempts = 0;
        var poll = setInterval(function() {
          attempts++;
          api('/mcp/connect/' + encodeURIComponent(serverName), { method: 'POST' }).then(function(data) {
            clearInterval(poll);
            if (typeof window.toast === 'function') window.toast(serverName + ' connected - ' + data.tools + ' tools!', { type: 'success' });
            setTimeout(function() { WE.renderMcp(); }, 300);
          }).catch(function() {
            if (attempts > 30) {
              clearInterval(poll);
              if (btnEl) { btnEl.textContent = 'Timed out'; btnEl.disabled = false; }
            }
          });
        }, 3000);
      }).catch(function(e) {
        if (btnEl) { btnEl.textContent = 'Auth failed'; btnEl.disabled = false; }
        if (typeof window.toast === 'function') window.toast('Auth failed: ' + (e.message || '').slice(0, 100), { type: 'error' });
      });
    };

    WE._scanMcp = function() {
      api('/mcp/scan', { method: 'POST' }).then(function() {
        if (typeof window.toast === 'function') window.toast('Scanning all MCP servers...', { type: 'info' });
        setTimeout(function() { WE.renderMcp(); }, 8000);
      }).catch(function(e) {
        if (typeof window.toast === 'function') window.toast('Scan failed: ' + e.message, { type: 'error' });
      });
    };
  }

  window.WalleMcp = { install: install };
})();
