import { clsx, type ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";

export interface IPost {
  images: string[];
  title: string;
  price: number;
  category: string;
  condition: string;
  brand?: string;
  description: string;
  tags: string[];
  sku: string;
  location?: string;
  status?: boolean;
  id: string;
  publist_id?: string;
  raw_condition?: string;
  base64Images?: string[];
  mapped?: boolean;
}

export interface ISyncItem {
  title: string;
  price: number;
  el: HTMLElement;
  url_info: string;
}

export function cn(...inputs: ClassValue[]) {
  return twMerge(clsx(inputs));
}

export function mapToIPost(raw: any): IPost {
  let images: string[] = [];

  if (Array.isArray(raw?.listImage)) {
    images = raw.listImage
      .map((img: any) =>
        typeof img === "string"
          ? img
          : `${import.meta.env.VITE_BASE_IMG_URL as string}${img.url}`
      )
      .slice(0, 10); // chỉ lấy tối đa 10 ảnh
  }

  // xử lý package_contain
  let packageContainText = "Package contain:\n";
  if (Array.isArray(raw?.package_contain)) {
    packageContainText += raw.package_contain
      .map((item: string) => `- ${item}`)
      .join("\n");
  } else if (
    typeof raw?.package_contain === "string" &&
    raw.package_contain.trim() !== ""
  ) {
    packageContainText += raw.package_contain;
  }

  // build description rõ ràng, không có thụt đầu dòng
  const descriptionLines = [
    raw.description || "",
    raw.code || "",
    raw.title || "",
    (typeof raw?.category === "string" ? raw.category : raw?.category?.name) ||
      "",
    packageContainText,
    `Join the "Prology | Latest Products & Deals" group for more products.`,
  ]
    .filter(Boolean) // loại bỏ cái rỗng
    .join("\n\n"); // cách 1 dòng giữa các block

  return {
    images,
    title: raw?.title?.includes(raw?.code)
      ? raw?.title
      : `${raw?.title} - ${raw?.code}`,
    price: raw?.price,
    category: "electronics & computers",
    condition: (raw?.conditionEbay as string)?.toLowerCase()?.includes("new")
      ? "new"
      : "used – like new",
    brand: typeof raw?.manufactor === "string" ? raw?.manufactor : "",
    description: descriptionLines,
    tags: [],
    sku: raw?.code,
    location: raw?.location || "Sydney, Australia",
    status: false,
    id: raw?.id,
    publist_id: raw?.listingId,
    raw_condition: raw?.condition,
    mapped: true,
  };
}
