import debounce from '~/src/lib/utils/debounce';

/**
 * This inline script is inserted at the top of the <head>. If used inline it
 * will trigged a style-recalc which can cause flicker and perf issues.
 */
export const VH_INLINE_SCRIPT = `document.documentElement.style.setProperty('--vh',(innerHeight * 0.01)+'px');`;

// value is kept up to date on resize
if (typeof window !== 'undefined') {
  const updateDom = () => {
    const vh = window.innerHeight * 0.01;
    document.documentElement.style.setProperty('--vh', `${vh}px`);
  };

  addEventListener('resize', debounce(updateDom, 100));
}

export const toVhValue = (vh: number | undefined, modifier = '') => {
  return vh ? `calc((${vh} * var(--vh, 1vh))${modifier})` : '';
};
