import { defineBreadcrumb } from "nuxt-schema-org/schema";

interface BreadcrumbItem {
  name: string;
  link?: string;
}

export const useBreadcrumbSchema = (pages: BreadcrumbItem[]) => {
  const { t } = useI18n();
  const localePath = useLocalePath();
  const route = useRoute();
  const config = useRuntimeConfig();

  const siteUrl = config.public.BASE_URL;

  const toAbs = (path: string) => new URL(path, siteUrl).toString();

  const crumbs = [{ name: t("home"), link: "/" }, ...pages].filter(
    (c) => c?.name,
  );

  // Ensure last crumb has a link (current route) if missing/empty
  if (crumbs.length) {
    const last = crumbs[crumbs.length - 1];
    if (!last.link || last.link.trim() === "") last.link = route.path;
  }

  useSchemaOrg([
    defineBreadcrumb({
      itemListElement: crumbs.map((c, index) => ({
        position: index + 1,
        name: c.name,
        item: toAbs(localePath(c.link!)),
      })),
    }),
  ]);
};
