(() => {
  const root = document.documentElement;
  root.classList.add('js');

  // Motion prefs
  const reduced = window.matchMedia?.('(prefers-reduced-motion: reduce)')?.matches ?? false;
  const hoverFine = window.matchMedia?.('(hover: hover) and (pointer: fine)')?.matches ?? false;

  // Ensure page is visible ASAP (for page transitions)
  const markReady = () => document.body.classList.add('page-ready');
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', markReady, { once: true });
  } else {
    markReady();
  }

  // Theme
  const mediaDark = window.matchMedia?.('(prefers-color-scheme: dark)');
  const stored = localStorage.getItem('mvg-theme');
  const initialTheme = stored || (mediaDark?.matches ? 'dark' : 'light');
  root.dataset.theme = initialTheme;

  function setTheme(next){
    root.dataset.theme = next;
    localStorage.setItem('mvg-theme', next);
    document.querySelectorAll('[data-theme-toggle]').forEach(btn => {
      btn.setAttribute('aria-label', next === 'dark' ? 'Switch to light mode' : 'Switch to dark mode');
    });
  }

  document.querySelectorAll('[data-theme-toggle]').forEach(btn => {
    btn.addEventListener('click', () => {
      const next = root.dataset.theme === 'dark' ? 'light' : 'dark';
      setTheme(next);
      toast(`${next === 'dark' ? 'Dark' : 'Light'} mode`);
    });
  });

  // Year in footer
  document.querySelectorAll('[data-year]').forEach(el => {
    el.textContent = String(new Date().getFullYear());
  });

  // Active nav link (best-prefix match)
  (() => {
    const current = (location.pathname.endsWith('/') ? location.pathname : location.pathname + '/');
    const links = [...document.querySelectorAll('[data-nav-link]')];
    let best = null;
    let bestLen = -1;

    links.forEach(a => {
      const href = a.getAttribute('data-nav-link');
      if (!href) return;
      const match = (href === '/')
        ? (current === '/')
        : current.startsWith(href);

      if (match && href.length > bestLen){
        best = a;
        bestLen = href.length;
      }
    });

    if (best){
      best.classList.add('active');
      best.setAttribute('aria-current', 'page');
    }
  })();

  // Mobile nav
  const nav = document.querySelector('.nav');
  const toggle = document.querySelector('[data-nav-toggle]');
  if (nav && toggle){
    toggle.addEventListener('click', () => {
      const open = nav.classList.toggle('open');
      toggle.setAttribute('aria-expanded', open ? 'true' : 'false');
    });

    // Close on navigation
    nav.querySelectorAll('.nav-links a').forEach(a => {
      a.addEventListener('click', () => nav.classList.remove('open'));
    });
  }


  
// Language switcher disabled (EN-only for now)
(() => {
  const wrap = document.querySelector('[data-lang-switch]');
  if (wrap) wrap.remove();
})();


  // Cinematic background (Apple-grade, still subtle)
  if (!reduced){
    const bg = document.createElement('div');
    bg.className = 'bg-float';
    bg.setAttribute('aria-hidden', 'true');
    document.body.prepend(bg);
  }

  // Cursor glow (only on pointer-fine devices)
  if (!reduced && hoverFine){
    const glow = document.createElement('div');
    glow.className = 'cursor-glow';
    glow.setAttribute('aria-hidden', 'true');
    document.body.appendChild(glow);

    let gx = window.innerWidth * 0.55;
    let gy = window.innerHeight * 0.18;
    let raf = null;

    const update = () => {
      root.style.setProperty('--gx', `${gx}px`);
      root.style.setProperty('--gy', `${gy}px`);
      raf = null;
    };

    window.addEventListener('pointermove', (e) => {
      gx = e.clientX;
      gy = e.clientY;
      if (raf) return;
      raf = requestAnimationFrame(update);
    }, { passive: true });

    update();
  }

  // Inject hero "evidence spine" line (SVG) for every hero section
  (() => {
    const heroes = [...document.querySelectorAll('.hero')];
    if (!heroes.length) return;

    heroes.forEach((hero, i) => {
      if (hero.querySelector('.hero-spine')) return;

      const gradId = `spineGrad_${i}`;
      const spine = document.createElement('div');
      spine.className = 'hero-spine';
      spine.setAttribute('aria-hidden', 'true');

      spine.innerHTML = `
        <svg viewBox="0 0 1100 120" preserveAspectRatio="none" role="presentation">
          <defs>
            <linearGradient id="${gradId}" x1="0" y1="0" x2="1100" y2="0" gradientUnits="userSpaceOnUse">
              <stop offset="0" stop-color="#43D3FF" stop-opacity="0"/>
              <stop offset="0.18" stop-color="#43D3FF" stop-opacity="0.85"/>
              <stop offset="0.50" stop-color="#7C5CFF" stop-opacity="1"/>
              <stop offset="0.82" stop-color="#43D3FF" stop-opacity="0.85"/>
              <stop offset="1" stop-color="#43D3FF" stop-opacity="0"/>
            </linearGradient>
          </defs>

          <path class="spine-path spine-glow" d="M20 72 C 80 72 90 72 120 72 C 210 72 250 44 340 44 C 430 44 480 72 560 72 C 640 72 690 44 780 44 C 870 44 920 72 1000 72 C 1040 72 1060 72 1080 72" stroke="url(#${gradId})"/>
          <path class="spine-path spine-base spine-draw" d="M20 72 C 80 72 90 72 120 72 C 210 72 250 44 340 44 C 430 44 480 72 560 72 C 640 72 690 44 780 44 C 870 44 920 72 1000 72 C 1040 72 1060 72 1080 72" stroke="url(#${gradId})"/>
          <path class="spine-path spine-base spine-dash" d="M20 72 C 80 72 90 72 120 72 C 210 72 250 44 340 44 C 430 44 480 72 560 72 C 640 72 690 44 780 44 C 870 44 920 72 1000 72 C 1040 72 1060 72 1080 72" stroke="url(#${gradId})"/>

          <!-- Nodes -->
          <circle class="spine-node" cx="120" cy="72" r="3.4"/>
          <circle class="spine-node" cx="340" cy="44" r="3.4"/>
          <circle class="spine-node" cx="560" cy="72" r="3.4"/>
          <circle class="spine-node" cx="780" cy="44" r="3.4"/>
          <circle class="spine-node" cx="1000" cy="72" r="3.4"/>

          <circle class="spine-ring spine-pulse" cx="120" cy="72" r="11" style="animation-delay: .10s"/>
          <circle class="spine-ring spine-pulse" cx="340" cy="44" r="11" style="animation-delay: .55s"/>
          <circle class="spine-ring spine-pulse" cx="560" cy="72" r="11" style="animation-delay: 1.05s"/>
          <circle class="spine-ring spine-pulse" cx="780" cy="44" r="11" style="animation-delay: 1.55s"/>
          <circle class="spine-ring spine-pulse" cx="1000" cy="72" r="11" style="animation-delay: 2.05s"/>
        </svg>

        <div class="spine-labels">
          <span>Policy</span>
          <span>Validator</span>
          <span>Receipts</span>
          <span>Permit</span>
          <span>Gate</span>
        </div>
      `.trim();

      hero.prepend(spine);
    });
  })();

  // Reveal on scroll
  if (!reduced && 'IntersectionObserver' in window){
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => {
        if (e.isIntersecting){
          e.target.classList.add('in');
          io.unobserve(e.target);
        }
      });
    }, { rootMargin: '0px 0px -8% 0px', threshold: 0.12 });

    document.querySelectorAll('.reveal').forEach(el => io.observe(el));
  } else {
    document.querySelectorAll('.reveal').forEach(el => el.classList.add('in'));
  }


  // Evidence spine: clickable + scroll-synchronized highlight (procurement-grade, no gimmicks)
  (() => {
    const card = document.querySelector('.hero-right');
    if (!card || reduced) return;

    const hero = card.closest('.hero');
    const steps = [...card.querySelectorAll('[data-spine-step]')];
    if (!steps.length) return;

    const ledeEl = card.querySelector('[data-spine-lede]');

    const lede = {
      verify: 'Prove prerequisites before action — policy + evidence pinned.',
      permit: 'Signed, scoped, expiring authorization — auditable by design.',
      gate: 'Fail‑closed enforcement at non‑bypassable control points.',
      receipts: 'Export attachables (PDF + JSON) for Security, Counsel, and audit.'
    };

    let locked = false;

    const setActive = (key) => {
      steps.forEach(s => {
        const on = s.getAttribute('data-spine-step') === key;
        s.classList.toggle('active', on);
        // Button semantics
        s.setAttribute('aria-pressed', on ? 'true' : 'false');
      });
      if (ledeEl && lede[key]) ledeEl.textContent = lede[key];
      if (hero && key) hero.setAttribute('data-spine-active', key);
    };

    // Default
    setActive('verify');

    // Click-to-highlight (locks until the user scrolls)
    steps.forEach((s, idx) => {
      s.addEventListener('click', () => {
        const key = s.getAttribute('data-spine-step');
        if (!key) return;
        locked = true;
        setActive(key);
      });

      // Arrow key navigation for reviewers
      s.addEventListener('keydown', (e) => {
        const k = e.key;
        if (!['ArrowDown','ArrowUp','ArrowLeft','ArrowRight'].includes(k)) return;
        e.preventDefault();
        const dir = (k === 'ArrowDown' || k === 'ArrowRight') ? 1 : -1;
        const next = (idx + dir + steps.length) % steps.length;
        const el = steps[next];
        const key = el.getAttribute('data-spine-step');
        locked = true;
        if (key) setActive(key);
        el.focus();
      });
    });

    window.addEventListener('scroll', () => { locked = false; }, { passive: true });

    // Scroll sync (when not locked)
    const markers = [...document.querySelectorAll('[data-spine-target]')];
    if (!markers.length || !('IntersectionObserver' in window)) return;

    const io = new IntersectionObserver((entries) => {
      if (locked) return;
      const visible = entries
        .filter(e => e.isIntersecting)
        .sort((a,b) => (b.intersectionRatio - a.intersectionRatio));
      if (!visible.length) return;
      const key = visible[0].target.getAttribute('data-spine-target');
      if (key) setActive(key);
    }, { threshold: [0.15, 0.25, 0.45, 0.65], rootMargin: '-10% 0px -55% 0px' });

    markers.forEach(m => io.observe(m));
  })();


  // Copy buttons
  document.querySelectorAll('[data-copy]').forEach(btn => {
    btn.addEventListener('click', async () => {
      const text = btn.getAttribute('data-copy') || '';
      try{
        await navigator.clipboard.writeText(text);
        toast('Copied');
      } catch {
        const ta = document.createElement('textarea');
        ta.value = text;
        ta.style.position = 'fixed';
        ta.style.left = '-9999px';
        document.body.appendChild(ta);
        ta.focus();
        ta.select();
        document.execCommand('copy');
        ta.remove();
        toast('Copied');
      }
    });
  });


  // Contact mailto-draft form (no backend)
  (() => {
    const form = document.querySelector('[data-mailto-form]');
    if (!form) return;
    const preview = form.querySelector('[data-draft-preview]');
    const btnCopy = form.querySelector('[data-copy-draft]');
    const to = 'security@meridianverity.com';
    const subject = 'Meridian Verity Group — security deep dive';

    const gather = () => {
      const get = (n) => (form.querySelector(`[name="${n}"]`)?.value || '').trim();
      const lines = [
        `Name: ${get('name') || '—'}`,
        `Company: ${get('company') || '—'}`,
        `Role: ${get('role') || '—'}`,
        `Region: ${get('region') || '—'}`,
        ``,
        `Highest-risk action surface: ${get('surface') || '—'}`,
        `Evidence consumer: ${get('consumer') || '—'}`,
        ``,
        `Message:`,
        `${get('note') || '—'}`,
        ``,
        `Preferred next step:`,
        `• 30-minute security-attended deep dive`,
        `• Map control point and define evidence acceptance criteria`,
      ];
      return lines.join('\n');
    };

    const updatePreview = () => {
      const body = gather();
      if (preview) preview.value = body;
      return body;
    };

    form.addEventListener('input', updatePreview, { passive: true });
    updatePreview();

    form.addEventListener('submit', (e) => {
      e.preventDefault();
      const body = updatePreview();
      const href = `mailto:${to}?subject=${encodeURIComponent(subject)}&body=${encodeURIComponent(body)}`;
      window.location.href = href;
    });

    if (btnCopy){
      btnCopy.addEventListener('click', async () => {
        const text = updatePreview();
        try{
          await navigator.clipboard.writeText(text);
          toast('Draft copied');
        } catch {
          toast('Copy failed');
        }
      });
    }
  })();


  // Smooth anchor scroll (only if motion allowed)
  if (!reduced){
    document.querySelectorAll('a[href^="#"]').forEach(a => {
      a.addEventListener('click', (e) => {
        const id = a.getAttribute('href');
        if (!id || id.length < 2) return;
        const el = document.querySelector(id);
        if (!el) return;
        e.preventDefault();
        el.scrollIntoView({behavior:'smooth', block:'start'});
        history.pushState(null, '', id);
      });
    });
  }

  // Micro parallax (optional; used in hero/right cards)
  const parallax = document.querySelector('[data-parallax]');
  if (!reduced && parallax){
    let raf = null;
    const onMove = (ev) => {
      const rect = parallax.getBoundingClientRect();
      const x = (ev.clientX - rect.left) / rect.width - 0.5;
      const y = (ev.clientY - rect.top) / rect.height - 0.5;
      if (raf) cancelAnimationFrame(raf);
      raf = requestAnimationFrame(() => {
        parallax.style.transform = `translate3d(${x * 10}px, ${y * 10}px, 0)`;
      });
    };
    parallax.addEventListener('mousemove', onMove);
    parallax.addEventListener('mouseleave', () => parallax.style.transform = 'translate3d(0,0,0)');
  }

  // Tilt depth (Apple-like hover depth, no bloat)
  if (!reduced && hoverFine){
    const bindTilt = (el, maxX = 8, maxY = 10) => {
      let rect = null;
      let raf = null;
      let lx = 0, ly = 0;

      const update = () => {
        if (!rect) rect = el.getBoundingClientRect();
        const x = (lx - rect.left) / rect.width - 0.5;
        const y = (ly - rect.top) / rect.height - 0.5;

        el.style.setProperty('--rx', `${(-y * maxX).toFixed(2)}deg`);
        el.style.setProperty('--ry', `${(x * maxY).toFixed(2)}deg`);
        el.style.setProperty('--mx', `${(x + 0.5) * 100}%`);
        el.style.setProperty('--my', `${(y + 0.5) * 100}%`);
        raf = null;
      };

      const onMove = (e) => {
        lx = e.clientX;
        ly = e.clientY;
        if (raf) return;
        raf = requestAnimationFrame(update);
      };

      const onEnter = () => {
        rect = el.getBoundingClientRect();
        el.classList.add('tilting');
      };

      const onLeave = () => {
        el.classList.remove('tilting');
        el.style.removeProperty('--rx');
        el.style.removeProperty('--ry');
        el.style.removeProperty('--mx');
        el.style.removeProperty('--my');
        rect = null;
        if (raf){ cancelAnimationFrame(raf); raf = null; }
      };

      el.addEventListener('mouseenter', onEnter);
      el.addEventListener('mousemove', onMove);
      el.addEventListener('mouseleave', onLeave);
      window.addEventListener('resize', () => { rect = null; }, { passive: true });
    };

    document.querySelectorAll('.card').forEach(el => bindTilt(el, 7.5, 10));
    document.querySelectorAll('.hero-right').forEach(el => bindTilt(el, 5.5, 7));
    document.querySelectorAll('.callout').forEach(el => bindTilt(el, 4.5, 6));
  }

  // Active subnav highlighting (when present)
  const subnav = document.querySelector('.subnav');
  if (subnav){
    const links = [...subnav.querySelectorAll('a[href^="#"]')];
    const sections = links.map(a => document.querySelector(a.getAttribute('href'))).filter(Boolean);
    if (!reduced && sections.length && 'IntersectionObserver' in window){
      const map = new Map();
      sections.forEach((sec, i) => map.set(sec, links[i]));
      const io2 = new IntersectionObserver((entries) => {
        entries.forEach(e => {
          if (e.isIntersecting){
            links.forEach(l => l.classList.remove('active'));
            map.get(e.target)?.classList.add('active');
          }
        });
      }, {rootMargin:'-20% 0px -70% 0px', threshold: 0.02});
      sections.forEach(sec => io2.observe(sec));
    }
  }

  // Toast
  const toastEl = (() => {
    const t = document.createElement('div');
    t.className = 'toast';
    t.setAttribute('role', 'status');
    t.setAttribute('aria-live', 'polite');
    document.body.appendChild(t);
    return t;
  })();
  let toastTimer = null;

  function toast(msg){
    toastEl.textContent = msg;
    toastEl.classList.add('show');
    if (toastTimer) clearTimeout(toastTimer);
    toastTimer = setTimeout(() => toastEl.classList.remove('show'), 1300);
  }


  // Accessibility panel (neighbor-first, local-only, no tracking)
  (() => {
    const KEY = 'mvg-a11y';
    const defaults = {
      scale: 1,
      line: 'normal',      // normal | spacious | extra
      spacing: 'standard', // standard | expanded
      width: 'default',    // default | narrow
      contrast: 'default', // default | high | low
      underline: true,     // links underlined
      clean: false,
      focus: 'thick',      // thick | xthick
      motion: 'system',    // system | on | off  (on = reduce motion)
      targets: false
    };

    const load = () => {
      try{
        const raw = localStorage.getItem(KEY);
        if (!raw) return { ...defaults };
        const obj = JSON.parse(raw);
        return { ...defaults, ...obj };
      } catch {
        return { ...defaults };
      }
    };

    const save = (s) => {
      try{ localStorage.setItem(KEY, JSON.stringify(s)); } catch {}
    };

    const state = load();

    const apply = (s) => {
      root.style.setProperty('--a11y-scale', String(s.scale || 1));
      root.dataset.a11yLine = s.line || 'normal';
      root.dataset.a11yContrast = s.contrast || 'default';

      root.classList.toggle('a11y-narrow', (s.width === 'narrow'));
      root.classList.toggle('a11y-no-underline', !s.underline);
      root.classList.toggle('a11y-clean', !!s.clean);
      root.classList.toggle('a11y-targets', !!s.targets);
      root.classList.toggle('a11y-spacing-expanded', (s.spacing === 'expanded'));

      root.classList.toggle('a11y-focus-xthick', (s.focus === 'xthick'));
      root.classList.toggle('a11y-focus-thick', (s.focus !== 'xthick'));

      const reduce = (s.motion === 'on') || (s.motion === 'system' && reduced);
      root.classList.toggle('a11y-reduce-motion', !!reduce);
    };

    apply(state);

    // Inject only once
    if (document.querySelector('[data-a11y-fab]')) return;

    const fab = document.createElement('button');
    fab.className = 'a11y-fab';
    fab.type = 'button';
    fab.setAttribute('data-a11y-fab', '');
    fab.setAttribute('aria-haspopup', 'dialog');
    fab.setAttribute('aria-expanded', 'false');
    fab.setAttribute('aria-label', 'Accessibility settings');
    fab.innerHTML = `
      <span class="a11y-fab-ic" aria-hidden="true">⌘</span>
      <span class="a11y-fab-txt">Accessibility</span>
    `.trim();

    const overlay = document.createElement('div');
    overlay.className = 'a11y-overlay';
    overlay.setAttribute('data-a11y-overlay', '');
    overlay.innerHTML = `
      <div class="a11y-panel" role="dialog" aria-modal="true" aria-label="Accessibility controls" tabindex="-1">
        <div class="a11y-panel-head">
          <div>
            <div class="pill"><span class="dot"></span> Neighbor first</div>
            <h3 style="margin-top:10px">Accessibility</h3>
            <p style="margin-top:8px; color: var(--muted); max-width:60ch">
              Make this site comfortable to use.<br/>
              We don’t track you. Settings stay on your device.
            </p>
          </div>
          <button class="btn icon-btn" type="button" data-a11y-close aria-label="Close">
            <svg viewBox="0 0 24 24" fill="none" aria-hidden="true">
              <path d="M7 7l10 10M17 7L7 17" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
            </svg>
          </button>
        </div>

        <div class="a11y-controls">
          <div class="a11y-row">
            <div class="a11y-label">Text size</div>
            <div class="a11y-seg" data-a11y-group="scale">
              <button type="button" class="seg" data-a11y="scale" data-val="1">100%</button>
              <button type="button" class="seg" data-a11y="scale" data-val="1.1">110%</button>
              <button type="button" class="seg" data-a11y="scale" data-val="1.25">125%</button>
              <button type="button" class="seg" data-a11y="scale" data-val="1.5">150%</button>
              <button type="button" class="seg" data-a11y="scale" data-val="1.75">175%</button>
            </div>
          </div>

          <div class="a11y-row">
            <div class="a11y-label">Line height</div>
            <div class="a11y-seg" data-a11y-group="line">
              <button type="button" class="seg" data-a11y="line" data-val="normal">Normal</button>
              <button type="button" class="seg" data-a11y="line" data-val="spacious">Spacious</button>
              <button type="button" class="seg" data-a11y="line" data-val="extra">Extra</button>
            </div>
          </div>

          <div class="a11y-row">
            <div class="a11y-label">Text spacing</div>
            <div class="a11y-seg" data-a11y-group="spacing">
              <button type="button" class="seg" data-a11y="spacing" data-val="standard">Standard</button>
              <button type="button" class="seg" data-a11y="spacing" data-val="expanded">Expanded</button>
            </div>
          </div>

          <div class="a11y-row">
            <div class="a11y-label">Reading width</div>
            <div class="a11y-seg" data-a11y-group="width">
              <button type="button" class="seg" data-a11y="width" data-val="default">Default</button>
              <button type="button" class="seg" data-a11y="width" data-val="narrow">Narrow</button>
            </div>
          </div>

          <div class="a11y-row">
            <div class="a11y-label">Contrast</div>
            <div class="a11y-seg" data-a11y-group="contrast">
              <button type="button" class="seg" data-a11y="contrast" data-val="default">Default</button>
              <button type="button" class="seg" data-a11y="contrast" data-val="high">High</button>
              <button type="button" class="seg" data-a11y="contrast" data-val="low">Low glare</button>
            </div>
          </div>

          <div class="a11y-row">
            <div class="a11y-label">Underline links</div>
            <div class="a11y-seg" data-a11y-group="underline">
              <button type="button" class="seg" data-a11y="underline" data-val="on">On</button>
              <button type="button" class="seg" data-a11y="underline" data-val="off">Off</button>
            </div>
          </div>

          <div class="a11y-row">
            <div class="a11y-label">Clean mode</div>
            <div class="a11y-seg" data-a11y-group="clean">
              <button type="button" class="seg" data-a11y="clean" data-val="off">Off</button>
              <button type="button" class="seg" data-a11y="clean" data-val="on">On</button>
            </div>
          </div>

          <div class="a11y-row">
            <div class="a11y-label">Focus ring</div>
            <div class="a11y-seg" data-a11y-group="focus">
              <button type="button" class="seg" data-a11y="focus" data-val="thick">Thick</button>
              <button type="button" class="seg" data-a11y="focus" data-val="xthick">Extra thick</button>
            </div>
          </div>

          <div class="a11y-row">
            <div class="a11y-label">Reduce motion</div>
            <div class="a11y-seg" data-a11y-group="motion">
              <button type="button" class="seg" data-a11y="motion" data-val="system">System</button>
              <button type="button" class="seg" data-a11y="motion" data-val="on">On</button>
              <button type="button" class="seg" data-a11y="motion" data-val="off">Off</button>
            </div>
          </div>

          <div class="a11y-row">
            <div class="a11y-label">Large targets</div>
            <div class="a11y-seg" data-a11y-group="targets">
              <button type="button" class="seg" data-a11y="targets" data-val="off">Off</button>
              <button type="button" class="seg" data-a11y="targets" data-val="on">On</button>
            </div>
          </div>

          <div class="hr" style="margin:14px 0"></div>

          <div class="a11y-actions">
            <a class="btn" href="#" data-a11y-about>About accessibility</a>
            <button class="btn" type="button" data-a11y-reset>Reset</button>
            <button class="btn primary" type="button" data-a11y-done>Done</button>
          </div>

          <p class="form-hint" style="margin-top:10px">
            Privacy: settings are stored locally (localStorage). No cookies required.
          </p>
        </div>
      </div>
    `.trim();

    document.body.appendChild(fab);
    document.body.appendChild(overlay);
    // Localize the “About accessibility” link based on language prefix
    const about = overlay.querySelector('[data-a11y-about]');
    if (about){
      const p = (location.pathname.split('/')[1] || '').toLowerCase();
      const pref = ['kr','de','jp','zh','en'].includes(p) ? `/${p}` : '';
      about.setAttribute('href', `${pref}/accessibility/`);
    }


    const panel = overlay.querySelector('.a11y-panel');
    const btnClose = overlay.querySelector('[data-a11y-close]');
    const btnDone = overlay.querySelector('[data-a11y-done]');
    const btnReset = overlay.querySelector('[data-a11y-reset]');

    let lastActive = null;

    const open = () => {
      lastActive = document.activeElement;
      overlay.classList.add('open');
      document.body.classList.add('a11y-open');
      fab.setAttribute('aria-expanded','true');
      // sync UI
      syncUI();
      setTimeout(() => panel.focus(), 0);
    };

    const close = () => {
      overlay.classList.remove('open');
      document.body.classList.remove('a11y-open');
      fab.setAttribute('aria-expanded','false');
      if (lastActive && typeof lastActive.focus === 'function') lastActive.focus();
    };

    const syncUI = () => {
      overlay.querySelectorAll('[data-a11y]').forEach(b => {
        const key = b.getAttribute('data-a11y');
        const val = b.getAttribute('data-val');
        let active = false;

        if (key === 'scale') active = String(state.scale) === String(val);
        else if (key === 'line') active = state.line === val;
        else if (key === 'spacing') active = state.spacing === val;
        else if (key === 'width') active = state.width === val;
        else if (key === 'contrast') active = state.contrast === val;
        else if (key === 'underline') active = (state.underline ? 'on' : 'off') === val;
        else if (key === 'clean') active = (state.clean ? 'on' : 'off') === val;
        else if (key === 'focus') active = state.focus === val;
        else if (key === 'motion') active = state.motion === val;
        else if (key === 'targets') active = (state.targets ? 'on' : 'off') === val;

        b.classList.toggle('active', active);
        b.setAttribute('aria-pressed', active ? 'true' : 'false');
      });
    };

    const update = (key, val) => {
      if (key === 'scale') state.scale = parseFloat(val) || 1;
      else if (key === 'line') state.line = val;
      else if (key === 'spacing') state.spacing = val;
      else if (key === 'width') state.width = val;
      else if (key === 'contrast') state.contrast = val;
      else if (key === 'underline') state.underline = (val === 'on');
      else if (key === 'clean') state.clean = (val === 'on');
      else if (key === 'focus') state.focus = val;
      else if (key === 'motion') state.motion = val;
      else if (key === 'targets') state.targets = (val === 'on');

      apply(state);
      save(state);
      syncUI();
    };

    overlay.addEventListener('click', (e) => {
      if (e.target === overlay) close();
    });

    fab.addEventListener('click', (e) => {
      e.preventDefault();
      open();
    });

    btnClose.addEventListener('click', close);
    btnDone.addEventListener('click', close);

    btnReset.addEventListener('click', () => {
      Object.assign(state, defaults);
      apply(state);
      save(state);
      syncUI();
      toast('Accessibility reset');
    });

    overlay.querySelectorAll('[data-a11y]').forEach(b => {
      b.addEventListener('click', () => {
        update(b.getAttribute('data-a11y'), b.getAttribute('data-val'));
      });
    });

    // Trap focus in dialog
    overlay.addEventListener('keydown', (e) => {
      if (!overlay.classList.contains('open')) return;
      if (e.key === 'Escape') { e.preventDefault(); close(); return; }

      if (e.key === 'Tab'){
        const focusables = overlay.querySelectorAll('a[href], button:not([disabled]), input, textarea, select, [tabindex]:not([tabindex="-1"])');
        const list = [...focusables].filter(el => el.offsetParent !== null);
        if (!list.length) return;
        const first = list[0];
        const last = list[list.length - 1];
        if (e.shiftKey && document.activeElement === first){
          e.preventDefault(); last.focus();
        } else if (!e.shiftKey && document.activeElement === last){
          e.preventDefault(); first.focus();
        }
      }
    });
  })();


  // Accessibility forms (mailto draft; fail-closed UX; no backend)
  (() => {
    const forms = [...document.querySelectorAll('form[data-a11y-mailto]')];
    if (!forms.length) return;

    const to = 'privacy@meridianverity.com';
    const isEmail = (s) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(String(s || '').trim());
    const isUrl = (s) => {
      const v = String(s || '').trim();
      if (!v) return false;
      if (v.startsWith('/')) return true;
      return /^https?:\/\/[^\s]+$/i.test(v);
    };

    const setStatus = (form, msg, ok = true) => {
      const el = form.querySelector('[data-a11y-status]');
      if (!el) return;
      el.textContent = msg || '';
      el.classList.toggle('ok', !!ok);
      el.classList.toggle('bad', !ok);
    };

    const clearErrors = (form) => {
      form.querySelectorAll('.field-error').forEach(e => e.textContent = '');
      form.querySelectorAll('[aria-invalid="true"]').forEach(el => el.removeAttribute('aria-invalid'));
      setStatus(form, '');
    };

    const setErr = (form, name, msg) => {
      const el = form.querySelector(`[data-error-for="${name}"]`);
      if (el) el.textContent = msg;
      const input = form.querySelector(`[name="${name}"]`);
      if (input) input.setAttribute('aria-invalid', 'true');
    };

    const gatherFormats = (form) => {
      const checked = [...form.querySelectorAll('input[type="checkbox"][name="formats"]:checked')].map(i => i.value);
      const other = (form.querySelector('[name="other"]')?.value || '').trim();
      if (checked.includes('Other') || checked.includes('기타')){
        if (other) checked.push(`Other: ${other}`);
      }
      return checked;
    };

    const buildBody = (form, kind) => {
      const get = (n) => (form.querySelector(`[name="${n}"]`)?.value || '').trim();

      if (kind === 'formats'){
        const formats = gatherFormats(form);
        const lines = [
          `Request type: Accessibility format request`,
          `Document / page URL: ${get('url') || '—'}`,
          `Requested format(s): ${formats.length ? formats.join(', ') : '—'}`,
          `Deadline (optional): ${get('deadline') || '—'}`,
          `Reply-to email (optional): ${get('replyEmail') || '—'}`,
          ``,
          `Details:`,
          `${get('details') || '—'}`,
          ``,
          `Privacy note: We don’t track. Settings are local-only.`
        ];
        return lines.join('\n');
      }

      // report
      const lines = [
        `Request type: Accessibility issue`,
        `Page URL: ${get('pageUrl') || '—'}`,
        ``,
        `What happened (expected vs actual):`,
        `${get('whatHappened') || '—'}`,
        ``,
        `Setup (optional): ${get('setup') || '—'}`,
        `Contact email (optional): ${get('replyEmail') || '—'}`,
        ``,
        `Privacy note: We don’t track. Settings are local-only.`
      ];
      return lines.join('\n');
    };

    const updatePreview = (form) => {
      const kind = form.getAttribute('data-a11y-mailto');
      const preview = form.querySelector('[data-a11y-preview]');
      const body = buildBody(form, kind);
      if (preview) preview.value = body;
      return body;
    };

    const validate = (form) => {
      const kind = form.getAttribute('data-a11y-mailto');
      let ok = true;

      if (kind === 'formats'){
        const url = form.querySelector('[name="url"]')?.value;
        if (!isUrl(url)){
          ok = false;
          setErr(form, 'url', 'Enter a valid URL (https://… or /path).');
        }

        const formats = gatherFormats(form);
        if (!formats.length){
          ok = false;
          setErr(form, 'formats', 'Select at least one format.');
        }

        const email = (form.querySelector('[name="replyEmail"]')?.value || '').trim();
        if (email && !isEmail(email)){
          ok = false;
          setErr(form, 'replyEmail', 'Enter a valid email address.');
        }
      } else {
        const url = form.querySelector('[name="pageUrl"]')?.value;
        if (!isUrl(url)){
          ok = false;
          setErr(form, 'pageUrl', 'Enter a valid URL (https://… or /path).');
        }

        const what = (form.querySelector('[name="whatHappened"]')?.value || '').trim();
        if (!what || what.length < 12){
          ok = false;
          setErr(form, 'whatHappened', 'Please add a bit more detail (one or two sentences).');
        }

        const email = (form.querySelector('[name="replyEmail"]')?.value || '').trim();
        if (email && !isEmail(email)){
          ok = false;
          setErr(form, 'replyEmail', 'Enter a valid email address.');
        }
      }

      return ok;
    };

    forms.forEach(form => {
      updatePreview(form);
      form.addEventListener('input', () => updatePreview(form), { passive: true });

      const copyBtn = form.querySelector('[data-a11y-copy]');
      if (copyBtn){
        copyBtn.addEventListener('click', async () => {
          try{
            const txt = updatePreview(form);
            await navigator.clipboard.writeText(txt);
            setStatus(form, 'Draft copied.', true);
          } catch {
            setStatus(form, 'Copy failed. You can still email privacy@ with the same details.', false);
          }
        });
      }

      form.addEventListener('submit', (e) => {
        e.preventDefault();
        clearErrors(form);

        const ok = validate(form);
        const kind = form.getAttribute('data-a11y-mailto');
        const subject = kind === 'formats' ? 'Accessibility format request' : 'Accessibility issue';
        const body = updatePreview(form);

        if (!ok){
          setStatus(form, 'Please fix the highlighted fields. If needed, email privacy@meridianverity.com with the same details.', false);
          return;
        }

        const href = `mailto:${to}?subject=${encodeURIComponent(subject)}&body=${encodeURIComponent(body)}`;
        try{
          window.location.href = href;
          setStatus(form, 'Draft opened in your email client. Review before sending.', true);
        } catch {
          setStatus(form, 'We couldn’t open your email client. Please email privacy@meridianverity.com with the same details.', false);
        }
      });
    });
  })();

  // Evidence anchors carousel (3-up, scroll-snap, arrow controls).
  (() => {
    const carousels = document.querySelectorAll('[data-carousel]');
    if (!carousels.length) return;

    const raf = (fn) => (window.requestAnimationFrame ? window.requestAnimationFrame(fn) : setTimeout(fn, 0));

    carousels.forEach((el) => {
      const id = el.getAttribute('data-carousel') || '';
      if (!id) return;

      const prev = document.querySelector(`[data-carousel-prev="${id}"]`);
      const next = document.querySelector(`[data-carousel-next="${id}"]`);
      if (!prev || !next) return;

      const step = () => {
        const first = el.querySelector('.card');
        if (!first) return el.clientWidth || 0;
        const styles = getComputedStyle(el);
        const gap = parseFloat(styles.gap || styles.columnGap || '0') || 0;
        return first.getBoundingClientRect().width + gap;
      };

      const update = () => {
        const max = Math.max(0, el.scrollWidth - el.clientWidth);
        const x = el.scrollLeft;
        const atStart = x <= 2;
        const atEnd = x >= (max - 2);

        // Edge hint: subtle gradient indicates there are more cards to the right.
        const shell = el.closest('.carousel-shell');
        if (shell) shell.classList.toggle('has-next', !atEnd);

        prev.disabled = atStart;
        next.disabled = atEnd;
        prev.setAttribute('aria-disabled', atStart ? 'true' : 'false');
        next.setAttribute('aria-disabled', atEnd ? 'true' : 'false');
      };

      const scrollByCards = (dir) => {
        el.scrollBy({ left: dir * step(), behavior: reduced ? 'auto' : 'smooth' });
      };

      prev.addEventListener('click', () => scrollByCards(-1));
      next.addEventListener('click', () => scrollByCards(1));

      // Keyboard support when the carousel has focus.
      el.addEventListener('keydown', (e) => {
        if (e.key === 'ArrowRight') { e.preventDefault(); scrollByCards(1); }
        if (e.key === 'ArrowLeft') { e.preventDefault(); scrollByCards(-1); }
      });

      el.addEventListener('scroll', () => raf(update), { passive: true });
      window.addEventListener('resize', () => raf(update));

      raf(update);
    });
  })();



  // Expose toast for rare inline use
  window.MVGToast = toast;
})();