'use client'

import { useEffect, useState } from 'react'
import { tokenManager } from '@/lib/auth/token'

export function MockProvider({ children }: { children: React.ReactNode }) {
  const [mockEnabled, setMockEnabled] = useState(false)

  useEffect(() => {
    async function initMocking() {
      // 首先初始化设备ID（确保用户第一次访问就有设备ID）
      tokenManager.initializeDeviceId()

      // 只在开发环境和浏览器环境中启用
      if (process.env.NODE_ENV !== 'development' || typeof window === 'undefined') {
        setMockEnabled(true)
        return
      }

      // 检查是否启用 mock
      const shouldMock = process.env.NEXT_PUBLIC_ENABLE_MOCK === 'true'
      console.log('🔧 Mock enabled:', shouldMock)

      if (!shouldMock) {
        console.log('🚫 MSW 已禁用')
        setMockEnabled(true)
        return
      }

      try {
        // 动态导入 MSW
        const { worker } = await import('../mocks/browser')

        // 启动 Service Worker
        await worker.start({
          onUnhandledRequest: 'bypass',
          serviceWorker: {
            url: '/mockServiceWorker.js',
          },
          // 添加选项以避免拦截页面导航
          quiet: false,
        })

        console.log('🎭 MSW Worker started successfully')
        setMockEnabled(true)
      } catch (error) {
        console.error('❌ Failed to start MSW:', error)
        setMockEnabled(true) // 即使失败也继续渲染
      }
    }

    initMocking()
  }, [])

  // 在 mock 初始化完成前显示加载状态
  if (!mockEnabled) {
    return (
      <div className="flex min-h-screen items-center justify-center">
        <div className="text-center">
          <div className="mx-auto mb-4 h-8 w-8 animate-spin rounded-full border-b-2 border-blue-500"></div>
          <p className="text-gray-600">Initializing development environment...</p>
        </div>
      </div>
    )
  }

  return <>{children}</>
}
