/* global React */

// Inline-loads the XILROS logo SVGs so currentColor flows from CSS
// and the --logo-bg custom property controls the interior cutouts on the lion mark.

const _logoCache = {};

function _loadSVG(url) {
  if (_logoCache[url]) return Promise.resolve(_logoCache[url]);
  return fetch(url, { cache: 'no-store' })
    .then(r => r.text())
    .then(t => (_logoCache[url] = t));
}

function SVGInline({ src, width, height, style, className, ariaLabel }) {
  const ref = React.useRef(null);
  React.useEffect(() => {
    let cancelled = false;
    _loadSVG(src).then(t => {
      if (cancelled || !ref.current) return;
      const doc = new DOMParser().parseFromString(t, 'image/svg+xml');
      const svg = doc.documentElement;
      svg.removeAttribute('width');
      svg.removeAttribute('height');
      if (width)  svg.setAttribute('width',  width);
      if (height) svg.setAttribute('height', height);
      if (width && !height) svg.style.height = 'auto';
      if (height && !width) svg.style.width  = 'auto';
      if (ariaLabel) { svg.setAttribute('role', 'img'); svg.setAttribute('aria-label', ariaLabel); }
      else svg.setAttribute('aria-hidden', 'true');
      svg.style.display = 'block';
      ref.current.innerHTML = '';
      ref.current.appendChild(svg);
    });
    return () => { cancelled = true; };
  }, [src, width, height]);
  return <span ref={ref} className={className} style={style} />;
}

function LogoMark({ size = 28, color, bg, label }) {
  return (
    <SVGInline
      src="assets/logo-lionhead.svg"
      width={size}
      style={{ color, ['--logo-bg']: bg, display: 'inline-flex' }}
      ariaLabel={label || 'XILROS'}
    />
  );
}

function LogoWordmark({ width = 96, color }) {
  return (
    <SVGInline
      src="assets/logo-wordmark.svg"
      width={width}
      style={{ color, display: 'inline-flex' }}
      ariaLabel="XILROS"
    />
  );
}

function LogoLockup({ markSize = 28, wordWidth = 96, color, bg, gap = 12 }) {
  return (
    <span style={{ display: 'inline-flex', alignItems: 'center', gap, color }}>
      <LogoMark size={markSize} bg={bg} />
      <LogoWordmark width={wordWidth} />
    </span>
  );
}

Object.assign(window, { SVGInline, LogoMark, LogoWordmark, LogoLockup });
