"use client";

import Image from "next/image";
import Link from "next/link";
import { buildStorageUrl } from "@/components/main/BaseUrl";
import { useTranslation } from "react-i18next";

export interface SharedPostPayload {
  postId: string;
  caption?: string;
  type?: string;
  preview?: string;
  authorUserName?: string;
  authorDisplayName?: string;
  url?: string;
}

export function parseSharedPost(content: string): SharedPostPayload | null {
  if (!content) return null;
  try {
    const line = content.split("\n")[0];
    const j = JSON.parse(line);
    if (j?.e2ee) return null;
    return j.sharedPost ?? null;
  } catch {
    return null;
  }
}

export default function SharedPostBubble({ data }: { data: SharedPostPayload }) {
  const { t } = useTranslation("common");
  const href = data.url || `/posts/${data.postId}`;
  const preview = data.preview ? buildStorageUrl(data.preview) : null;

  return (
    <Link
      href={href}
      className="block overflow-hidden rounded-xl border border-white/20 bg-black/10"
    >
      {preview && (
        <div className="relative aspect-[4/3] w-full min-w-[200px] max-w-[240px] bg-neutral-900">
          {data.type === "video" ? (
            <video
              src={preview}
              className="h-full w-full object-cover"
              muted
              playsInline
              preload="metadata"
            />
          ) : (
            <Image
              src={preview}
              alt=""
              fill
              className="object-cover"
              unoptimized
            />
          )}
        </div>
      )}
      <div className="px-2 py-1.5">
        <p className="text-[11px] font-semibold opacity-90">
          {data.authorDisplayName || data.authorUserName || t("chats.post")}
        </p>
        {data.caption ? (
          <p className="line-clamp-2 text-[10px] opacity-75">{data.caption}</p>
        ) : null}
      </div>
    </Link>
  );
}
