import type { FunctionalComponent } from 'preact';
import { ASUKA_ICON_ALIASES } from './asukaIconCatalog.generated';

function slugify(input?: string | null): string {
  if (!input) return '';
  return String(input)
    .trim()
    .toLowerCase()
    .replace(/\s+/g, '-')
    .replace(/_/g, '-');
}

export function normalizePremiumIconName(raw?: string | null, fallback?: string | null): string {
  const normalized = slugify(raw);
  if (!normalized && fallback) return normalizePremiumIconName(fallback);
  return (ASUKA_ICON_ALIASES[normalized] ?? normalized) || normalizePremiumIconName(fallback);
}

function svgToDataUri(svg: string) {
  const normalized = svg
    .replace(/\r?\n|\r/g, ' ')
    .replace(/\s{2,}/g, ' ')
    .trim();
  return `data:image/svg+xml;utf8,${encodeURIComponent(normalized)}`;
}

type AsukaIconProps = {
  name?: string | null;
  className?: string;
  size?: number;
  title?: string;
};

export const AsukaIcon: FunctionalComponent<AsukaIconProps> = ({ name, className, size = 18, title }) => {
  const raw = String(name ?? '').trim();

  if (!raw) return null;

  const style: Record<string, string | number> = {
    width: `${size}px`,
    height: `${size}px`,
    fontSize: `${size}px`,
  };

  // custom URL support: "url:https://..."
  if (raw.startsWith('url:')) {
    const src = raw.slice(4).trim();
    if (!src) return null;
    style.maskImage = `url("${src}")`;
    style.webkitMaskImage = `url("${src}")`;
    return <span class={`ask-icon ask-icon--mask ${className ?? ''}`.trim()} style={style as any} title={title} aria-hidden="true" />;
  }

  // raw svg support: "svg:<svg ...>"
  if (raw.startsWith('svg:')) {
    const svg = raw.slice(4).trim();
    if (!svg) return null;
    const dataUri = svgToDataUri(svg);
    style.maskImage = `url("${dataUri}")`;
    style.webkitMaskImage = `url("${dataUri}")`;
    return <span class={`ask-icon ask-icon--mask ${className ?? ''}`.trim()} style={style as any} title={title} aria-hidden="true" />;
  }

  const normalized = normalizePremiumIconName(raw);
  return (
    <span
      class={`ask-icon ask-icon--${normalized} ${className ?? ''}`.trim()}
      style={style as any}
      title={title}
      aria-hidden="true"
    />
  );
};

export default AsukaIcon;
