import * as React from "react";
import { createPortal } from "react-dom";

export interface PopupAnchor {
  top?: number;
  left?: number;
  right?: number;
  bottom?: number;
}

export interface PopupProps {
  open: boolean;
  onClose: () => void;
  /** "menu" = compact button-list card; "form" = wider inline form card. */
  variant?: "menu" | "form";
  anchor?: PopupAnchor | "center";
  children: React.ReactNode;
  className?: string;
  /** Portal target - defaults to document.body. Override for iframe/canvas embedding. */
  portalTarget?: Element;
}

export function Popup({
  open,
  onClose,
  variant = "menu",
  anchor = "center",
  children,
  className,
  portalTarget,
}: PopupProps) {
  if (!open) return null;

  const classes = ["ads-popup", `ads-popup--${variant}`];
  if (className) classes.push(className);

  const style: React.CSSProperties =
    anchor === "center"
      ? { top: "50%", left: "50%", transform: "translate(-50%, -50%)" }
      : { ...anchor };

  const content = (
    <>
      <div className="ads-popup-catcher" onClick={onClose} />
      <div className={classes.join(" ")} style={style}>
        {children}
      </div>
    </>
  );

  const target = portalTarget ?? (typeof document !== "undefined" ? document.body : null);
  return target ? createPortal(content, target) : content;
}

export interface PopupMenuItemProps {
  onClick?: () => void;
  destructive?: boolean;
  children: React.ReactNode;
}

export function PopupMenuItem({ onClick, destructive, children }: PopupMenuItemProps) {
  return (
    <button
      type="button"
      className={destructive ? "ads-popup-item ads-popup-item--destructive" : "ads-popup-item"}
      onClick={onClick}
    >
      {children}
    </button>
  );
}
