import React from 'react';
import { IconName, iconSvgs } from './icons';

interface AppIconProps extends React.HTMLAttributes<HTMLSpanElement> {
  name: IconName;
}

export function AppIcon({ name, ...props }: AppIconProps): JSX.Element {
  const svg = iconSvgs[name];

  if (!svg) {
    console.warn(`Icon "${name}" not found`);
    const { className, style, ...rest } = props;
    return <span className={className} style={style} aria-hidden="true" {...rest} />;
  }

  const { className, style, ...rest } = props;
  const ariaHidden = (rest as Record<string, unknown>)['aria-hidden'] ?? true;

  const isInlineMarkup = typeof svg === 'string' && svg.trim().startsWith('<');

  // Inline markup keeps `currentColor`; fallback to <img> when loader returns a URL.
  if (!isInlineMarkup) {
    return (
      <img
        src={svg}
        className={className}
        role="img"
        aria-hidden={ariaHidden as boolean}
        {...(rest as React.ImgHTMLAttributes<HTMLImageElement>)}
      />
    );
  }

  // Strip fixed sizing; push utility classes onto <svg> so Tailwind sizing applies.
  const svgMarkup = svg
    .replace(/\swidth="[^"]*"/i, '')
    .replace(/\sheight="[^"]*"/i, '')
    .replace(
      /<svg([^>]*)>/i,
      `<svg$1 width="100%" height="100%"${className ? ` class="${className}"` : ''}>`,
    );

  return (
    <span
      role="img"
      aria-hidden={ariaHidden as boolean}
      style={{ display: 'inline-flex', ...style }}
      {...rest}
      dangerouslySetInnerHTML={{ __html: svgMarkup }}
    />
  );
}

export type { IconName };
