import { sendVisitorMessage } from './websocket.js';

const $fps        = document.getElementById('fps');
const $activeJobs = document.getElementById('active-jobs');
const $connStatus = document.getElementById('connection-status');
const $log        = document.getElementById('event-log');

const MAX_LOG = 6;
const logEntries = [];
let uiInitialized = false;

// ── Session-mode send override ────────────────────────────────────────────────
let _sessionSendHandler = null;

export function setSessionSendHandler(fn) {
  _sessionSendHandler = fn;
}

export function setInputBarSessionMode(active, placeholder) {
  const $input = document.getElementById('visitor-input');
  if (!$input) return;
  if (active) {
    $input.classList.add('session-active');
    $input.placeholder = placeholder || 'Ask Timmy (session active)…';
  } else {
    $input.classList.remove('session-active');
    $input.placeholder = 'Say something to Timmy…';
  }
}

export function initUI() {
  if (uiInitialized) return;
  uiInitialized = true;
  initInputBar();
}

function initInputBar() {
  const $input  = document.getElementById('visitor-input');
  const $sendBtn = document.getElementById('send-btn');
  if (!$input || !$sendBtn) return;

  function send() {
    const text = $input.value.trim();
    if (!text) return;
    $input.value = '';
    if (_sessionSendHandler) {
      _sessionSendHandler(text);
    } else {
      sendVisitorMessage(text);
      appendSystemMessage(`you: ${text}`);
    }
  }

  $sendBtn.addEventListener('click', send);
  $input.addEventListener('keydown', e => {
    if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); send(); }
  });
}

export function updateUI({ fps, jobCount, connectionState }) {
  if ($fps) $fps.textContent = `FPS: ${fps}`;
  if ($activeJobs) $activeJobs.textContent = `JOBS: ${jobCount}`;

  if ($connStatus) {
    if (connectionState === 'connected') {
      $connStatus.textContent = '● CONNECTED';
      $connStatus.className   = 'connected';
    } else if (connectionState === 'connecting') {
      $connStatus.textContent = '◌ CONNECTING...';
      $connStatus.className   = '';
    } else {
      $connStatus.textContent = '○ OFFLINE';
      $connStatus.className   = '';
    }
  }
}

export function appendSystemMessage(text) {
  if (!$log) return;
  const el = document.createElement('div');
  el.className = 'log-entry';
  el.textContent = text;
  logEntries.push(el);
  if (logEntries.length > MAX_LOG) {
    const removed = logEntries.shift();
    $log.removeChild(removed);
  }
  $log.appendChild(el);
  $log.scrollTop = $log.scrollHeight;
}

export function appendChatMessage(agentLabel, message, cssColor, agentId) {
  void agentLabel; void cssColor; void agentId;
  appendSystemMessage(message);
}

export function loadChatHistory() { return []; }
export function saveChatHistory() {}
