import type { AnyLink } from "@/lib/collections";

const COLLECTION_COLORS = [
  "#e45c5c",
  "#e4885c",
  "#d4c24a",
  "#5cb85c",
  "#5ca8e4",
  "#8e5ce4",
  "#e45ca8",
  "#5ce4d4",
];

export function collectionColor(name: string): string {
  let hash = 0;
  for (let i = 0; i < name.length; i++) {
    hash = (hash * 31 + name.charCodeAt(i)) >>> 0;
  }
  return COLLECTION_COLORS[hash % COLLECTION_COLORS.length] as string;
}

export function getDomain(url: string): string {
  try {
    return new URL(url).hostname.replace(/^www\./, "");
  } catch {
    return url;
  }
}

export function getFaviconUrl(url: string): string {
  const domain = getDomain(url);
  return `https://www.google.com/s2/favicons?domain=${domain}&sz=32`;
}

export function getUniqueCollections(links: AnyLink[]): string[] {
  const seen = new Set<string>();
  for (const link of links) {
    const col = link.data.collection;
    if (col) seen.add(col);
  }
  return Array.from(seen).sort();
}

export function getUniqueTags(links: AnyLink[]): string[] {
  const seen = new Set<string>();
  for (const link of links) {
    for (const tag of link.data.tags) {
      seen.add(tag);
    }
  }
  return Array.from(seen).sort();
}

export function filterByCollection(links: AnyLink[], col: string): AnyLink[] {
  return links.filter((l) => l.data.collection === col);
}

export function filterByTag(links: AnyLink[], tag: string): AnyLink[] {
  return links.filter((l) => l.data.tags.includes(tag));
}

export function formatDate(date: Date): string {
  return date.toLocaleDateString("de-DE", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
  });
}
