const MENTION_RE = /@([a-zA-Z0-9._]{1,30})/g;

export function extractMentionUsernames(text: string): string[] {
  const seen = new Set<string>();
  const out: string[] = [];
  for (const match of text.matchAll(MENTION_RE)) {
    const username = (match[1] || "").trim().toLowerCase();
    if (!username || seen.has(username)) continue;
    seen.add(username);
    out.push(username);
  }
  return out;
}

export type ProfileLookupProfile = Record<string, unknown> & {
  username?: string;
  name?: string;
  profile_picture_url?: string;
  is_verified?: boolean;
};

export function parsePlaygroundProfileData(data: string): ProfileLookupProfile | null {
  const trimmed = data.trim();
  if (!trimmed) return null;
  try {
    const parsed = JSON.parse(trimmed) as ProfileLookupProfile;
    return parsed && typeof parsed === "object" ? parsed : null;
  } catch {
    return null;
  }
}

const PROFILE_FIELD_LABELS: Record<string, string> = {
  username: "帳號",
  name: "顯示名稱",
  profile_picture_url: "大頭照",
  biography: "自我介紹",
  follower_count: "粉絲數",
  likes_count: "近 7 天讚",
  quotes_count: "近 7 天引用",
  reposts_count: "近 7 天轉發",
  views_count: "近 7 天瀏覽",
  is_verified: "藍勾認證"
};

export function profileFieldLabel(key: string): string {
  return PROFILE_FIELD_LABELS[key] || key;
}

export function formatProfileFieldValue(key: string, value: unknown): string {
  if (value == null || value === "") return "—";
  if (key === "is_verified") return value === true ? "是" : "否";
  if (key === "profile_picture_url") return String(value);
  if (typeof value === "number") return value.toLocaleString("zh-TW");
  return String(value);
}

export function profileDisplayEntries(profile: ProfileLookupProfile): Array<{ key: string; label: string; value: string }> {
  const skip = new Set(["username", "name", "profile_picture_url", "is_verified"]);
  return Object.entries(profile)
    .filter(([key, value]) => !skip.has(key) && value != null && value !== "")
    .map(([key, value]) => ({
      key,
      label: profileFieldLabel(key),
      value: formatProfileFieldValue(key, value)
    }));
}