import color from "picocolors";
import boxen from "boxen";
import { gridSelect } from "./grid.js";
import { getTools } from "./plugins/index.js";

let poemConfig = {
  lines: ["你我皆牛马", "生在人世间", "终日赶波涛", "一刻不得闲"],
  perLine: 2,
  padding: { top: 2, bottom: 2, left: 6, right: 6 },
  borderStyle: "double",
  borderColor: "cyan",
};

let updateInfo = null;

export function setPoem(lines, perLine = 2) {
  poemConfig.lines = lines;
  poemConfig.perLine = perLine;
}

export function setPoemStyle(style) {
  Object.assign(poemConfig, style);
}

export function setUpdateInfo(info) {
  updateInfo = info;
}

function renderPoem() {
  const merged = [];
  for (let i = 0; i < poemConfig.lines.length; i += poemConfig.perLine) {
    merged.push(poemConfig.lines.slice(i, i + poemConfig.perLine).join(" | "));
  }
  return boxen(color.yellow(merged.join("\n")), {
    padding: poemConfig.padding,
    borderStyle: poemConfig.borderStyle,
    borderColor: poemConfig.borderColor,
    textAlignment: "center",
    float: "center",
  });
}

function renderUpdateInfo(selected) {
  if (!updateInfo) return "";
  const btn = selected ? color.cyan("[ 立即更新 ]") : color.white("  立即更新  ");
  const msg = `📦 发现新版本 ${color.red(updateInfo.current)} → ${color.green(updateInfo.latest)}  ${btn}`;
  return (
    "\n" +
    boxen(color.yellow(msg), {
      padding: { top: 0, bottom: 0, left: 2, right: 2 },
      borderStyle: "round",
      borderColor: "green",
      textAlignment: "center",
      float: "center",
    })
  );
}

function renderHeader(onUpdate) {
  return renderPoem() + renderUpdateInfo(onUpdate);
}

export async function showMainMenu() {
  const tools = getTools();

  return gridSelect({
    items: tools,
    cols: 3,
    colWidth: 24,
    renderHeader,
    updateInfo,
    instructions: "←→ 选择 | Enter 确认 | Esc 退出",
    mapper: (item, isUpdate) => (isUpdate ? { isUpdate: true } : item),
    showUpdateButton: !!updateInfo,
  });
}

export { poemConfig };
