import color from "picocolors";
import boxen from "boxen";
import figlet from "figlet";
import { gridSelect } from "./grid.js";

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

let titleConfig = {
  text: "Zguiy Tool Box",
  font: "Standard",
  color: "magenta",
};

const tools = [
  { name: "格式转换", desc: "支持多种模型格式转换", module: "./lib/convert/index.js" },
  { name: "KTX2 纹理压缩", desc: "图片转KTX2格式", module: "./lib/ktx2/index.js" },
  { name: "glTF扩展", desc: "添加KHR_texture_basisu", module: "./lib/gltf/index.js" },
  { name: "模型压缩", desc: "压缩glTF/GLB模型", module: "./lib/model/index.js" },
  { name: "图片批量处理", desc: "裁剪/缩放/转换", module: "./lib/image/index.js" },
  { name: "Sprite图集", desc: "合并精灵图集", module: "./lib/sprite/index.js" },
  { name: "LOD生成器", desc: "生成多级细节", module: "./lib/lod/index.js" },
  { name: "音频压缩", desc: "压缩音频文件", module: "./lib/audio/index.js" },
  { name: "项目脚手架", desc: "快速创建项目模板", module: "./lib/scaffold/index.js" },
];

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

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

export function setTitle(text, font = "Standard", titleColor = "magenta") {
  titleConfig.text = text;
  titleConfig.font = font;
  titleConfig.color = titleColor;
}

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 renderTitle() {
  const art = figlet.textSync(titleConfig.text, { font: titleConfig.font });
  const termWidth = process.stdout.columns || 80;
  return art.split("\n").map(line => {
    const pad = Math.max(0, Math.floor((termWidth - line.length) / 2));
    return " ".repeat(pad) + color[titleConfig.color](line);
  }).join("\n");
}

function renderHeader() {
  return renderPoem() + "\n\n" + renderTitle();
}

export async function showMainMenu() {
  return gridSelect({
    items: tools,
    cols: 3,
    colWidth: 24,
    renderHeader: renderHeader,
  });
}

export { tools, poemConfig, titleConfig };
