import { ref } from "vue";

export const projectBreadcrumbSegments = ref([]);

function ensureCompany(company, companyId) {
  if (company && company.id) return company;
  if (!companyId) return null;
  return { id: companyId, name: null };
}

function ensureProject(project, projectId) {
  if (project && project.id) return project;
  if (!projectId) return null;
  return { id: projectId, name: null };
}

/**
 * Generic helper: set full breadcrumb trail for a project-scoped page.
 *
 * @param {{ id: string|number, name?: string }|null} company
 * @param {{ id: string|number, name?: string }|null} project
 * @param {{ label: string, to?: any }[]} items - extra segments after the project item
 */
export function setProjectBreadcrumbTrail(company, project, items = []) {
  if (!company || !company.id || !project || !project.id) {
    projectBreadcrumbSegments.value = [];
    return;
  }

  const base = [
    { label: "Projecten", to: "/projects" },
    {
      label: company.name ?? "Bedrijf",
      to: `/companies/${company.id}/projects`,
    },
    {
      label: project.name ?? "Project",
      to: `/companies/${company.id}/projects/${project.id}/dashboard`,
    },
  ];

  projectBreadcrumbSegments.value = [...base, ...items];
}

/**
 * Convenience helpers for common project pages
 */
export function setProjectGroupsIndexBreadcrumb(company, project) {
  const c = ensureCompany(company, company?.id);
  const p = ensureProject(project, project?.id);
  setProjectBreadcrumbTrail(c, p, [{ label: "Groepen" }]);
}

export function setProjectGroupsFormBreadcrumb(
  company,
  project,
  isEdit,
  params,
) {
  const c = ensureCompany(company, company?.id);
  const p = ensureProject(project, project?.id);
  setProjectBreadcrumbTrail(c, p, [
    {
      label: "Groepen",
      to: { name: "project-settings-groups", params },
    },
    { label: isEdit ? "Groep bewerken" : "Nieuwe groep" },
  ]);
}

export function setProjectGroupsAddUserBreadcrumb(company, project, params) {
  const c = ensureCompany(company, company?.id);
  const p = ensureProject(project, project?.id);
  setProjectBreadcrumbTrail(c, p, [
    {
      label: "Groepen",
      to: { name: "project-settings-groups", params },
    },
    { label: "Gebruiker toevoegen" },
  ]);
}

/**
 * Backwards compatible helper used by older code that expects a single current label.
 * Keeps the old [Projecten, Bedrijf, Project, CurrentPage] behaviour.
 */
export function setProjectBreadcrumb(company, project, currentLabel) {
  const c = ensureCompany(company, company?.id);
  const p = ensureProject(project, project?.id);
  if (!c || !p) {
    projectBreadcrumbSegments.value = [];
    return;
  }
  setProjectBreadcrumbTrail(c, p, [{ label: currentLabel ?? "Project" }]);
}

export function clearProjectBreadcrumb() {
  projectBreadcrumbSegments.value = [];
}
