import { ref } from "vue";

/**
 * Company-scoped breadcrumb segments when inside a company route.
 * Consumed by AppBreadcrumb.
 */
export const companyBreadcrumbSegments = ref([]);

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

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

  const base = [
    { label: "Bedrijven", to: "/companies" },
    {
      label: company.name ?? "Bedrijf",
      to: `/companies/${company.id}`,
    },
  ];

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

/**
 * Convenience helpers for common company pages
 */
export function setCompanyGroupsFormBreadcrumb(company, companyId, isEdit) {
  const c = ensureCompany(company, companyId);
  if (!c) {
    companyBreadcrumbSegments.value = [];
    return;
  }
  setCompanyBreadcrumbTrail(c, [
    {
      label: "Groepen",
      to: { name: "company-settings-index", params: { companyId: c.id } },
    },
    { label: isEdit ? "Groep bewerken" : "Nieuwe groep" },
  ]);
}

/**
 * Backwards compatible helper used by existing layout code.
 * Keeps the old [Bedrijven, CompanyName, CurrentPage] behaviour.
 */
export function setCompanyBreadcrumb(company, companyId, currentLabel) {
  const c = ensureCompany(company, companyId);
  if (!c) {
    companyBreadcrumbSegments.value = [];
    return;
  }
  setCompanyBreadcrumbTrail(c, [{ label: currentLabel ?? "Bedrijf" }]);
}

export function clearCompanyBreadcrumb() {
  companyBreadcrumbSegments.value = [];
}
