// PRE — Argus Companion Widget
(() => {
  const argusReactions = [];
  const MAX_ARGUS_REACTIONS = 30;
  let argusExpanded = false;
  let argusEnabled = true;
  let argusName = 'Argus';

  function initArgus() {
    // Create widget DOM
    const widget = document.createElement('div');
    widget.id = 'argus-widget';
    widget.className = 'argus-widget';
    widget.innerHTML = `
      <div class="argus-panel" id="argus-panel">
        <div class="argus-panel-header">
          <div class="argus-panel-header-left">
            <span id="argus-panel-name">${PRE.escapeHtml(argusName)}</span>
          </div>
          <div class="argus-panel-toggle active" id="argus-toggle" title="Toggle Argus"></div>
        </div>
        <div class="argus-panel-body" id="argus-panel-body">
          <div class="argus-empty">Argus is watching and will share<br>thoughts as you work.</div>
        </div>
      </div>
      <div class="argus-fab" id="argus-fab" title="Argus companion">
        <span>✦</span>
        <div class="argus-badge"></div>
      </div>
    `;
    document.body.appendChild(widget);

    // Load config
    fetch('/api/argus').then(r => r.json()).then(cfg => {
      argusEnabled = cfg.enabled;
      argusName = cfg.name || 'Argus';
      const nameEl = document.getElementById('argus-panel-name');
      if (nameEl) nameEl.textContent = argusName;
      const toggle = document.getElementById('argus-toggle');
      if (toggle) toggle.classList.toggle('active', argusEnabled);
      if (!argusEnabled) widget.style.opacity = '0.5';
    }).catch(() => {});

    // FAB click → toggle panel
    document.getElementById('argus-fab').addEventListener('click', () => {
      argusExpanded = !argusExpanded;
      const panel = document.getElementById('argus-panel');
      panel.classList.toggle('argus-panel--open', argusExpanded);
      // Clear badge
      document.getElementById('argus-fab').classList.remove('argus-fab--active');
      if (argusExpanded) {
        const body = document.getElementById('argus-panel-body');
        body.scrollTop = body.scrollHeight;
      }
    });

    // Toggle switch
    document.getElementById('argus-toggle').addEventListener('click', (e) => {
      e.stopPropagation();
      argusEnabled = !argusEnabled;
      e.currentTarget.classList.toggle('active', argusEnabled);
      widget.style.opacity = argusEnabled ? '1' : '0.5';
      fetch('/api/argus', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ enabled: argusEnabled }),
      }).catch(() => {});
    });
  }

  function renderArgusReactions() {
    const body = document.getElementById('argus-panel-body');
    if (!body) return;
    if (argusReactions.length === 0 && !body.querySelector('.argus-thinking')) {
      body.innerHTML = '<div class="argus-empty">Argus is watching and will share<br>thoughts as you work.</div>';
      return;
    }
    // Preserve thinking indicator if present
    const thinkingEl = body.querySelector('.argus-thinking');

    body.innerHTML = argusReactions.map((r, i) => {
      const time = new Date(r.timestamp).toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' });
      const trigger = r.trigger || '';
      const tool = r.tool ? ` \u00b7 ${r.tool}` : '';
      const boostedClass = r.boosted ? ' argus-reaction--boosted' : '';
      const reactionId = r.id || '';

      // Render reply thread if present
      let replyHtml = '';
      if (r.replies && r.replies.length > 0) {
        replyHtml = r.replies.map(rep =>
          `<div class="argus-reply-thread">
            <div class="argus-reply-user">${PRE.escapeHtml(rep.userReply)}</div>
            <div class="argus-reply-response">${PRE.escapeHtml(rep.content)}</div>
          </div>`
        ).join('');
      }

      return `<div class="argus-reaction${boostedClass}" data-reaction-id="${PRE.escapeHtml(reactionId)}" data-index="${i}">
        <div class="argus-reaction-content">${PRE.escapeHtml(r.content)}</div>
        ${replyHtml}
        <div class="argus-reaction-meta">
          <span>${time}</span>
          <span class="argus-reaction-trigger">${PRE.escapeHtml(trigger)}${PRE.escapeHtml(tool)}</span>
          ${reactionId ? `<button class="argus-reply-btn" data-reaction-id="${PRE.escapeHtml(reactionId)}" title="Reply to this">reply</button>` : ''}
        </div>
      </div>`;
    }).join('');

    // Re-attach thinking indicator if it was present
    if (thinkingEl) body.appendChild(thinkingEl);

    // Attach reply button handlers
    body.querySelectorAll('.argus-reply-btn').forEach(btn => {
      btn.addEventListener('click', (e) => {
        e.stopPropagation();
        const rid = btn.dataset.reactionId;
        const reactionEl = btn.closest('.argus-reaction');
        // Toggle reply input
        let existing = reactionEl.querySelector('.argus-reply-input-wrap');
        if (existing) { existing.remove(); return; }
        // Remove any other open reply inputs
        body.querySelectorAll('.argus-reply-input-wrap').forEach(el => el.remove());
        // Create inline input
        const wrap = document.createElement('div');
        wrap.className = 'argus-reply-input-wrap';
        wrap.innerHTML = `<input type="text" class="argus-reply-input" placeholder="Reply to ${PRE.escapeHtml(argusName)}..." maxlength="300" />`;
        reactionEl.insertBefore(wrap, reactionEl.querySelector('.argus-reaction-meta'));
        const input = wrap.querySelector('input');
        input.focus();
        input.addEventListener('keydown', async (ev) => {
          if (ev.key !== 'Enter' || !input.value.trim()) return;
          const userReply = input.value.trim();
          input.disabled = true;
          input.value = 'thinking...';
          try {
            const res = await fetch('/api/argus/reply', {
              method: 'POST',
              headers: { 'Content-Type': 'application/json' },
              body: JSON.stringify({ reactionId: rid, reply: userReply }),
            });
            const data = await res.json();
            if (data.content) {
              // Find the reaction and add the reply
              const idx = parseInt(reactionEl.dataset.index, 10);
              if (argusReactions[idx]) {
                if (!argusReactions[idx].replies) argusReactions[idx].replies = [];
                argusReactions[idx].replies.push({ userReply, content: data.content });
              }
            }
          } catch {}
          renderArgusReactions();
        });
      });
    });

    body.scrollTop = body.scrollHeight;
  }

  window.Argus = {
    addReaction(msg) {
      // Remove thinking indicator
      this.hideThinking();
      argusReactions.push(msg);
      if (argusReactions.length > MAX_ARGUS_REACTIONS) argusReactions.shift();
      renderArgusReactions();
      // Pulse the FAB if panel is closed
      if (!argusExpanded) {
        document.getElementById('argus-fab')?.classList.add('argus-fab--active');
      }
    },
    addReply(msg) {
      // Find the reaction this reply belongs to and append it
      const reaction = argusReactions.find(r => r.id === msg.reactionId);
      if (reaction) {
        if (!reaction.replies) reaction.replies = [];
        // Only add if not already present (might have been added via fetch response)
        if (!reaction.replies.some(rep => rep.content === msg.content)) {
          reaction.replies.push({ userReply: '', content: msg.content });
        }
        renderArgusReactions();
      }
    },
    showThinking() {
      const body = document.getElementById('argus-panel-body');
      if (!body || body.querySelector('.argus-thinking')) return;
      // Remove empty state if present
      const empty = body.querySelector('.argus-empty');
      if (empty) empty.remove();
      const el = document.createElement('div');
      el.className = 'argus-thinking';
      el.innerHTML = `<span class="argus-thinking-text">${PRE.escapeHtml(argusName)} is thinking</span><span class="argus-thinking-dots"><span>.</span><span>.</span><span>.</span></span>`;
      body.appendChild(el);
      body.scrollTop = body.scrollHeight;
    },
    hideThinking() {
      const el = document.querySelector('.argus-thinking');
      if (el) el.remove();
    },
    clear() {
      argusReactions.length = 0;
      this.hideThinking();
      renderArgusReactions();
      document.getElementById('argus-fab')?.classList.remove('argus-fab--active');
    },
    toggle() {
      document.getElementById('argus-fab')?.click();
    },
    get reactions() { return argusReactions; },
  };

  // Initialize on load
  initArgus();
})();
