/**
 * Dashboard 佈局
 */
'use client'

import { useSession } from 'next-auth/react'
import { useRouter } from 'next/navigation'
import { useEffect } from 'react'
import { Sidebar } from '@/components/layout/sidebar'
import { Breadcrumb } from '@/components/layout/breadcrumb'

export default function DashboardLayout({ children }: { children: React.ReactNode }) {
  const { data: session, status } = useSession()
  const router = useRouter()

  useEffect(() => {
    console.log('[Dashboard] ========== Dashboard Auth Check ==========')
    console.log('[Dashboard] Status:', status)
    console.log('[Dashboard] Has session:', !!session)
    console.log('[Dashboard] Has user:', !!session?.user)
    console.log('[Dashboard] User email:', session?.user?.email)
    console.log('[Dashboard] ===========================================')

    // 完全移除重定向邏輯,讓 session 自然載入
    // NextAuth 會自動處理 session 同步
  }, [status, session])

  // 載入中時顯示 loading
  if (status === 'loading') {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-center">
          <div className="w-16 h-16 border-4 border-indigo-600 border-t-transparent rounded-full animate-spin mx-auto mb-4"></div>
          <p className="text-gray-600">正在載入 Session...</p>
          <p className="text-xs text-gray-400 mt-2">Status: {status}</p>
        </div>
      </div>
    )
  }

  // 如果沒有 session,顯示登入提示 (不要自動重定向)
  if (!session || !session.user) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gray-100">
        <div className="bg-white p-8 rounded-lg shadow-md text-center max-w-md">
          <h2 className="text-2xl font-bold text-gray-900 mb-4">需要登入</h2>
          <p className="text-gray-600 mb-6">您尚未登入或 Session 已過期</p>
          <p className="text-sm text-gray-500 mb-4">Status: {status}</p>
          <button
            onClick={() => router.push('/auth/signin')}
            className="bg-indigo-600 text-white px-6 py-2 rounded-md hover:bg-indigo-700"
          >
            前往登入
          </button>
        </div>
      </div>
    )
  }

  return (
    <div className="flex h-screen bg-gray-100">
      {/* Sidebar */}
      <aside className="w-64 flex-shrink-0">
        <Sidebar />
      </aside>

      {/* Main Content */}
      <main className="flex-1 overflow-auto">
        <div className="p-8">
          <Breadcrumb />
          {children}
        </div>
      </main>
    </div>
  )
}
