import React from "react";

export interface FAIconProps {
  /** Icon name with or without fa- prefix e.g. "robot", "fa-user", "gear", "shopify", "google" */
  name: string;
  /** Icon style prefix or inline CSS style object */
  style?: "solid" | "regular" | "brands" | React.CSSProperties;
  /** Optional custom CSS classes for sizing, colors, or positioning */
  className?: string;
  /** Font Awesome size variant: "xs" | "sm" | "lg" | "xl" | "2xl" */
  size?: "xs" | "sm" | "lg" | "xl" | "2xl";
  /** Spin animation for loading indicators */
  spin?: boolean;
  /** Pulse animation */
  pulse?: boolean;
  /** Accessibility label when icon is used without visible text */
  label?: string;
  /** Click handler */
  onClick?: (event: React.MouseEvent<HTMLElement>) => void;
}

const BRAND_ICONS = new Set([
  "shopify",
  "google",
  "openai",
  "github",
  "stripe",
  "paypal",
  "cc-visa",
  "cc-mastercard",
  "cc-paypal",
  "cc-amex",
  "cc-discover",
  "apple",
  "whatsapp",
  "twitter",
  "facebook",
  "instagram",
  "linkedin",
  "youtube",
  "discord",
  "telegram",
]);

/**
 * Reusable Font Awesome Icon Component for ShopPilot AI.
 * Provides accessible, consistent Font Awesome icons across all pages.
 */
export function FAIcon({
  name,
  style = "solid",
  className = "",
  size,
  spin = false,
  pulse = false,
  label,
  onClick,
}: FAIconProps) {
  const isStyleObj = typeof style === "object" && style !== null;
  const iconStyle = isStyleObj ? (style as React.CSSProperties) : undefined;
  const styleType = isStyleObj ? "solid" : (style as string);

  const cleanName = (name || "")
    .replace(/^fa[srb]?\s+/, "")
    .replace(/^fa-/, "")
    .trim();
  const isBrand = BRAND_ICONS.has(cleanName) || styleType === "brands";

  const prefix = isBrand ? "fa-brands fab" : styleType === "regular" ? "fa-regular far" : "fa-solid fas";
  const iconClass = `fa-${cleanName}`;
  const sizeClass = size ? `fa-${size}` : "";
  const spinClass = spin ? "fa-spin" : pulse ? "fa-pulse" : "";

  const combinedClasses = `fa ${prefix} ${iconClass} ${sizeClass} ${spinClass} ${className}`.replace(/\s+/g, " ").trim();

  return (
    <i
      className={combinedClasses}
      style={iconStyle}
      aria-hidden={!label ? true : undefined}
      aria-label={label}
      role={label ? "img" : undefined}
      onClick={onClick}
    />
  );
}

export default FAIcon;
