'use client'

import { useAuthStore } from '@/lib/store/authStore'
import { buildTree, type TreeNode } from './Sidebar'

function findTrail(nodes: TreeNode[], targetMenuNo: string | null): TreeNode[] {
  if (!targetMenuNo) return []
  for (const node of nodes) {
    if (node.menuNo === targetMenuNo) return [node]
    const childTrail = findTrail(node.children, targetMenuNo)
    if (childTrail.length > 0) return [node, ...childTrail]
  }
  return []
}

export function Breadcrumb() {
  const menuList      = useAuthStore((s) => s.menuList)
  const selectedMenuNo = useAuthStore((s) => s.selectedMenuNo)

  const tree  = buildTree(menuList)
  const trail = findTrail(tree, selectedMenuNo)

  if (trail.length === 0) return null

  const current = trail[trail.length - 1]

  return (
    <div className="bg-white border-b px-6 py-2.5 flex items-center gap-3 shrink-0">
      <h1 className="text-sm font-semibold text-gray-800">{current.menuNm}</h1>
      {trail.length > 1 && (
        <>
          <span className="text-gray-200">|</span>
          <nav className="flex items-center gap-1 text-xs text-gray-400">
            {trail.map((item, i) => (
              <span key={item.menuNo} className="flex items-center gap-1">
                {i > 0 && <span className="text-gray-300">›</span>}
                <span className={i === trail.length - 1 ? 'text-blue-600 font-medium' : ''}>
                  {item.menuNm}
                </span>
              </span>
            ))}
          </nav>
        </>
      )}
    </div>
  )
}
