import { buildProjectGroups } from "./chats-projects.js";

export function filterProjectFolders(projects = [], search = "") {
  const query = search.trim().toLocaleLowerCase();
  if (!query) return projects;
  return projects.filter((project) => project.name.toLocaleLowerCase().includes(query));
}

export function projectPopoverPlacement(rect = {}, viewportHeight = 0) {
  const rowCenter = (Number(rect.top) || 0) + (Number(rect.height) || 0) / 2;
  return rowCenter > (Number(viewportHeight) || 0) / 2 ? "above" : "below";
}

export function recentProjectFolders(threads = [], workspaces = [], hiddenProjects = []) {
  const registeredWorkspaceIds = new Set(workspaces.map((workspace) => workspace.id));
  return buildProjectGroups(threads, workspaces, hiddenProjects)
    .filter((project) => registeredWorkspaceIds.has(project.workspaceId))
    .map((project) => ({ name: project.label, workspaceId: project.workspaceId }));
}

export function upsertProjectFolder(projects = [], project) {
  const name = String(project?.name ?? "");
  const next = projects.filter((item) => item.name.toLocaleLowerCase() !== name.toLocaleLowerCase());
  next.push({ name, workspaceId: project.workspaceId });
  return next.sort((left, right) => left.name.localeCompare(right.name));
}

export function validateProjectName(value) {
  const name = typeof value === "string" ? value.trim() : "";
  const reserved = /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\..*)?$/i;
  const invalid = !name
    || name.length > 80
    || name === "."
    || name === ".."
    || /[<>:"/\\|?*\u0000-\u001f]/.test(name)
    || /[ .]$/.test(name)
    || reserved.test(name);
  return invalid ? { valid: false, message: "Use a simple folder name." } : { valid: true, message: "" };
}

const projectErrorMessages = {
  invalid_project_name: "Use a simple folder name.",
  project_create_failed: "Could not create that project folder.",
  project_not_found: "Project folder not found. Choose a direct child folder under projectsRoot.",
  projects_root_unavailable: "Project folder discovery is unavailable. Set projectsRoot in local config to a parent folder; only direct child folders appear here.",
  workspace_config_write_failed: "Project was found, but local workspace config could not be updated.",
  folder_browse_failed: "Could not open that folder.",
  folder_create_failed: "Could not create that folder.",
  folder_selection_expired: "That folder selection expired. Browse to the folder again.",
  workspace_mismatch: "The new chat opened in a different project. No message was sent.",
  attachment_limit_exceeded: "Add up to 8 images, no more than 8 MB each or 32 MB total."
};

export function projectListErrorMessage(error) {
  if (error?.message === "projects_root_unavailable") return projectErrorMessages.projects_root_unavailable;
  return "Project folder discovery failed.";
}

export function projectOperationError(error) {
  return projectErrorMessages[error?.message] ?? "Project update failed.";
}
