"use client"

export function applyGlassMaterialFix() {
  // More robust detection method for backdrop-filter support
  const isBackdropFilterSupported = () => {
    // Check for CSS.supports API first (more reliable)
    if (typeof CSS !== "undefined" && CSS.supports) {
      console.debug("[Glass Material] Using CSS.supports for detection")
      return CSS.supports("backdrop-filter", "blur(1px)") || CSS.supports("-webkit-backdrop-filter", "blur(1px)")
    }

    // Fallback to the element style check method
    console.debug("[Glass Material] Falling back to element style check for detection")
    const el = document.createElement("div")
    el.style.backdropFilter = "blur(1px)"
    const hasBackdropFilter = el.style.backdropFilter.length > 0
    const hasWebkitBackdropFilter = el.style.webkitBackdropFilter?.length > 0
    return hasBackdropFilter || hasWebkitBackdropFilter
  }

  // Add debug logging
  const supported = isBackdropFilterSupported()
  console.debug(`[Glass Material] backdrop-filter supported: ${supported}`)

  // Add a class to the document to indicate backdrop-filter support
  if (supported) {
    document.documentElement.classList.add("backdrop-filter-supported")
    console.debug("[Glass Material] Added backdrop-filter-supported class")
  } else {
    document.documentElement.classList.add("backdrop-filter-not-supported")
    console.warn("[Glass Material] backdrop-filter is not supported in this browser. Using fallback styles.")
  }

  // Create a style element to add fixes
  const styleEl = document.createElement("style")
  styleEl.id = "glass-material-fix"
  styleEl.textContent = `
    /* Fix for backdrop-filter in various browsers */
    [data-material="glass"] {
      --glass-opacity: ${document.documentElement.getAttribute("data-glass-opacity") || "0.7"};
      --glass-blur: ${document.documentElement.getAttribute("data-glass-blur") || "36px"};
    }
    
    /* Fix for dropdown menus and portals */
    [data-radix-popper-content-wrapper] > div {
      backdrop-filter: blur(var(--glass-blur)) !important;
      -webkit-backdrop-filter: blur(var(--glass-blur)) !important;
      background-color: hsla(var(--card) / var(--glass-opacity)) !important;
      border: 1px solid rgba(255, 255, 255, 0.1) !important;
      transform: translateZ(0) !important;
      -webkit-transform: translateZ(0) !important;
      will-change: backdrop-filter !important;
    }
    
    /* Ensure portals are transparent */
    [data-radix-portal] {
      background-color: transparent !important;
    }
  `

  document.head.appendChild(styleEl)
  console.debug("[Glass Material] Added glass material fix styles")

  // Add a MutationObserver to handle dynamically added dropdown menus
  const observer = new MutationObserver((mutations) => {
    mutations.forEach((mutation) => {
      if (mutation.addedNodes.length) {
        mutation.addedNodes.forEach((node) => {
          if (node.nodeType === 1) {
            // Check if this is a dropdown menu or portal
            const element = node as HTMLElement
            if (
              element.hasAttribute("data-radix-popper-content-wrapper") ||
              element.classList.contains("dropdown-menu-content") ||
              element.classList.contains("popover-content")
            ) {
              console.debug("[Glass Material] Found dynamically added dropdown menu", element)

              // Force backdrop-filter on the element
              setTimeout(() => {
                const contentDiv = element.querySelector("div")
                if (contentDiv) {
                  contentDiv.style.backdropFilter = `blur(var(--glass-blur))`
                  contentDiv.style.webkitBackdropFilter = `blur(var(--glass-blur))`
                  contentDiv.style.backgroundColor = `hsla(var(--card) / var(--glass-opacity))`
                  contentDiv.style.transform = "translateZ(0)"
                  contentDiv.style.willChange = "backdrop-filter"
                  console.debug("[Glass Material] Applied backdrop-filter to dropdown content", contentDiv)
                }
              }, 0)
            }
          }
        })
      }
    })
  })

  // Start observing the document body for added nodes
  observer.observe(document.body, { childList: true, subtree: true })
  console.debug("[Glass Material] Started MutationObserver for dynamic dropdowns")

  return () => {
    if (document.getElementById("glass-material-fix")) {
      document.getElementById("glass-material-fix")?.remove()
    }
    observer.disconnect()
    console.debug("[Glass Material] Cleaned up glass material fix")
  }
}
