const THUMB_MIN = 150;
const THUMB_MAX = 400;

let _thumbSizeHint;
let _onChange = null;
let thumbSize = 250;
let thumbHintTimer = null;
let saveTimer = null;

export function init({ gridContainer, thumbSizeHint, initialSize, onChange }) {
  _thumbSizeHint = thumbSizeHint;
  _onChange = onChange;
  if (initialSize) setThumbSize(initialSize, { showHint: false, notify: false });

  gridContainer.addEventListener('wheel', (e) => {
    if (!e.ctrlKey) return;
    e.preventDefault();
    setThumbSize(thumbSize + (-e.deltaY * 0.8));
  }, { passive: false });
}

export function setThumbSize(size, { showHint = true, notify = true } = {}) {
  thumbSize = Math.round(Math.max(THUMB_MIN, Math.min(THUMB_MAX, size)));
  document.documentElement.style.setProperty('--thumb-size', thumbSize + 'px');
  if (showHint) _showHint(thumbSize);
  if (notify) _scheduleSave(thumbSize);
}

function _showHint(size) {
  _thumbSizeHint.textContent = `${size}px`;
  _thumbSizeHint.classList.add('show');
  clearTimeout(thumbHintTimer);
  thumbHintTimer = setTimeout(() => _thumbSizeHint.classList.remove('show'), 1000);
}

function _scheduleSave(size) {
  if (!_onChange) return;
  clearTimeout(saveTimer);
  saveTimer = setTimeout(() => _onChange(size), 250);
}
