// string-tune.jsx — StringTune (@fiddle-digital/string-tune) init + React helpers
// Parallax, split, masonry, sequence (see skills/ tutorials)

function prefersReducedMotion() {
  return typeof window !== 'undefined' &&
    window.matchMedia('(prefers-reduced-motion: reduce)').matches;
}

function useStringTuneInit() {
  React.useEffect(() => {
    if (prefersReducedMotion()) return;
    const ST = window.StringTune;
    if (!ST?.StringTune?.getInstance) return;

    const run = () => {
      try {
        const stringTune = ST.StringTune.getInstance();
        if (!window.__portfolioStringTunePluginsV2) {
          /* Do not register StringLazy — it hijacks <img> nodes and swaps in placeholder URLs
             (tutorial defaults), breaking showcase/workflow screenshots. Lazy loading is via
             native loading="lazy" on imgs. */
          stringTune.use(ST.StringParallax);
          stringTune.use(ST.StringSplit);
          stringTune.use(ST.StringMasonry);
          stringTune.use(ST.StringSequence);
          window.__portfolioStringTunePluginsV2 = true;
        }
        stringTune.start(0);
      } catch (e) {
        console.warn('[string-tune]', e);
      }
    };

    let idleId;
    let rafId;
    if (typeof requestIdleCallback !== 'undefined') {
      idleId = requestIdleCallback(run, { timeout: 2000 });
    } else {
      rafId = requestAnimationFrame(run);
    }
    return () => {
      if (idleId != null && typeof cancelIdleCallback !== 'undefined') cancelIdleCallback(idleId);
      if (rafId != null) cancelAnimationFrame(rafId);
    };
  }, []);
}

function StringTuneSplit({ as: Comp = 'span', className = '', children }) {
  const ref = React.useRef(null);
  React.useEffect(() => {
    if (prefersReducedMotion()) return;
    const el = ref.current;
    if (!el) return;
    el.setAttribute('string', 'split');
    el.setAttribute('string-repeat', '');
    el.setAttribute('string-split', 'char');
  }, []);
  return (
    <Comp ref={ref} className={className}>
      {children}
    </Comp>
  );
}

window.useStringTuneInit = useStringTuneInit;
window.StringTuneSplit = StringTuneSplit;
