const DEFAULT_THEME_COLOR = '#eff6ff';

function resolveThemeColor() {
  if (typeof window === 'undefined') {
    return DEFAULT_THEME_COLOR;
  }

  const hostname = window.location.hostname.toLowerCase();

  if (hostname === 'localhost' || hostname === '127.0.0.1' || hostname === '0.0.0.0') {
    return '#e2e8f0';
  }

  if (hostname.startsWith('test.')) {
    return '#dcfce7';
  }

  if (hostname.startsWith('rel.')) {
    return '#fed7aa';
  }

  if (hostname.startsWith('preview.')) {
    return '#dbeafe';
  }

  return '#f3e8ff';
}

function setThemeColor(color: string) {
  if (typeof document === 'undefined') {
    return;
  }

  let themeColorMeta = document.querySelector<HTMLMetaElement>('meta[name="theme-color"]');

  if (!themeColorMeta) {
    themeColorMeta = document.createElement('meta');
    themeColorMeta.name = 'theme-color';
    document.head.append(themeColorMeta);
  }

  themeColorMeta.content = color;
}

export function syncAppThemeColor() {
  const color = resolveThemeColor();
  setThemeColor(color);
}

export function installAppThemeColorSync() {
  if (typeof window === 'undefined' || typeof document === 'undefined') {
    return () => undefined;
  }

  const sync = () => {
    syncAppThemeColor();
    window.requestAnimationFrame(() => {
      syncAppThemeColor();
    });
  };

  const handleVisibilityChange = () => {
    if (document.visibilityState === 'visible') {
      sync();
    }
  };

  sync();
  window.addEventListener('focus', sync);
  window.addEventListener('pageshow', sync);
  document.addEventListener('visibilitychange', handleVisibilityChange);

  return () => {
    window.removeEventListener('focus', sync);
    window.removeEventListener('pageshow', sync);
    document.removeEventListener('visibilitychange', handleVisibilityChange);
  };
}
