import type { OwnPost } from "../../domain/types";
import { useI18n } from "../../i18n/I18nContext";

type Props = {
  post: OwnPost;
  /** compact = 一排 badge；detail = 網格全欄位 */
  variant?: "compact" | "detail";
};

function n(v: number | undefined | null): number {
  return typeof v === "number" && !Number.isNaN(v) ? v : 0;
}

/** Threads API 可對齊的成效列：讚／回／轉發／引用／瀏覽／分享 */
export function PostMetrics({ post, variant = "compact" }: Props) {
  const { t, locale } = useI18n();
  const dateLocale = locale === "en" ? "en-US" : "zh-TW";
  const rows: { key: string; label: string; value: number }[] = [
    { key: "like", label: t("metrics.like"), value: n(post.like_count) },
    { key: "reply", label: t("metrics.reply"), value: n(post.reply_count) },
    { key: "repost", label: t("metrics.repost"), value: n(post.repost_count) },
    { key: "quote", label: t("metrics.quote"), value: n(post.quote_count) },
    { key: "view", label: t("metrics.view"), value: n(post.view_count) },
    { key: "share", label: t("metrics.share"), value: n(post.share_count) },
  ];

  if (variant === "detail") {
    return (
      <div className="hb-metrics-grid" role="group" aria-label={t("metrics.aria")}>
        {rows.map((r) => (
          <div key={r.key} className="hb-metrics-cell">
            <span className="hb-metrics-cell__val">{r.value.toLocaleString(dateLocale)}</span>
            <span className="hb-metrics-cell__label">{r.label}</span>
          </div>
        ))}
      </div>
    );
  }

  return (
    <div className="hb-metrics-inline" role="group" aria-label={t("metrics.aria")}>
      {rows.map((r) => (
        <span key={r.key} className="hb-metrics-chip">
          <strong>{r.value.toLocaleString(dateLocale)}</strong> {r.label}
        </span>
      ))}
    </div>
  );
}

export function postTypeLabel(
  post: OwnPost,
  t: (key: string) => string,
): string {
  if (post.is_quote_post) return t("metrics.type.quote");
  if (post.is_reply) return t("metrics.type.reply");
  const mt = (post.media_type || "").toUpperCase();
  if (mt.includes("IMAGE")) return t("metrics.type.image");
  if (mt.includes("VIDEO")) return t("metrics.type.video");
  if (mt.includes("CAROUSEL")) return t("metrics.type.carousel");
  if (mt.includes("REPOST")) return t("metrics.type.repost");
  if (mt.includes("TEXT")) return t("metrics.type.text");
  return post.media_type || t("metrics.type.post");
}
