export default () => {
  // Reduced default count for better performance
  let snowflakes_count = 20

  if (typeof total !== "undefined") {
    snowflakes_count = total
  }

  // This function allows you to turn on and off the snow
  const toggle_snow = () => {
    const check_box = document.getElementById(
      "toggle_snow",
    ) as HTMLInputElement | null
    const snowEl = document.getElementById("snow")

    if (snowEl) {
      snowEl.style.display = check_box?.checked ? "block" : "none"
    }
  }

  // Creating snowflakes using DocumentFragment for better performance
  const spawn_snow = (snow_density = 50) => {
    const fragment = document.createDocumentFragment()

    for (let x = 0; x < snow_density; x++) {
      const snowflake = document.createElement("div")
      snowflake.className = "snowflake"

      // Set CSS custom properties for each snowflake
      const randomX = Math.random() * 100
      const randomScale = 0.3 + Math.random() * 0.7
      const randomDuration = 10 + Math.random() * 15 // Slower = less GPU work
      const randomDelay = Math.random() * 15
      const randomOpacity = 0.4 + Math.random() * 0.6
      const randomAnimation = Math.floor(Math.random() * 3) + 1

      snowflake.style.setProperty("--start-x", `${randomX}%`)
      snowflake.style.setProperty("--scale", randomScale.toString())
      snowflake.style.setProperty("--duration", `${randomDuration}s`)
      snowflake.style.setProperty("--delay", `${randomDelay}s`)
      snowflake.style.setProperty("--opacity", randomOpacity.toString())
      snowflake.style.setProperty("--animation-name", `fall-${randomAnimation}`)

      fragment.appendChild(snowflake)
    }

    document.getElementById("snow")?.appendChild(fragment)
  }

  // Highly optimized CSS with maximum performance settings
  const createOptimizedCSS = () => {
    const css = `
      #snow {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        pointer-events: none;
        z-index: 1000;
        overflow: hidden;
        /* Contain layout calculations */
        contain: layout style paint;
      }

      .snowflake {
        position: absolute;
        top: -10px;
        width: 6px;
        height: 6px;
        background: rgba(255, 255, 255, 0.9);
        border-radius: 50%;
        
        /* Critical GPU optimizations */
        will-change: transform;
        transform: translateZ(0);
        backface-visibility: hidden;
        
        /* REMOVED box-shadow - this is a major performance killer */
        /* Even lightweight shadows are expensive with many elements */
        
        /* Use CSS custom properties for individual variations */
        left: var(--start-x);
        opacity: var(--opacity);
        animation: var(--animation-name) var(--duration) var(--delay) linear infinite;
        
        /* Reduce repaints by using contain */
        contain: layout style paint;
      }

      /* Ultra-optimized animations - only transform property */
      /* Grouped transforms reduce compositing work */
      @keyframes fall-1 {
        0% { 
          transform: translate3d(0, 0, 0) scale(var(--scale));
        }
        100% { 
          transform: translate3d(20px, 100vh, 0) scale(var(--scale));
        }
      }

      @keyframes fall-2 {
        0% { 
          transform: translate3d(0, 0, 0) scale(var(--scale));
        }
        100% { 
          transform: translate3d(-20px, 100vh, 0) scale(var(--scale));
        }
      }

      @keyframes fall-3 {
        0% { 
          transform: translate3d(0, 0, 0) scale(var(--scale));
        }
        100% { 
          transform: translate3d(0, 100vh, 0) scale(var(--scale));
        }
      }

      /* Pause animations when snow container is hidden to save resources */
      #snow[style*="display: none"] .snowflake {
        animation-play-state: paused;
      }

      /* Reduce motion for users who prefer it */
      @media (prefers-reduced-motion: reduce) {
        .snowflake {
          animation: none;
          display: none;
        }
      }
    `

    // Check if styles already exist
    if (!document.getElementById("snow-styles")) {
      const styleEl = document.createElement("style")
      styleEl.id = "snow-styles"
      styleEl.type = "text/css"
      styleEl.appendChild(document.createTextNode(css))
      document.head.appendChild(styleEl)
    }
  }

  const handleSnow = () => {
    const snowEl = document.getElementById("snow")

    if (!snowEl) {
      // Create snow container
      const el = document.createElement("div")
      el.id = "snow"
      document.body.appendChild(el)

      // Add optimized CSS
      createOptimizedCSS()

      // Use requestAnimationFrame to prevent blocking
      requestAnimationFrame(() => {
        spawn_snow(snowflakes_count)
      })
    } else {
      // Remove existing snow
      snowEl.remove()
      // Remove styles as well
      const styles = document.getElementById("snow-styles")
      if (styles) {
        styles.remove()
      }
    }
  }

  // Expose toggle function globally if needed
  window.toggle_snow = toggle_snow

  return handleSnow()
}
