"use client"
import { useEffect, useState } from 'react'
import Link from 'next/link'
import { usePathname } from 'next/navigation'

export default function Header(){
  const [user, setUser] = useState<any>(null)
  const [loading, setLoading] = useState(true)
  const pathname = usePathname()

  useEffect(()=>{
    fetch('/api/me', { credentials: 'include' }).then(r=>r.json()).then(d=>{
      if(d.logged) setUser(d.user)
      else setUser(null)
    }).finally(()=>setLoading(false))
  },[pathname])

  return (
    <header className="sticky top-0 z-[100] bg-white border-b-2 border-slate-900">
      <div className="max-w-6xl mx-auto px-4 h-16 flex items-center justify-between bg-white">
        <Link href="/" className="font-black text-xl tracking-tight text-slate-900">ReplyOne</Link>

        <nav className="flex items-center gap-2">
          {loading ? (
            <div className="w-24 h-9 bg-slate-200 rounded-full animate-pulse"/>
          ) : user ? (
            <>
              <span className={`px-2.5 py-1 rounded-full text-xs font-black ${user.level===10?'bg-red-600 text-white':user.level===2?'bg-slate-900 text-white':'bg-white border-2 border-slate-900 text-slate-900'}`}>
                {user.level===10?'관리자10':user.level===2?'회원2':user.level===1?'비회원1':`LV.${user.level}`}
              </span>
              <Link href="/dashboard" className="px-4 py-2 rounded-full bg-slate-900 text-white text-sm font-black hover:bg-black">대시보드</Link>
              <button onClick={async()=>{ await fetch('/api/auth/logout',{method:'POST'}); location.href='/'; }} className="px-4 py-2 rounded-full bg-white border-2 border-slate-900 text-slate-900 text-sm font-black">로그아웃</button>
            </>
          ) : (
            <>
              {/* 진입점 - 비로그인시 우상단 */}
              <Link href="/login" className="px-5 py-2.5 rounded-full bg-white border-2 border-slate-900 text-slate-900 text-sm font-black hover:bg-slate-50">로그인</Link>
              <Link href="/signup" className="px-5 py-2.5 rounded-full bg-slate-900 text-white text-sm font-black hover:bg-black">회원가입</Link>
            </>
          )}
        </nav>
      </div>
    </header>
  )
}
