import React from 'react';

import { DEFAULT_VIEWBOX, SVG_NS } from '../svgString';
import type { IconData } from '../types';

import { defaultIconProps } from './common';
import type { IconPropsReact } from './types';

/**
 * Build an icon React component from its shared {@link IconData}.
 *
 * The path data lives in a single `data` module that both this component and
 * the `svgIcon()` string API import, so it is never bundled twice. The
 * rendered output and prop handling match the previously code-generated
 * components: props spread onto the `<svg>` element, `size` overrides
 * width/height, and `variant` selects filled/outlined.
 */
export const makeIcon = (data: IconData, name: string, displayName: string) => {
  const Icon = (props: IconPropsReact) => {
    // `size` is destructured out so it is not forwarded as a stray DOM attribute.
    const { variant, size, ...restProps } = {
      ...defaultIconProps,
      ...props,
    };

    const inner = variant === 'outlined' ? data.o ?? data.f : data.f ?? data.o;
    const rootAttrs = variant === 'outlined' ? data.rao : data.raf;
    const viewBox = (variant === 'outlined' ? data.vbo : undefined) ?? data.vb ?? DEFAULT_VIEWBOX;
    const overrides = props.size ? { width: props.size, height: props.size } : {};

    return React.createElement('svg', {
      xmlns: SVG_NS,
      viewBox,
      ...rootAttrs,
      'aria-label': name,
      ...restProps,
      ...overrides,
      dangerouslySetInnerHTML: { __html: inner ?? '' },
    });
  };

  Icon.displayName = displayName;

  return Icon;
};
