import React from "react";
import { render } from "@testing-library/react";
import ProductDetailsAccordion from "@/components/productpage/ProductDetailsAccordion";
import { expect, test, vi } from "vitest";
import DOMPurify from "isomorphic-dompurify";

// Mock Accordion components
vi.mock("@/components/ui/accordion", () => ({
  Accordion: ({ children }: any) => <div>{children}</div>,
  AccordionItem: ({ children, value }: any) => <div data-testid={`item-${value}`}>{children}</div>,
  AccordionTrigger: ({ children }: any) => <button>{children}</button>,
  AccordionContent: ({ children }: any) => <div>{children}</div>,
}));

// Mock Separator component
vi.mock("@/components/ui/separator", () => ({
  Separator: () => <hr />,
}));

// Spy on DOMPurify.sanitize
vi.mock("isomorphic-dompurify", () => ({
  default: {
    sanitize: vi.fn((html) => html),
  },
}));

test("ProductDetailsAccordion memoizes sanitization", () => {
  const description = "<b>Safe HTML</b>";
  const { rerender } = render(
    <ProductDetailsAccordion
      description={description}
      manufacturerInfo="Info 1"
      structuredData={[]}
    />
  );

  // Initial render should call sanitize once
  expect(DOMPurify.sanitize).toHaveBeenCalledTimes(1);

  // Re-render with same description but different manufacturerInfo
  rerender(
    <ProductDetailsAccordion
      description={description}
      manufacturerInfo="Info 2"
      structuredData={[]}
    />
  );

  // sanitize should NOT be called again due to useMemo and React.memo
  expect(DOMPurify.sanitize).toHaveBeenCalledTimes(1);

  // Re-render with DIFFERENT description
  rerender(
    <ProductDetailsAccordion
      description="<i>New HTML</i>"
      manufacturerInfo="Info 2"
      structuredData={[]}
    />
  );

  // sanitize should be called again
  expect(DOMPurify.sanitize).toHaveBeenCalledTimes(2);
});
