export function parseMatchTags(raw: string | null | undefined): string[] {
  if (!raw?.trim()) return [];
  try {
    const parsed = JSON.parse(raw) as unknown;
    if (!Array.isArray(parsed)) return [];
    return parsed
      .map((t) => (typeof t === "string" ? t.trim() : ""))
      .filter(Boolean);
  } catch {
    return raw
      .split(/[,，、\n]/)
      .map((t) => t.trim())
      .filter(Boolean);
  }
}

export function serializeMatchTags(tags: string[]): string | null {
  const unique = [...new Set(tags.map((t) => t.trim()).filter(Boolean))];
  return unique.length > 0 ? JSON.stringify(unique) : null;
}

export function formatMatchTagsInput(tags: string[]): string {
  return tags.join("、");
}

export function parseMatchTagsInput(input: string): string[] {
  return input
    .split(/[,，、\n]/)
    .map((t) => t.trim())
    .filter(Boolean);
}

/** 依海巡標籤與產品 matchTags 計分，分數越高越適合推薦。 */
export function scoreProductForTag(
  searchTag: string | null | undefined,
  matchTags: string[]
): number {
  const tag = (searchTag ?? "").trim().toLowerCase();
  if (!tag || matchTags.length === 0) return 0;

  let best = 0;
  for (const raw of matchTags) {
    const candidate = raw.trim().toLowerCase();
    if (!candidate) continue;
    if (tag === candidate) best = Math.max(best, 100);
    else if (tag.includes(candidate) || candidate.includes(tag)) best = Math.max(best, 70);
    else {
      const tagWords = tag.split(/\s+/);
      const candWords = candidate.split(/\s+/);
      const overlap = tagWords.filter((w) => candWords.some((c) => c.includes(w) || w.includes(c)));
      if (overlap.length > 0) best = Math.max(best, 40 + overlap.length * 10);
    }
  }
  return best;
}