import { forwardRef } from "react";

/**
 * Chip
 *
 * active:     boolean - applies active state; sets aria-pressed when onClick is used
 * disabled:   boolean
 * icon:       ReactNode - leading icon; add aria-hidden="true" if decorative
 * onClick:    function - renders as <button aria-pressed>; toggleable filter chip
 * onClose:    function - renders a close button inside the chip
 * closeLabel: string - aria-label for the close button (default: "Remove")
 *
 * Renders as <button> with onClick, static <span> without.
 */
const Chip = forwardRef(function Chip(
  {
    active = false,
    disabled = false,
    icon,
    onClose,
    closeLabel = "Remove",
    onClick,
    className = "",
    children,
    ...props
  },
  ref
) {
  const classes = [
    "prs-chip",
    active   && "prs-chip_active",
    disabled && "prs-chip_disabled",
    className,
  ]
    .filter(Boolean)
    .join(" ");

  const inner = (
    <>
      {icon && <span className="icon">{icon}</span>}
      <span className="prs-chip-label">{children}</span>
      {onClose && (
        <button
          type="button"
          className="close"
          aria-label={closeLabel}
          disabled={disabled}
          onClick={(e) => {
            e.stopPropagation();
            onClose(e);
          }}
        >
          <CloseIcon />
        </button>
      )}
    </>
  );

  // Removable tag - chip itself is not interactive unless onClick also provided
  if (onClose && !onClick) {
    return (
      <span ref={ref} className={classes} {...props}>
        {inner}
      </span>
    );
  }

  // Toggleable or clickable chip
  if (onClick) {
    return (
      <button
        ref={ref}
        type="button"
        className={classes}
        aria-pressed={active}
        disabled={disabled}
        onClick={onClick}
        {...props}
      >
        {inner}
      </button>
    );
  }

  // Static display chip
  return (
    <span ref={ref} className={classes} {...props}>
      {inner}
    </span>
  );
});

export default Chip;

// Internal close icon - always decorative
const CloseIcon = () => (
  <svg viewBox="0 0 12 12" fill="currentColor" width="8" height="8" aria-hidden="true">
    <path d="M1.47 1.47a.75.75 0 0 1 1.06 0L6 4.94l3.47-3.47a.75.75 0 1 1 1.06 1.06L7.06 6l3.47 3.47a.75.75 0 1 1-1.06 1.06L6 7.06 2.53 10.53a.75.75 0 0 1-1.06-1.06L4.94 6 1.47 2.53a.75.75 0 0 1 0-1.06Z" />
  </svg>
);
