// Glossary page — a-z jump rail, search/filter w/ highlight, deep-link copy, related chips, / shortcut, tweaks.
// Voice: AB Group enterprise, modern, clean. Pairs with services/glossary-data.js (window.GLOSSARY_TERMS).

const { useState, useEffect, useMemo, useRef, useCallback } = React;

// — Letters list
const ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');

// — Build slug from a term name (used for matching related slugs from data)
function slugify(s) {
  return String(s).toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, '');
}

// — Localize a glossary entry. Mirrors pickServiceContent() in service-content.js:
//   when lang === 'es' and the slug exists in window.GLOSSARY_DATA_ES, overlay
//   def/agNote/tags. Term and abbr stay in English (industry shorthand).
function pickTerm(t, lang) {
  if (lang !== 'es') return t;
  const es = (window.GLOSSARY_DATA_ES || {})[t.slug];
  if (!es) return t;
  return Object.assign({}, t,
    es.def    !== undefined ? { def:    es.def }    : null,
    es.agNote !== undefined ? { agNote: es.agNote } : null,
    es.tags   !== undefined ? { tags:   es.tags }   : null);
}

// — Highlight helper: wraps occurrences of `q` in <mark>
function HighlightedText({ text, query }) {
  if (!query) return <>{text}</>;
  const safe = query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  const re = new RegExp(`(${safe})`, 'ig');
  const parts = String(text).split(re);
  return (
    <>
      {parts.map((p, i) =>
        re.test(p) ? <mark key={i} className="gl-mark">{p}</mark> : <span key={i}>{p}</span>
      )}
    </>
  );
}

// — Tag pill colors
const TAG_COLORS = {
  Ocean:        { bg: '#EFF6FF', fg: '#1846B0' },
  Air:          { bg: '#F5F3FF', fg: '#5B21B6' },
  Customs:      { bg: '#FEF3C7', fg: '#92400E' },
  Trade:        { bg: '#FFF7ED', fg: '#9A3412' },
  HAZMAT:       { bg: '#FEE2E2', fg: '#B42318' },
  Trucking:     { bg: '#ECFEFF', fg: '#155E75' },
  Warehousing:  { bg: '#F0FDF4', fg: '#15803D' },
  Compliance:   { bg: '#F0F9FF', fg: '#075985' },
  Security:     { bg: '#FAFAF9', fg: '#1F2937' },
  Insurance:    { bg: '#FAF5FF', fg: '#6B21A8' },
  Documentation:{ bg: '#F9FAFB', fg: '#1F2937' },
  Operations:   { bg: '#F9FAFB', fg: '#344054' },
  Classification:{ bg: '#FEF2F2', fg: '#991B1B' },
  Fulfillment:  { bg: '#FDF4FF', fg: '#86198F' },
};

function TagPill({ label }) {
  const c = TAG_COLORS[label] || { bg: '#F2F4F7', fg: '#475467' };
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center',
      padding: '3px 9px', borderRadius: 9999,
      background: c.bg, color: c.fg,
      fontSize: 10.5, fontWeight: 600, letterSpacing: '0.04em',
      textTransform: 'uppercase', fontFamily: 'JetBrains Mono, monospace'
    }}>{label}</span>
  );
}

// — Inline SVG icons we need beyond Primitives
function CopyIcon({ size = 14 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round">
      <rect x="9" y="9" width="13" height="13" rx="2" ry="2"/>
      <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/>
    </svg>
  );
}
function CheckIcon({ size = 14 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <polyline points="20 6 9 17 4 12"/>
    </svg>
  );
}
function SearchIcon({ size = 16 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <circle cx="11" cy="11" r="8"/>
      <path d="m21 21-4.3-4.3"/>
    </svg>
  );
}

// =========================================================
// Term card
// =========================================================
function TermCard({ t, query, density, showAgNotes, showTags, onJumpTo }) {
  const i18n = window.__useI18n();
  const tr = i18n.t;
  const [copied, setCopied] = useState(false);
  const cardRef = useRef(null);

  const copyLink = useCallback(() => {
    const url = location.origin + location.pathname + '#' + t.slug;
    navigator.clipboard?.writeText(url);
    setCopied(true);
    setTimeout(() => setCopied(false), 1400);
    history.replaceState(null, '', '#' + t.slug);
  }, [t.slug]);

  // Resolve related (term names → slugs)
  const relatedTerms = useMemo(() => {
    if (!t.related) return [];
    return t.related
      .map(r => window.GLOSSARY_INDEX[slugify(r)])
      .filter(Boolean);
  }, [t]);

  const padY = density === 'compact' ? 24 : density === 'spacious' ? 44 : 32;

  return (
    <article id={t.slug} ref={cardRef} className="gl-card"
      style={{
        padding: `${padY}px 0`,
        borderTop: '1px solid #eaecf0',
        scrollMarginTop: 96,
      }}>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr auto', alignItems: 'flex-start', gap: 24 }}>
        <div style={{ minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'baseline', flexWrap: 'wrap', gap: 12, marginBottom: 8 }}>
            <h3 style={{ margin: 0, fontSize: density === 'compact' ? 22 : 26, fontWeight: 700,
              letterSpacing: '-0.025em', color: '#0B1220', lineHeight: 1.15 }}>
              <HighlightedText text={t.term} query={query}/>
            </h3>
            {t.abbr && (
              <span style={{ fontFamily: 'JetBrains Mono, monospace',
                fontSize: 13, fontWeight: 600, color: '#1846B0',
                background: '#EFF6FF', padding: '3px 10px', borderRadius: 6,
                letterSpacing: '0.02em' }}>
                <HighlightedText text={t.abbr} query={query}/>
              </span>
            )}
            {showTags !== false && (
              <div style={{ display: 'inline-flex', gap: 6, flexWrap: 'wrap', marginLeft: 4 }}>
                {(t.tags || []).map(tag => <TagPill key={tag} label={tag}/>)}
              </div>
            )}
          </div>

          <p style={{ margin: '10px 0 0', fontSize: density === 'compact' ? 14.5 : 15.5,
            lineHeight: 1.65, color: '#344054', letterSpacing: '-0.005em',
            maxWidth: 760 }}>
            <HighlightedText text={t.def} query={query}/>
          </p>

          {t.agNote && showAgNotes !== false && (
            <div style={{ marginTop: 18, padding: '14px 18px',
              background: '#F8FAFF', border: '1px solid #DBEAFE',
              borderRadius: 10, maxWidth: 760, display: 'grid',
              gridTemplateColumns: 'auto 1fr', gap: 12, alignItems: 'flex-start' }}>
              <div style={{ marginTop: 1, fontFamily: 'JetBrains Mono, monospace',
                fontSize: 10, fontWeight: 700, letterSpacing: '0.1em',
                color: '#1846B0', background: '#fff', border: '1px solid #BFDBFE',
                padding: '3px 7px', borderRadius: 4 }}>
                {tr('glossary.agnote.label')}
              </div>
              <p style={{ margin: 0, fontSize: 14, lineHeight: 1.55, color: '#1E3A8A',
                letterSpacing: '-0.005em' }}>
                <HighlightedText text={t.agNote} query={query}/>
              </p>
            </div>
          )}

          {relatedTerms.length > 0 && (
            <div style={{ marginTop: 18, display: 'flex', alignItems: 'center',
              gap: 10, flexWrap: 'wrap', maxWidth: 760 }}>
              <span style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.1em',
                textTransform: 'uppercase', color: '#98A2B3' }}>{tr('glossary.related.label')}</span>
              {relatedTerms.map(rt => (
                <button key={rt.slug}
                  onClick={() => onJumpTo(rt.slug)}
                  className="gl-related-chip"
                  style={{
                    border: '1px solid #eaecf0', background: '#fff',
                    color: '#344054', fontFamily: 'inherit',
                    padding: '5px 11px', borderRadius: 9999,
                    fontSize: 12.5, fontWeight: 500, cursor: 'pointer',
                    letterSpacing: '-0.005em',
                    transition: 'all 160ms cubic-bezier(0.16,1,0.3,1)',
                  }}>
                  {rt.term}{rt.abbr ? ` · ${rt.abbr}` : ''}
                </button>
              ))}
            </div>
          )}
        </div>

        {/* Copy-link button */}
        <button onClick={copyLink}
          aria-label={copied ? tr('glossary.copy.aria.copied') : tr('glossary.copy.aria')}
          className="gl-copy-btn"
          style={{
            width: 36, height: 36, borderRadius: 9,
            border: '1px solid #eaecf0', background: copied ? '#ECFDF3' : '#fff',
            color: copied ? '#039855' : '#475467',
            display: 'grid', placeItems: 'center', cursor: 'pointer',
            flexShrink: 0, transition: 'all 160ms ease',
          }}>
          {copied ? <CheckIcon/> : <CopyIcon/>}
        </button>
      </div>
    </article>
  );
}

// =========================================================
// Letter section
// =========================================================
function LetterSection({ letter, terms, query, density, showAgNotes, showTags, onJumpTo }) {
  const i18n = window.__useI18n();
  const tr = i18n.t;
  return (
    <section id={'letter-' + letter} style={{ scrollMarginTop: 96, paddingTop: 8 }}>
      <div style={{
        display: 'flex', alignItems: 'baseline', gap: 18,
        padding: '40px 0 8px',
        borderBottom: '2px solid #0B1220',
      }}>
        <h2 style={{
          margin: 0, fontSize: 80, fontWeight: 800, color: '#0B1220',
          letterSpacing: '-0.05em', lineHeight: 0.9, fontFeatureSettings: '"ss01" 1',
        }}>{letter}</h2>
        <span style={{ fontFamily: 'JetBrains Mono, monospace',
          fontSize: 12, fontWeight: 600, color: '#98A2B3',
          letterSpacing: '0.06em' }}>
          {String(terms.length).padStart(2, '0')} {terms.length === 1 ? tr('glossary.term.singular') : tr('glossary.term.plural')}
        </span>
      </div>
      {terms.map(t => (
        <TermCard key={t.slug} t={t} query={query} density={density}
          showAgNotes={showAgNotes} showTags={showTags}
          onJumpTo={onJumpTo}/>
      ))}
    </section>
  );
}

// =========================================================
// A-Z Rail (sticky)
// =========================================================
function AZRail({ availableLetters, activeLetter, onJump }) {
  const [visible, setVisible] = useState(false);
  useEffect(() => {
    function onScroll() {
      // Show rail once the user has scrolled past the hero / search,
      // and hide it once they near the page footer.
      const y = window.scrollY || window.pageYOffset || 0;
      const showAfter = 360; // px: roughly past hero
      const docH = document.documentElement.scrollHeight;
      const winH = window.innerHeight;
      const nearBottom = (y + winH) > (docH - 360);
      setVisible(y > showAfter && !nearBottom);
    }
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('resize', onScroll);
    return () => {
      window.removeEventListener('scroll', onScroll);
      window.removeEventListener('resize', onScroll);
    };
  }, []);

  return (
    <div className="gl-az-rail" style={{
      position: 'fixed',
      top: '50%',
      right: 24,
      transform: `translateY(-50%) translateX(${visible ? '0' : '12px'})`,
      opacity: visible ? 1 : 0,
      pointerEvents: visible ? 'auto' : 'none',
      transition: 'opacity 220ms ease, transform 280ms cubic-bezier(0.16,1,0.3,1)',
      zIndex: 40,
      display: 'flex', flexDirection: 'column', gap: 2,
      padding: '12px 8px',
      background: 'rgba(255,255,255,0.78)',
      backdropFilter: 'saturate(180%) blur(10px)',
      WebkitBackdropFilter: 'saturate(180%) blur(10px)',
      border: '1px solid #eaecf0', borderRadius: 999,
      boxShadow: '0 6px 20px rgba(16,24,40,0.08), 0 1px 2px rgba(16,24,40,0.04)',
      width: 44,
    }}>
      {ALPHABET.map(L => {
        const has = availableLetters.has(L);
        const isActive = activeLetter === L;
        return (
          <button key={L}
            onClick={() => has && onJump(L)}
            disabled={!has}
            style={{
              width: 28, height: 24, border: 0, background: 'transparent',
              fontFamily: 'JetBrains Mono, monospace',
              fontSize: 12, fontWeight: 700,
              letterSpacing: '0.02em',
              color: !has ? '#D0D5DD' : isActive ? '#fff' : '#475467',
              cursor: has ? 'pointer' : 'default',
              borderRadius: 6,
              transition: 'all 140ms ease',
              backgroundColor: isActive && has ? '#0B1220' : 'transparent',
              margin: '0 auto',
            }}
            onMouseEnter={(e) => { if (has && !isActive) e.currentTarget.style.background = '#F2F4F7'; }}
            onMouseLeave={(e) => { if (has && !isActive) e.currentTarget.style.background = 'transparent'; }}>
            {L}
          </button>
        );
      })}
    </div>
  );
}

// =========================================================
// Floating search — mirrors AZRail (fixed, fades in on scroll)
// =========================================================
function FloatingSearch({ query, setQuery, resultCount, totalCount }) {
  const i18n = window.__useI18n();
  const tr = i18n.t;
  const [visible, setVisible] = useState(false);
  const inputRef = useRef(null);
  useEffect(() => {
    function onScroll() {
      const y = window.scrollY || window.pageYOffset || 0;
      const showAfter = 360;
      const docH = document.documentElement.scrollHeight;
      const winH = window.innerHeight;
      const nearBottom = (y + winH) > (docH - 360);
      setVisible(y > showAfter && !nearBottom);
    }
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('resize', onScroll);
    return () => {
      window.removeEventListener('scroll', onScroll);
      window.removeEventListener('resize', onScroll);
    };
  }, []);

  return (
    <div style={{
      position: 'fixed',
      top: 24,
      left: '50%',
      transform: `translateX(-50%) translateY(${visible ? '0' : '-12px'})`,
      opacity: visible ? 1 : 0,
      pointerEvents: visible ? 'auto' : 'none',
      transition: 'opacity 220ms ease, transform 280ms cubic-bezier(0.16,1,0.3,1)',
      zIndex: 40,
      width: 'min(640px, calc(100vw - 120px))',
    }}>
      <div className="gl-search-wrap" style={{
        position: 'relative',
        display: 'grid', gridTemplateColumns: 'auto 1fr auto auto',
        alignItems: 'center', gap: 14,
        background: 'rgba(255,255,255,0.92)',
        backdropFilter: 'saturate(180%) blur(12px)',
        WebkitBackdropFilter: 'saturate(180%) blur(12px)',
        border: '1px solid #eaecf0',
        borderRadius: 14, padding: '12px 16px',
        boxShadow: '0 6px 20px rgba(16,24,40,0.08), 0 1px 2px rgba(16,24,40,0.04)',
        transition: 'border-color 160ms ease, box-shadow 160ms ease',
      }}>
        <div style={{ color: '#667085', display: 'grid', placeItems: 'center' }}>
          <SearchIcon size={16}/>
        </div>
        <input
          ref={inputRef}
          type="text"
          value={query}
          onChange={(e) => setQuery(e.target.value)}
          placeholder={tr('glossary.search.placeholderShort')}
          style={{
            border: 0, outline: 'none', background: 'transparent',
            fontFamily: 'inherit', fontSize: 14, color: '#0B1220',
            letterSpacing: '-0.005em', width: '100%',
          }}/>
        <div style={{ fontFamily: 'JetBrains Mono, monospace',
          fontSize: 11, fontWeight: 600, color: '#98A2B3',
          letterSpacing: '0.04em', whiteSpace: 'nowrap',
        }}>
          {query
            ? <>{resultCount} / {totalCount}</>
            : tr('glossary.search.totalShort', { n: totalCount })}
        </div>
        <kbd style={{
          fontFamily: 'JetBrains Mono, monospace',
          fontSize: 10.5, fontWeight: 600, color: '#475467',
          background: '#F9FAFB', border: '1px solid #eaecf0',
          padding: '3px 7px', borderRadius: 6, letterSpacing: '0.02em',
        }}>/</kbd>
      </div>
    </div>
  );
}

// =========================================================
// Search bar
// =========================================================
function GlossarySearch({ query, setQuery, resultCount, totalCount, inputRef }) {
  const i18n = window.__useI18n();
  const tr = i18n.t;
  return (
    <div className="gl-search-wrap" style={{
      position: 'relative',
      display: 'grid', gridTemplateColumns: 'auto 1fr auto auto',
      alignItems: 'center', gap: 14,
      background: '#fff', border: '1px solid #d0d5dd',
      borderRadius: 14, padding: '14px 18px',
      boxShadow: '0 1px 2px rgba(16,24,40,0.05)',
      transition: 'border-color 160ms ease, box-shadow 160ms ease',
    }}>
      <div style={{ color: '#667085', display: 'grid', placeItems: 'center' }}>
        <SearchIcon size={18}/>
      </div>
      <input
        ref={inputRef}
        type="text"
        value={query}
        onChange={(e) => setQuery(e.target.value)}
        placeholder={tr('glossary.search.placeholder')}
        style={{
          border: 0, outline: 'none', background: 'transparent',
          fontFamily: 'inherit', fontSize: 15, color: '#0B1220',
          letterSpacing: '-0.005em', width: '100%',
        }}/>
      <div style={{ fontFamily: 'JetBrains Mono, monospace',
        fontSize: 11.5, fontWeight: 600, color: '#98A2B3',
        letterSpacing: '0.04em',
        whiteSpace: 'nowrap',
      }}>
        {query
          ? tr('glossary.search.matches', { n: resultCount, total: totalCount })
          : tr('glossary.search.total', { n: totalCount })}
      </div>
      <kbd style={{
        fontFamily: 'JetBrains Mono, monospace',
        fontSize: 11, fontWeight: 600, color: '#475467',
        background: '#F9FAFB', border: '1px solid #eaecf0',
        padding: '3px 7px', borderRadius: 6, letterSpacing: '0.02em',
      }}>/</kbd>
    </div>
  );
}

// =========================================================
// Main page
// =========================================================
function GlossaryPage() {
  const i18n = window.__useI18n();
  const tr = i18n.t;
  const lang = i18n.lang;
  // Overlay localized def/agNote/tags onto the canonical English term list when
  // the active language has a translation. Term + abbr stay in English on
  // purpose (industry shorthand the trade uses regardless of locale).
  const TERMS = useMemo(
    () => (window.GLOSSARY_TERMS || []).map(t => pickTerm(t, lang)),
    [lang]
  );
  const [query, setQuery] = useState('');
  const [activeLetter, setActiveLetter] = useState('A');
  const inputRef = useRef(null);
  const heroVideoRef = useRef(null);

  // Tweaks
  const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
    "density": "comfortable",
    "groupBy": "letter",
    "showAgNotes": true,
    "showTags": true,
    "accent": "blue"
  }/*EDITMODE-END*/;
  const [tweaks, setTweak] = window.useTweaks(TWEAK_DEFAULTS);

  useEffect(() => { window.applyAccent(tweaks.accent || 'blue'); }, [tweaks.accent]);

  // Replay hero on enter
  const replayHero = () => {
    const v = heroVideoRef.current; if (!v) return;
    try { v.currentTime = 0; } catch {}
    const p = v.play(); if (p && p.catch) p.catch(() => {});
  };

  // Restart hero video whenever it re-enters the viewport
  useEffect(() => {
    const v = heroVideoRef.current; if (!v) return;
    let wasOut = false;
    const io = new IntersectionObserver((entries) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting && entry.intersectionRatio > 0.25) {
          if (wasOut) {
            try { v.currentTime = 0; } catch {}
            const p = v.play(); if (p && p.catch) p.catch(() => {});
            wasOut = false;
          }
        } else if (entry.intersectionRatio === 0) {
          wasOut = true;
          try { v.pause(); } catch {}
        }
      });
    }, { threshold: [0, 0.25, 0.5] });
    io.observe(v);
    return () => io.disconnect();
  }, []);

  // Filter terms
  const filtered = useMemo(() => {
    if (!query.trim()) return TERMS;
    const q = query.trim().toLowerCase();
    return TERMS.filter(t =>
      t.term.toLowerCase().includes(q) ||
      (t.abbr || '').toLowerCase().includes(q) ||
      t.def.toLowerCase().includes(q) ||
      (t.agNote || '').toLowerCase().includes(q) ||
      (t.tags || []).some(tag => tag.toLowerCase().includes(q))
    );
  }, [query, TERMS]);

  // Group by first letter
  const grouped = useMemo(() => {
    const g = {};
    filtered.forEach(t => {
      const L = (t.term[0] || '#').toUpperCase();
      (g[L] = g[L] || []).push(t);
    });
    Object.keys(g).forEach(k => g[k].sort((a, b) => a.term.localeCompare(b.term)));
    return g;
  }, [filtered]);

  const availableLetters = useMemo(() => new Set(Object.keys(grouped)), [grouped]);

  // Smooth-jump to letter
  const jumpToLetter = useCallback((L) => {
    const el = document.getElementById('letter-' + L);
    if (el) { el.scrollIntoView({ behavior: 'smooth', block: 'start' }); }
  }, []);

  // Smooth-jump to term (related-chips)
  const jumpToTerm = useCallback((slug) => {
    setQuery(''); // clear filter so the term is visible
    setTimeout(() => {
      const el = document.getElementById(slug);
      if (el) {
        el.scrollIntoView({ behavior: 'smooth', block: 'start' });
        el.classList.add('gl-flash');
        setTimeout(() => el.classList.remove('gl-flash'), 1400);
        history.replaceState(null, '', '#' + slug);
      }
    }, 50);
  }, []);

  // Jump on initial hash
  useEffect(() => {
    if (location.hash) {
      const slug = location.hash.slice(1);
      setTimeout(() => {
        const el = document.getElementById(slug);
        if (el) el.scrollIntoView({ behavior: 'smooth', block: 'start' });
      }, 200);
    }
  }, []);

  // Active-letter scrollspy
  useEffect(() => {
    if (typeof IntersectionObserver === 'undefined') return;
    const sections = ALPHABET
      .map(L => document.getElementById('letter-' + L))
      .filter(Boolean);
    if (!sections.length) return;
    const io = new IntersectionObserver((entries) => {
      const visible = entries.filter(e => e.isIntersecting);
      if (visible.length) {
        // pick the topmost
        visible.sort((a, b) => a.boundingClientRect.top - b.boundingClientRect.top);
        const id = visible[0].target.id; // letter-X
        setActiveLetter(id.split('-')[1]);
      }
    }, { rootMargin: '-90px 0px -70% 0px', threshold: 0 });
    sections.forEach(s => io.observe(s));
    return () => io.disconnect();
  }, [grouped]);

  // / keyboard shortcut
  useEffect(() => {
    const onKey = (e) => {
      if (e.key === '/' && document.activeElement !== inputRef.current) {
        e.preventDefault();
        inputRef.current?.focus();
      } else if (e.key === 'Escape' && document.activeElement === inputRef.current) {
        setQuery('');
        inputRef.current.blur();
      }
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, []);

  const allTags = useMemo(() => {
    const s = new Set();
    TERMS.forEach(t => (t.tags || []).forEach(tag => s.add(tag)));
    return [...s].sort();
  }, [TERMS]);

  return (
    <div style={{ background: '#fff', color: '#0B1220' }}>
      <window.MobileTopBar homeHref="../Homepage.html"/>
      <ServiceNav/>

      {/* ——— Hero */}
      <section className="gl-hero" style={{
        position: 'relative', overflow: 'hidden',
        background: '#0B1220', minHeight: 580,
        display: 'flex', alignItems: 'flex-end',
        borderBottom: '1px solid #0B1220',
      }}>
        <video ref={heroVideoRef} autoPlay muted playsInline preload="metadata"
          onClick={replayHero}
          style={{ position: 'absolute', inset: 0, width: '100%', height: '100%',
            objectFit: 'cover', zIndex: 0, opacity: 0.55, cursor: 'pointer' }} poster="../assets/posters/glossary.jpg">
          <source src="../uploads/optimized/glossary.mp4" type="video/mp4"/>
        </video>
        <div aria-hidden style={{ position: 'absolute', inset: 0, zIndex: 1,
          background: 'linear-gradient(180deg, rgba(11,18,32,0.4) 0%, rgba(11,18,32,0.55) 50%, rgba(11,18,32,0.95) 100%)' }}/>
        <div aria-hidden style={{ position: 'absolute', inset: 0, zIndex: 1, opacity: 0.18,
          backgroundImage:
            'linear-gradient(rgba(255,255,255,0.18) 1px, transparent 1px),' +
            'linear-gradient(90deg, rgba(255,255,255,0.18) 1px, transparent 1px)',
          backgroundSize: '88px 88px',
          maskImage: 'radial-gradient(ellipse 70% 60% at 50% 60%, #000 30%, transparent 80%)',
          WebkitMaskImage: 'radial-gradient(ellipse 70% 60% at 50% 60%, #000 30%, transparent 80%)' }}/>

        <div style={{ position: 'relative', zIndex: 2, width: '100%',
          maxWidth: 1440, margin: '0 auto', padding: '120px 64px 64px' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between',
            alignItems: 'flex-start', gap: 48, marginBottom: 64 }}>
            <div style={{
              display: 'inline-flex', alignItems: 'center', gap: 10,
              fontFamily: 'JetBrains Mono, monospace',
              fontSize: 12, fontWeight: 600, letterSpacing: '0.16em',
              textTransform: 'uppercase', color: '#93C5FD',
            }}>
              <span style={{ width: 28, height: 1, background: '#60A5FA' }}/>
              {tr('glossary.eyebrow')}
            </div>
            <div style={{
              display: 'inline-flex', alignItems: 'center', gap: 8,
              padding: '8px 14px', borderRadius: 9999,
              background: 'rgba(255,255,255,0.08)',
              border: '1px solid rgba(255,255,255,0.16)',
              backdropFilter: 'blur(10px)',
              fontFamily: 'JetBrains Mono, monospace',
              fontSize: 11, fontWeight: 600, letterSpacing: '0.12em',
              textTransform: 'uppercase', color: 'rgba(255,255,255,0.72)',
            }}>
              <span style={{ width: 6, height: 6, borderRadius: 9999,
                background: '#22C55E', boxShadow: '0 0 0 4px rgba(34,197,94,0.18)' }}/>
              {tr('glossary.badge.curated', { n: TERMS.length })}
            </div>
          </div>
          <h1 style={{
            fontSize: 96, fontWeight: 700, letterSpacing: '-0.045em',
            lineHeight: 0.92, color: '#fff', margin: 0, maxWidth: 1100,
            textShadow: '0 2px 24px rgba(11,18,32,0.35)',
          }}>
            {tr('glossary.hero.line1')}<br/>
            {tr('glossary.hero.line2a')}<em style={{ fontStyle: 'italic',
              backgroundImage: 'linear-gradient(90deg, #93C5FD 0%, #DBEAFE 70%, #fff 100%)',
              WebkitBackgroundClip: 'text', backgroundClip: 'text',
              WebkitTextFillColor: 'transparent' }}>{tr('glossary.hero.line2b')}</em>
          </h1>

          <div style={{
            marginTop: 48, paddingTop: 28,
            borderTop: '1px solid rgba(255,255,255,0.14)',
            display: 'grid', gridTemplateColumns: '1fr auto', gap: 64, alignItems: 'end',
          }}>
            <p style={{ margin: 0, fontSize: 17, lineHeight: 1.55,
              color: 'rgba(255,255,255,0.78)', letterSpacing: '-0.005em',
              maxWidth: 560 }}>
              {tr('glossary.hero.lead')}
            </p>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, auto)', gap: 48 }}>
              {[
                { v: TERMS.length, l: tr('glossary.stat.terms') },
                { v: '7', l: tr('glossary.stat.modes') },
                { v: '01/26', l: tr('glossary.stat.reviewed') },
              ].map(s => (
                <div key={s.l}>
                  <div style={{ fontFamily: 'JetBrains Mono, monospace',
                    fontSize: 36, fontWeight: 700, letterSpacing: '-0.025em',
                    color: '#fff', lineHeight: 1, fontVariantNumeric: 'tabular-nums' }}>
                    {s.v}
                  </div>
                  <div style={{ fontSize: 12, color: 'rgba(255,255,255,0.6)',
                    lineHeight: 1.4, marginTop: 10, letterSpacing: '-0.005em',
                    maxWidth: 160 }}>{s.l}</div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </section>

      {/* ——— Search bar (in-flow, at top of content) */}
      <section style={{ background: '#fff',
        borderBottom: '1px solid #eaecf0',
        padding: '20px 64px',
      }}>
        <div style={{ maxWidth: 1200, margin: '0 auto' }}>
          <GlossarySearch
            query={query} setQuery={setQuery}
            resultCount={filtered.length} totalCount={TERMS.length}
            inputRef={inputRef}/>
        </div>
      </section>

      {/* ——— Floating search — follows scroll just like the A-Z rail */}
      <FloatingSearch
        query={query} setQuery={setQuery}
        resultCount={filtered.length} totalCount={TERMS.length}/>

      {/* ——— Main: A-Z rail + content */}
      <div style={{ background: '#fff', position: 'relative' }}>
        <section style={{ background: '#fff', padding: '64px 64px 120px' }}>
          <div style={{ maxWidth: 1200, margin: '0 auto',
            alignItems: 'flex-start' }}>
            <AZRail
              availableLetters={availableLetters}
              activeLetter={activeLetter}
              onJump={jumpToLetter}/>

          <div style={{ minWidth: 0 }}>
            {filtered.length === 0 ? (
              <div style={{ padding: '80px 0', textAlign: 'center' }}>
                <div style={{ fontFamily: 'JetBrains Mono, monospace',
                  fontSize: 11, fontWeight: 600, letterSpacing: '0.16em',
                  textTransform: 'uppercase', color: '#98A2B3' }}>{tr('glossary.empty.kicker')}</div>
                <h3 style={{ margin: '14px 0 10px', fontSize: 28, fontWeight: 700,
                  letterSpacing: '-0.025em', color: '#0B1220' }}>
                  {tr('glossary.empty.title', { q: query })}
                </h3>
                <p style={{ margin: 0, fontSize: 15, color: '#667085' }}>
                  {tr('glossary.empty.lead')}
                </p>
                <button onClick={() => setQuery('')}
                  style={{ marginTop: 28, padding: '10px 18px',
                    background: '#0B1220', color: '#fff', border: 0, borderRadius: 8,
                    fontFamily: 'inherit', fontSize: 14, fontWeight: 600,
                    cursor: 'pointer' }}>
                  {tr('glossary.empty.clear')}
                </button>
              </div>
            ) : (
              ALPHABET.filter(L => grouped[L]).map(L => (
                <LetterSection key={L} letter={L}
                  terms={grouped[L]} query={query}
                  density={tweaks.density}
                  showAgNotes={tweaks.showAgNotes}
                  showTags={tweaks.showTags}
                  onJumpTo={jumpToTerm}/>
              ))
            )}
          </div>
        </div>
        </section>
      </div>

      {/* ——— Bottom CTA */}
      <section style={{ background: '#F9FAFB', borderTop: '1px solid #eef0f3',
        padding: '80px 64px' }}>
        <div style={{ maxWidth: 1200, margin: '0 auto',
          display: 'grid', gridTemplateColumns: '1fr auto', gap: 48,
          alignItems: 'center' }}>
          <div>
            <div style={{ fontFamily: 'JetBrains Mono, monospace',
              fontSize: 11, fontWeight: 600, letterSpacing: '0.16em',
              textTransform: 'uppercase', color: '#1846B0',
              marginBottom: 14 }}>
              {tr('glossary.cta.kicker')}
            </div>
            <h2 style={{ margin: 0, fontSize: 36, fontWeight: 700,
              letterSpacing: '-0.025em', lineHeight: 1.1, color: '#0B1220' }}>
              {tr('glossary.cta.title')}
            </h2>
            <p style={{ margin: '12px 0 0', fontSize: 15.5, color: '#667085',
              lineHeight: 1.55, letterSpacing: '-0.005em', maxWidth: 600 }}>
              {tr('glossary.cta.lead')}
            </p>
          </div>
          <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap' }}>
            <a href="../Homepage.html#hero-quote"
              onClick={(e) => { e.preventDefault();
                window.__abgsCTA && window.__abgsCTA.openContact('glossary-talk',
                  { intent: 'specialist', topic: 'Glossary' }); }}
              style={{ display: 'inline-flex', alignItems: 'center', gap: 8,
                padding: '14px 22px', background: '#1846B0', color: '#fff',
                borderRadius: 10, textDecoration: 'none',
                fontSize: 14, fontWeight: 600 }}>
              {tr('glossary.cta.specialist')} <Icon name="arrowRight" size={12}/>
            </a>
            <a href="compliance-certification.html"
              style={{ display: 'inline-flex', alignItems: 'center', gap: 8,
                padding: '14px 22px', background: '#fff', color: '#0B1220',
                border: '1px solid #d0d5dd',
                borderRadius: 10, textDecoration: 'none',
                fontSize: 14, fontWeight: 600 }}>
              {tr('glossary.cta.licenses')}
            </a>
          </div>
        </div>
      </section>

      <ServiceFooter/>
      <window.MobileTabBar current="home"/>

      {/* ——— Tweaks panel */}
      <window.TweaksPanel title={tr('glossary.tweaks.title')}>
        <window.TweakSection label={tr('glossary.tweaks.layout')}/>
        <window.TweakRadio label={tr('glossary.tweaks.density')} value={tweaks.density}
          options={['compact', 'comfortable', 'spacious']}
          onChange={(v) => setTweak('density', v)}/>
        <window.TweakToggle label={tr('glossary.tweaks.tags')} value={tweaks.showTags}
          onChange={(v) => setTweak('showTags', v)}/>
        <window.TweakToggle label={tr('glossary.tweaks.notes')} value={tweaks.showAgNotes}
          onChange={(v) => setTweak('showAgNotes', v)}/>

        <window.TweakSection label={tr('glossary.tweaks.theme')}/>
        <window.TweakRadio label={tr('glossary.tweaks.accent')} value={tweaks.accent}
          options={['blue', 'indigo', 'amber', 'green']}
          onChange={(v) => setTweak('accent', v)}/>

        <window.TweakSection label={tr('glossary.tweaks.search')}/>
        <window.TweakButton label={tr('glossary.tweaks.focus')}
          onClick={() => inputRef.current?.focus()}/>
      </window.TweaksPanel>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<GlossaryPage/>);
