/* ankle-flicker.js — portable per-letter flicker loader.
 *
 * Exposes a single global `AnkleFlicker` with init / stop / setSpeed.
 * Pairs with ankle-flicker.css. No deps.
 *
 *   AnkleFlicker.init(el, { text: 'LOADING', preset: 'small', palette: 'default', speed: 1 })
 *   AnkleFlicker.stop(el)
 *   AnkleFlicker.setSpeed(el, 2)   // 2× faster
 *   AnkleFlicker.initAll('[data-ankle-flicker]')
 *
 * Auto-init: any element with [data-ankle-flicker] in the DOM at script-load
 * gets initialized. The attribute value (if non-empty) becomes the text;
 * preset/palette/speed read from data-attrs.
 */
(function (root) {
  'use strict';

  // Per-letter "rhythm" — durations + negative delays that desync the letters
  // even when they all share the same keyframes. Designed for 7-letter
  // strings (LOADING); shorter / longer strings get extended/clipped.
  var RHYTHM = [
    { dur: 0.42, delay: 0 },
    { dur: 0.56, delay: -0.15 },
    { dur: 0.38, delay: -0.27 },
    { dur: 0.49, delay: -0.08 },
    { dur: 0.33, delay: -0.21 },
    { dur: 0.61, delay: -0.05 },
    { dur: 0.45, delay: -0.18 },
    { dur: 0.51, delay: -0.31 },
    { dur: 0.37, delay: -0.12 },
    { dur: 0.59, delay: -0.06 },
  ];

  var PRESETS = ['tiny', 'small', 'label', 'hero', 'xl'];
  var PALETTES = ['default', 'mono', 'cyber'];

  function applyClasses(el, opts) {
    el.classList.add('ankle-flicker');
    PRESETS.forEach(function (p) { el.classList.remove('ankle-flicker--' + p); });
    PALETTES.forEach(function (p) { el.classList.remove('ankle-flicker--palette-' + p); });
    var preset = PRESETS.indexOf(opts.preset) >= 0 ? opts.preset : 'small';
    var palette = PALETTES.indexOf(opts.palette) >= 0 ? opts.palette : 'default';
    el.classList.add('ankle-flicker--' + preset);
    el.classList.add('ankle-flicker--palette-' + palette);
  }

  function init(el, opts) {
    if (!el) return null;
    opts = opts || {};
    var text = String(opts.text != null ? opts.text : (el.getAttribute('data-ankle-flicker') || 'LOADING'));
    var speed = +opts.speed || +el.getAttribute('data-flicker-speed') || 1;
    if (speed <= 0) speed = 1;

    applyClasses(el, {
      preset: opts.preset || el.getAttribute('data-flicker-preset'),
      palette: opts.palette || el.getAttribute('data-flicker-palette'),
    });

    // Clear any previous render
    el.textContent = '';
    el.setAttribute('aria-live', 'polite');
    el.setAttribute('aria-label', text);

    var chars = text.split('');
    chars.forEach(function (ch, i) {
      var span = document.createElement('span');
      span.className = 'ankle-flicker__letter';
      span.textContent = ch;
      var r = RHYTHM[i % RHYTHM.length];
      var d = (r.dur / speed).toFixed(3) + 's';
      span.style.animationDuration = d;
      span.style.animationDelay = r.delay.toFixed(3) + 's';
      el.appendChild(span);
    });

    el.dataset.ankleFlickerActive = '1';
    el.dataset.ankleFlickerSpeed = String(speed);
    el.dataset.ankleFlickerText = text;
    return el;
  }

  function stop(el) {
    if (!el) return;
    el.textContent = '';
    delete el.dataset.ankleFlickerActive;
    delete el.dataset.ankleFlickerSpeed;
    delete el.dataset.ankleFlickerText;
    el.removeAttribute('aria-live');
    el.removeAttribute('aria-label');
  }

  function setSpeed(el, mult) {
    if (!el) return;
    mult = +mult || 1;
    if (mult <= 0) mult = 1;
    var letters = el.querySelectorAll('.ankle-flicker__letter');
    letters.forEach(function (span, i) {
      var r = RHYTHM[i % RHYTHM.length];
      span.style.animationDuration = (r.dur / mult).toFixed(3) + 's';
    });
    el.dataset.ankleFlickerSpeed = String(mult);
  }

  function initAll(selector) {
    selector = selector || '[data-ankle-flicker]';
    var nodes = document.querySelectorAll(selector);
    Array.prototype.forEach.call(nodes, function (el) {
      if (el.dataset.ankleFlickerActive === '1') return;
      init(el);
    });
  }

  var api = { init: init, stop: stop, setSpeed: setSpeed, initAll: initAll, RHYTHM: RHYTHM };

  // Auto-init on DOMContentLoaded for any [data-ankle-flicker] elements.
  if (typeof document !== 'undefined') {
    if (document.readyState === 'loading') {
      document.addEventListener('DOMContentLoaded', function () { initAll(); });
    } else {
      // Defer slightly so consumers can register listeners first.
      setTimeout(initAll, 0);
    }
  }

  // Expose
  root.AnkleFlicker = api;
  if (typeof module !== 'undefined' && module.exports) module.exports = api;
})(typeof window !== 'undefined' ? window : this);
