"use client";

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

export interface SharedProductPayload {
  listingId: string;
  title?: string;
  preview?: string;
  price?: number | null;
  shopName?: string;
  url?: string;
}

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

export default function SharedProductBubble({ data }: { data: SharedProductPayload }) {
  const { t } = useTranslation("common");
  const href = data.url || `/shops/listing/${data.listingId}`;
  const preview = data.preview ? IMAGE_BASE_URL + 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">
          <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.title || t("shops.viewProduct")}
        </p>
        {data.price != null && (
          <p className="text-[10px] opacity-75">
            {t("shops.priceLabel", { amount: data.price.toLocaleString() })}
          </p>
        )}
        {data.shopName ? (
          <p className="text-[10px] opacity-60">{data.shopName}</p>
        ) : null}
      </div>
    </Link>
  );
}
