"use client";

import { useState } from "react";
import { cn } from "@/lib/utils";
import {
  getCollapsedCaptionPreview,
  postCaptionNeedsMore,
} from "@/lib/postLinkCaption";
import { useTranslation } from "react-i18next";

type ExpandableBioProps = {
  bio?: string | null;
  className?: string;
  moreClassName?: string;
};

export default function ExpandableBio({
  bio,
  className,
  moreClassName = "text-blue-500 text-xs font-semibold",
}: ExpandableBioProps) {
  const { t } = useTranslation("common");
  const [showFull, setShowFull] = useState(false);
  const text = bio?.trim() || "";
  if (!text) return null;

  const needsMore = postCaptionNeedsMore(text);
  const displayed =
    showFull || !needsMore ? text : getCollapsedCaptionPreview(text);

  return (
    <span className={cn("whitespace-pre-wrap leading-6", className)}>
      {displayed}
      {needsMore ? (
        <>
          {" "}
          <button
            type="button"
            className={cn("inline cursor-pointer align-baseline", moreClassName)}
            onClick={() => setShowFull((v) => !v)}
          >
            {showFull ? t("posts.less") : t("posts.more")}
          </button>
        </>
      ) : null}
    </span>
  );
}
