import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'
import App from './App.jsx'
import AppErrorBoundary from './components/AppErrorBoundary.jsx'
import { getUserToken } from './lib/config.js'
getUserToken()

// ── Cache-bust service worker ──────────────────────────────────────────────
// Registers a SW whose sole purpose is to delete all old caches and then
// reload the page so users stuck on an old cached build get the latest
// version immediately. After the SW clears caches it unregisters itself.
if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('/sw.js', { scope: '/' }).catch(() => {})
  // Listen for the SW's signal that caches have been cleared, then reload.
  // Guarded with a one-shot sessionStorage flag: even if the SW message
  // somehow fires more than once (e.g. multiple tabs, a stray duplicate
  // registration), we only ever reload once per tab session. This is what
  // actually breaks the refresh loop — the sw.js fix above stops the loop
  // at its source, but this is a second, independent safety net.
  navigator.serviceWorker.addEventListener('message', (event) => {
    if (event.data?.type === 'SW_CACHE_CLEARED' && event.data?.reload) {
      let alreadyReloaded = false
      try { alreadyReloaded = sessionStorage.getItem('sw_cache_reloaded') === '1' } catch {}
      if (alreadyReloaded) return
      try { sessionStorage.setItem('sw_cache_reloaded', '1') } catch {}
      // Small delay so the SW finishes unregistering before reload
      setTimeout(() => window.location.reload(), 250)
    }
  })
}

;(function swDevToolsGuard() {
  // The console-based detector is intentionally disabled unless explicitly
  // requested. Running console probes on a timer in production can make the
  // dashboard feel laggy, especially while messages stream and code blocks paint.
  if (import.meta.env.VITE_ENABLE_DEVTOOLS_GUARD !== 'true') return

  let detected = false
  let overlay = null

  function showOverlay() {
    if (overlay) return
    document.documentElement.style.filter = 'blur(999px)'
    overlay = document.createElement('div')
    overlay.id = 'sw-dt-overlay'
    overlay.style.cssText = 'position:fixed;inset:0;z-index:2147483647;background:#05030d;display:flex;flex-direction:column;align-items:center;justify-content:center;font-family:Outfit,sans-serif;color:#f5f0ff'
    overlay.innerHTML = '<img src="/logo.png" style="width:56px;height:56px;object-fit:contain;margin-bottom:24px;filter:brightness(0) invert(1);opacity:.85"><h2 style="font-size:22px;margin:0 0 10px;font-weight:800;letter-spacing:-.02em">Developer Tools Detected</h2><p style="color:rgba(255,255,255,.38);font-size:14px;margin:0;text-align:center;max-width:320px">StudWorks cannot run with DevTools open.<br>Please close Developer Tools to continue.</p>'
    document.body.appendChild(overlay)
  }

  function hideOverlay() {
    document.documentElement.style.filter = ''
    if (overlay) { overlay.remove(); overlay = null }
  }

  function check() {
    const el = document.createElement('div')
    let isOpen = false
    Object.defineProperty(el, 'id', { get() { isOpen = true; return 'sw' } })
    console.log('%c', el)

    const prev = detected
    detected = isOpen
    if (detected && !prev) showOverlay()
    if (!detected && prev) hideOverlay()
  }

  setInterval(check, 5000)
  window.addEventListener('devtoolschange', e => { if (e.detail?.open) showOverlay(); else hideOverlay() })
})()

createRoot(document.getElementById('root')).render(
  <StrictMode>
    <AppErrorBoundary>
      <App />
    </AppErrorBoundary>
  </StrictMode>
)
