import { useEffect, useRef } from "react";

type Props = {
  sdkKey: string;
  productId: string;
  variantId: string;
  cartId?: string;
  cartUrl?: string;
  language?: string;
};

// Load the CDN SDK once in your app shell. For Next.js App Router,
// add "use client"; at the top of this file.
export function AntlaTryOn({
  sdkKey, productId, variantId, cartId, cartUrl = "/cart", language,
}: Props) {
  const host = useRef<HTMLDivElement>(null);
  const block = useRef<HTMLElement | null>(null);

  useEffect(() => {
    const element = block.current ?? document.createElement("antla-block");
    const attributes: Record<string, string | undefined> = {
      "variant-id": variantId,
      "product-id": productId,
      "cart-id": cartId,
      "cart-url": cartUrl,
      language,
      "sdk-key": sdkKey,
    };
    for (const [name, value] of Object.entries(attributes)) {
      if (value === undefined || value === "") element.removeAttribute(name);
      else if (element.getAttribute(name) !== value) element.setAttribute(name, value);
    }
    if (!block.current) {
      block.current = element;
      host.current?.appendChild(element);
    }
  }, [sdkKey, productId, variantId, cartId, cartUrl, language]);

  useEffect(() => () => {
    block.current?.remove();
    block.current = null;
  }, []);

  return <div ref={host} />;
}
