'use strict';

const { bold } = require('../utils/colors');
const { visibleWidth, truncateVisible, padEndVisible } = require('../utils/text_width');

function renderBox({ title, lines }) {
  const cols = Number(process.stdout.columns) || 80;
  const safeTitle = title ? String(title) : '';
  const safeLines = Array.isArray(lines) ? lines.map((line) => String(line)) : [];
  if (cols < 20) {
    console.log('');
    if (safeTitle) console.log(safeTitle);
    safeLines.forEach((line) => console.log(line));
    console.log('');
    return;
  }
  const contentWidth = Math.max(visibleWidth(safeTitle), ...safeLines.map(visibleWidth));
  const innerWidth = Math.max(10, Math.min(cols - 2, contentWidth + 2));
  const top = `+${'-'.repeat(innerWidth)}+`;
  const maxLine = innerWidth - 2;
  const renderLine = (text) => `| ${padEndVisible(truncateVisible(text, maxLine), maxLine)} |`;
  console.log('');
  console.log(top);
  if (safeTitle) console.log(renderLine(safeTitle));
  safeLines.forEach((line) => console.log(renderLine(line)));
  console.log(top);
  console.log('');
}

function renderBanner({ modelKey, workspace, conversationId }) {
  const title = `>_ Welcome to ${bold('EasyAgent')}`;
  const lines = [
    `model: ${modelKey || ''}`,
    `path: ${workspace || ''}`,
    `conversation: ${conversationId || 'none'}`,
  ];
  renderBox({ title, lines });
}

module.exports = { renderBanner, renderBox };
