/**
 * 员工端统一布局 — 顶部 Header（Logo + 员工名 + 退出）+ 底部固定 TabBar 导航
 * 所有已登录员工端页面共享此布局
 */

import { Link, useLocation, useNavigate } from 'react-router-dom'
import { useQuery } from '@tanstack/react-query'
import { DollarSign, FileText, ScrollText, LogOut, CalendarCheck, Home } from 'lucide-react'
import { portalApi } from '../../lib/api-services'

const tabItems = [
  { path: '/portal/home', label: '首页', icon: Home },
  { path: '/portal/payslip', label: '工资条', icon: DollarSign },
  { path: '/portal/contract', label: '我的合同', icon: FileText },
  { path: '/portal/attendance', label: '我的考勤', icon: CalendarCheck },
  { path: '/portal/policies', label: '规章制度', icon: ScrollText },
]

export default function PortalLayout({ children }: { children: React.ReactNode }) {
  const location = useLocation()
  const navigate = useNavigate()

  const employee = (() => {
    try { return JSON.parse(localStorage.getItem('portalEmployee') || '{}') } catch { return {} }
  })()

  // 获取 overview 数据作为 idCardNumber fallback（旧登录 localStorage 可能没有 idCardNumber）
  const { data: overview } = useQuery<any>({
    queryKey: ['portal-home-overview'],
    queryFn: async () => portalApi.homeOverview(),
    staleTime: 300000,
  })
  const idCardNumber = employee.idCardNumber || overview?.employeeIdCardNumber
  if (idCardNumber && !employee.idCardNumber) {
    try {
      localStorage.setItem('portalEmployee', JSON.stringify({ ...employee, idCardNumber }))
    } catch {}
  }

  const handleLogout = () => {
    localStorage.removeItem('portalToken')
    localStorage.removeItem('portalEmployee')
    navigate('/portal/login')
  }

  return (
    <div className="min-h-screen bg-gray-50 flex flex-col">
      {/* 顶部 Header — 安全区 padding 适配刘海屏 */}
      <header className="sticky top-0 z-30 bg-white border-b border-gray-200 pt-safe">
        <div className="max-w-md mx-auto h-14 flex items-center justify-between px-4">
          <div className="flex items-center min-w-0">
            <span className="text-sm font-bold text-gray-900 truncate">{employee.orgName || '安职通'}</span>
          </div>
          <div className="flex items-center gap-2 flex-shrink-0">
            {employee.name && (
              <span className="text-xs text-gray-500 truncate max-w-[120px]">{employee.name}{idCardNumber ? `（${idCardNumber}）` : ''}</span>
            )}
            <button
              onClick={handleLogout}
              className="flex items-center gap-1 text-xs text-gray-400 hover:text-gray-600 px-2 py-1.5 rounded-md hover:bg-gray-50"
            >
              <LogOut className="w-3.5 h-3.5" />
              退出
            </button>
          </div>
        </div>
      </header>

      {/* 主内容区 */}
      <main className="flex-1 max-w-md mx-auto w-full px-4 py-6 pb-28">
        {children}
      </main>

      {/* 底部固定 TabBar — 安全区 padding 适配 home indicator */}
      <nav className="fixed bottom-0 left-0 right-0 z-30 bg-white border-t border-gray-200 pb-safe">
        <div className="max-w-md mx-auto flex items-center justify-around h-16">
          {tabItems.map((item) => {
            const Icon = item.icon
            const active = location.pathname === item.path ||
              (item.path === '/portal/payslip' && location.pathname.startsWith('/portal/payslip'))
            return (
              <Link
                key={item.path}
                to={item.path}
                className={`flex flex-col items-center justify-center gap-0.5 flex-1 h-full transition-colors ${
                  active ? 'text-primary' : 'text-gray-400 hover:text-gray-600'
                }`}
              >
                <Icon className={`w-5 h-5 ${active ? 'fill-primary/10' : ''}`} />
                <span className={`text-xs ${active ? 'font-medium' : ''}`}>{item.label}</span>
              </Link>
            )
          })}
        </div>
      </nav>
    </div>
  )
}
