// wordmark.jsx
// ─────────────────────────────────────────────────────────────────────────────
// Sauvrn wordmark — overlay technique.
//
// Two layers:
//   Layer 1: "SAUVRN" in Inter Bold, solid color (coral)
//   Layer 2: "AI" in Inter Bold, same size, positioned to overlay the AU
//            portion of SAUVRN, with transparency
//
// The A in layer 2 aligns with the A in layer 1 (so the A appears doubled in
// a different color), and the I in layer 2 naturally lands at the start of
// the U position — creating a vertical accent over the U that reads as "AI"
// hidden in the wordmark.

const { useEffect, useState, useRef, useLayoutEffect } = React;

function SauvrnWordmark({
  size = 240,
  className = '',
  ariaLabel = 'Sauvrn',
  fillContainer = false,
  color = null,
  overlayColor = null,
  overlayOpacity = 0.55,
  bgColor = null,
  fontFamily = '"Inter", "Helvetica Neue", system-ui, sans-serif',
  fontWeight = 800,
  letterSpacing = '-0.04em',
}) {
  const svgRef = useRef(null);
  const [glyphs, setGlyphs] = useState(null);

  // Resolve colors from CSS vars if not provided. SVG presentation attrs
  // don't reliably resolve var(--…), so we read computed values once.
  const [resolvedColor, setResolvedColor] = useState(color || '#E55A4B');
  const [resolvedOverlay, setResolvedOverlay] = useState(overlayColor || '#E8E4D6');
  const [resolvedBg, setResolvedBg] = useState(bgColor || '#0A0B10');

  useLayoutEffect(() => {
    if (!svgRef.current) return;
    const cs = getComputedStyle(svgRef.current);
    if (!color) {
      const v = cs.getPropertyValue('--accent').trim();
      if (v) setResolvedColor(v);
    }
    if (!bgColor) {
      const v = cs.getPropertyValue('--bg').trim();
      if (v) setResolvedBg(v);
    }
    // No CSS var for overlay; only the consumer can pick.
    if (overlayColor) setResolvedOverlay(overlayColor);
  }, [color, overlayColor, bgColor]);

  useEffect(() => {
    if (color && overlayColor && bgColor) return;
    const onTweak = () => {
      if (!svgRef.current) return;
      const cs = getComputedStyle(svgRef.current);
      if (!color) {
        const v = cs.getPropertyValue('--accent').trim();
        if (v) setResolvedColor(v);
      }
      if (!bgColor) {
        const v = cs.getPropertyValue('--bg').trim();
        if (v) setResolvedBg(v);
      }
    };
    window.addEventListener('tweakchange', onTweak);
    return () => window.removeEventListener('tweakchange', onTweak);
  }, [color, overlayColor, bgColor]);

  // Measure per-character layout positions for "SAUVRN". We need exact x
  // positions for both the A (overlay A) and the U (overlay I) so the AI
  // overlay aligns to them precisely — not via natural A→I font kerning,
  // which differs across faces and weights.
  useLayoutEffect(() => {
    let cancelled = false;
    const measure = () => {
      if (cancelled || !svgRef.current) return;
      const probe = svgRef.current.querySelector('#sizer');
      if (!probe || typeof probe.getNumberOfChars !== 'function') return;
      try {
        const aStart = probe.getStartPositionOfChar(1);   // A layout start
        const uStart = probe.getStartPositionOfChar(2);   // U layout start
        const aExt   = probe.getExtentOfChar(1);
        const sExt   = probe.getExtentOfChar(0);
        const nExt   = probe.getExtentOfChar(5);
        const totalLeft  = sExt.x;
        const totalRight = nExt.x + nExt.width;
        setGlyphs({
          aX: aStart.x,            // for the overlay's A
          iX: uStart.x,            // for the overlay's I — same x as U
          aW: aExt.width,
          minX: totalLeft,
          totalW: totalRight - totalLeft,
        });
      } catch (e) { /* not laid out yet */ }
    };
    if (document.fonts && document.fonts.ready) document.fonts.ready.then(measure);
    else measure();
    return () => { cancelled = true; };
  }, [size]);

  const textStyle = {
    fontFamily,
    fontWeight,
    letterSpacing,
  };
  const fontProps = { fontSize: size, dominantBaseline: 'alphabetic', textAnchor: 'start' };

  const padX = Math.max(4, size * 0.04);
  const padY = padX;
  const baselineY = size * 0.78;
  const fontMetricH = size * 0.86;
  const intrinsicW = glyphs?.totalW ? glyphs.totalW + padX * 2 : size * 4.5;
  const intrinsicH = fontMetricH + padY * 2;
  const minX = glyphs?.minX ?? 0;

  return (
    <svg
      ref={svgRef}
      className={className}
      role="img"
      aria-label={ariaLabel}
      viewBox={`${minX - padX} ${-padY} ${intrinsicW} ${intrinsicH}`}
      width={intrinsicW}
      height={intrinsicH}
      style={fillContainer
        ? { display: 'block', overflow: 'visible', userSelect: 'none', width: '100%', height: 'auto' }
        : { display: 'block', overflow: 'visible', userSelect: 'none', maxWidth: '100%' }}
      shapeRendering="geometricPrecision"
    >
      {/* Sizer — invisible, mirrors layer 1's tspan structure so glyph
          positions match exactly across both texts (otherwise the AI overlay
          drifts when the V-dx kerning adjustment changes layout flow). */}
      <text id="sizer" x={0} y={baselineY} {...fontProps}
            style={{ ...textStyle, opacity: 0, pointerEvents: 'none' }}
            aria-hidden="true">
        <tspan>SAU</tspan><tspan dx={-size * 0.012}>V</tspan><tspan>RN</tspan>
      </text>

      {/* Layer 1: SAUVRN in solid color.
          The V is nudged left a touch with dx to tighten the U-V optical gap
          (V's angled left edge against U's straight right creates a visual
          loosening that Inter's built-in kerning doesn't fully resolve at
          display sizes). */}
      <text x={0} y={baselineY} {...fontProps} style={textStyle} fill={resolvedColor}>
        <tspan>SAU</tspan><tspan dx={-size * 0.012}>V</tspan><tspan>RN</tspan>
      </text>

      {/* Layer 2: A and I as independent tspans at the exact measured
          positions of the A and U in SAUVRN. This avoids font-specific
          A→I kerning drift — each glyph is pinned to its target spot. */}
      {glyphs && (
        <text y={baselineY} {...fontProps}
              style={{ ...textStyle, opacity: overlayOpacity }}
              fill={resolvedOverlay}>
          <tspan x={glyphs.aX}>A</tspan>
          <tspan x={glyphs.iX}>I</tspan>
        </text>
      )}
    </svg>
  );
}

Object.assign(window, { SauvrnWordmark });
