/* tdd-guard:skip — client nav shell that only composes links + session state (KAR-344 Phase 2) */
'use client'

import Link from'next/link'
import { usePathname } from'next/navigation'
import { FolderKanban, CalendarDays, ClipboardCheck, FolderArchive, BarChart3, Briefcase, User, Shield, ShieldCheck, ScrollText, Mail, ChevronDown, ChevronRight, ChevronLeft, LayoutList, Gauge, Wrench, GitBranch, Inbox, NotebookPen, GitCompareArrows } from'lucide-react'
import { useUserSession } from'@/lib/auth/hooks'
import { isAtLeastRole, hasPermission } from'@/lib/auth/permissions-shared'
import { useState, useEffect } from'react'
import { useTranslation } from'@/lib/i18n/use-translation'
import { MoreHorizontal, X as XIcon } from'lucide-react'

interface NavItem {
 href: string
 label: string
 icon: React.ElementType
 matchPrefixes: string[]
}

const SIDEBAR_STORAGE_KEY = 'sidebar_collapsed'

export default function AppShell({ children }: { children: React.ReactNode }) {
 const pathname = usePathname()
 const session = useUserSession()
 const [adminOpen, setAdminOpen] = useState(false)
 const [moreOpen, setMoreOpen] = useState(false)
 const [sidebarCollapsed, setSidebarCollapsed] = useState(false)
 const [hydrated, setHydrated] = useState(false)
 const { t } = useTranslation()

 // Close mobile drawer on navigation
 useEffect(() => { setMoreOpen(false) }, [pathname])

 // Hydrate sidebar state from localStorage
 useEffect(() => {
  const saved = localStorage.getItem(SIDEBAR_STORAGE_KEY)
  if (saved === 'true') setSidebarCollapsed(true)
  setHydrated(true)
 }, [])

 useEffect(() => {
  if (hydrated) localStorage.setItem(SIDEBAR_STORAGE_KEY, String(sidebarCollapsed))
 }, [sidebarCollapsed, hydrated])

 // Force admin section closed when sidebar collapses
 useEffect(() => {
  if (sidebarCollapsed) setAdminOpen(false)
 }, [sidebarCollapsed])

 const isAdmin = session ? isAtLeastRole(session,'admin') : false

 function isActive(prefixes: string[]) {
 return prefixes.some((p) => pathname === p || pathname.startsWith(p +'/'))
 }

 const BASE_ITEMS: NavItem[] = [
 { href:'/intake/board', label: t('nav.intake'), icon: Inbox, matchPrefixes: ['/intake'] },
 { href:'/projektanlage', label: t('nav.projektanlage'), icon: FolderKanban, matchPrefixes: ['/projektanlage','/project'] },
 { href:'/kalender', label: t('nav.kalender'), icon: CalendarDays, matchPrefixes: ['/kalender'] },
 { href:'/lsc-workshop', label: t('nav.lscWorkshop'), icon: Wrench, matchPrefixes: ['/lsc-workshop'] },
 { href:'/qaf-differences', label: t('nav.qafDifferences'), icon: GitCompareArrows, matchPrefixes: ['/qaf-differences'] },
 { href:'/fabrikanalyse', label: t('nav.fabrikanalyse'), icon: ClipboardCheck, matchPrefixes: ['/fabrikanalyse'] },
 { href:'/oee', label: t('nav.oeeAnalyse'), icon: Gauge, matchPrefixes: ['/oee'] },
 { href:'/wertstrom', label: t('nav.wertstrom'), icon: GitBranch, matchPrefixes: ['/wertstrom'] },
 { href:'/repository', label: t('nav.datenablage'), icon: FolderArchive, matchPrefixes: ['/repository'] },
 { href:'/pmo', label: t('nav.pmo'), icon: Briefcase, matchPrefixes: ['/pmo'] },
 { href:'/notes', label: t('nav.notizen'), icon: NotebookPen, matchPrefixes: ['/notes'] },
 ]

 const isMasterAdmin = session?.role ==='masteradmin'
 const BOTTOM_ITEMS: NavItem[] = [
 { href:'/konto', label: t('nav.konto'), icon: isMasterAdmin ? ShieldCheck : User, matchPrefixes: ['/konto'] },
 ]

 // Reporting — permission gated
 const REPORTING_ITEM: NavItem = { href:'/reporting', label: t('nav.reporting'), icon: BarChart3, matchPrefixes: ['/reporting'] }

 const ADMIN_SUB_ITEMS: NavItem[] = isAdmin ? [
 { href:'/admin/users', label: t('admin.users'), icon: ShieldCheck, matchPrefixes: ['/admin/users'] },
 { href:'/admin/views', label: t('admin.views'), icon: LayoutList, matchPrefixes: ['/admin/views'] },
 ...(session && hasPermission(session,'audit.read') ? [{ href:'/admin/audit', label: t('admin.auditLog'), icon: ScrollText, matchPrefixes: ['/admin/audit'] }] : []),
 { href:'/admin/emails', label: t('admin.emailQueue'), icon: Mail, matchPrefixes: ['/admin/emails'] },
 ] : []

 // Mobile primary tabs (4 +"Mehr")
 const MOBILE_TABS: NavItem[] = [
 BASE_ITEMS[0], // Intake
 BASE_ITEMS[1], // Projektanlage
 BASE_ITEMS[2], // Kalender
 BASE_ITEMS[3], // LSC Workshop
 ]

 // Items shown inside the"Mehr"drawer — everything after the 4 mobile tabs
 const DRAWER_ITEMS: NavItem[] = [
 ...BASE_ITEMS.slice(MOBILE_TABS.length), // Fabrikanalyse, OEE, Wertstrom, Datenablage, PMO, Projektnotizen
 ...(session && isAtLeastRole(session,'consultant') ? [REPORTING_ITEM] : []),
 BOTTOM_ITEMS[0], // Konto
 ]

 const sidebarWidthClass = sidebarCollapsed ?'md:w-16':'md:w-52'
 const mainMarginClass = sidebarCollapsed ?'md:ml-16':'md:ml-52'
 const linkClass = (active: boolean) => `flex items-center gap-3 ${sidebarCollapsed ?'justify-center px-0':'px-3'} py-2.5 rounded-sm text-sm font-medium transition-colors ${
   active ?'bg-sidebar-accent text-sidebar-accent-foreground font-semibold border-l-2 border-primary pl-[10px]':'text-sidebar-foreground/70 hover:text-sidebar-foreground hover:bg-sidebar-accent/50'
 }`

 return (
 <div className="min-h-screen bg-background flex">
 {/* Sidebar — desktop */}
 <aside className={`hidden md:flex flex-col ${sidebarWidthClass} bg-sidebar text-sidebar-foreground fixed left-0 top-0 bottom-0 z-20 shrink-0 transition-all duration-200 ease-out`}>
 <div className={`h-14 flex items-center ${sidebarCollapsed ?'justify-center px-0':'justify-between px-5'} border-b border-sidebar-border`}>
 {!sidebarCollapsed && <span className="font-semibold text-sm tracking-wide text-sidebar-foreground">SupplierPulse</span>}
 <button
 onClick={() => setSidebarCollapsed((c) => !c)}
 className="text-sidebar-foreground/60 hover:text-sidebar-foreground p-1 rounded-sm hover:bg-sidebar-accent/50 transition-colors"
 title={sidebarCollapsed ?'Sidebar ausklappen':'Sidebar einklappen'}
 aria-label={sidebarCollapsed ?'Sidebar ausklappen':'Sidebar einklappen'}
 >
 {sidebarCollapsed ? <ChevronRight size={16} /> : <ChevronLeft size={16} />}
 </button>
 </div>

 <nav className={`flex-1 ${sidebarCollapsed ?'p-2':'p-3'} space-y-0.5 overflow-y-auto`}>
 {/* Main items */}
 {BASE_ITEMS.map(({ href, label, icon: Icon, matchPrefixes }) => (
 <Link
 key={href}
 href={href}
 title={sidebarCollapsed ? label : undefined}
 className={linkClass(isActive(matchPrefixes))}
 >
 <Icon size={17} className="shrink-0"/>
 {!sidebarCollapsed && label}
 </Link>
 ))}

 {/* Reporting — consultant role and above */}
 {session && isAtLeastRole(session,'consultant') && (
 <Link
 href={REPORTING_ITEM.href}
 title={sidebarCollapsed ? REPORTING_ITEM.label : undefined}
 className={linkClass(isActive(REPORTING_ITEM.matchPrefixes))}
 >
 <BarChart3 size={17} className="shrink-0"/>
 {!sidebarCollapsed && REPORTING_ITEM.label}
 </Link>
 )}

 {/* Separator */}
 {isAdmin && <div className="my-2 border-t border-sidebar-border"/>}

 {/* Admin collapsible */}
 {isAdmin && (
 <div>
 <button
 onClick={() => {
   if (sidebarCollapsed) setSidebarCollapsed(false)
   setAdminOpen((v) => !v)
 }}
 title={sidebarCollapsed ? t('nav.admin') : undefined}
 className={`w-full flex items-center ${sidebarCollapsed ?'justify-center px-0':'justify-between px-3'} gap-3 py-2.5 rounded-sm text-sm font-medium text-sidebar-foreground/70 hover:text-sidebar-foreground hover:bg-sidebar-accent/50 transition-colors`}
 >
 <div className={`flex items-center gap-3 ${sidebarCollapsed ?'justify-center':''}`}>
 <Shield size={17} className="shrink-0"/>
 {!sidebarCollapsed && t('nav.admin')}
 </div>
 {!sidebarCollapsed && (adminOpen ? <ChevronDown size={14} /> : <ChevronRight size={14} />)}
 </button>
 {!sidebarCollapsed && adminOpen && (
 <div className="ml-4 mt-0.5 space-y-0.5">
 {ADMIN_SUB_ITEMS.map(({ href, label, icon: Icon, matchPrefixes }) => (
 <Link
 key={href}
 href={href}
 className={`flex items-center gap-3 px-3 py-2 rounded-sm text-xs font-medium transition-colors ${
 isActive(matchPrefixes) ?'bg-sidebar-accent text-sidebar-accent-foreground font-semibold':'text-sidebar-foreground/60 hover:text-sidebar-foreground hover:bg-sidebar-accent/50'
 }`}
 >
 <Icon size={14} />
 {label}
 </Link>
 ))}
 </div>
 )}
 </div>
 )}
 </nav>

 {/* Separator + Konto at bottom */}
 <div className={`${sidebarCollapsed ?'p-2':'p-3'} border-t border-sidebar-border space-y-0.5`}>
 {BOTTOM_ITEMS.map(({ href, label, icon: Icon, matchPrefixes }) => (
 <Link
 key={href}
 href={href}
 title={sidebarCollapsed ? label : undefined}
 className={linkClass(isActive(matchPrefixes))}
 >
 <Icon size={17} className="shrink-0"/>
 {!sidebarCollapsed && label}
 </Link>
 ))}
 {!sidebarCollapsed && <p className="text-[10px] text-sidebar-foreground/40 px-3 pt-1">Supplier Development</p>}
 </div>
 </aside>

 {/* Main content */}
 <div className={`flex-1 ${mainMarginClass} min-w-0 flex flex-col transition-all duration-200 ease-out`}>
 {children}
 </div>

 {/* Bottom tabs — mobile */}
 <nav className="md:hidden fixed bottom-0 left-0 right-0 z-20 bg-sidebar border-t border-sidebar-border flex safe-area-bottom">
 {MOBILE_TABS.map(({ href, label, icon: Icon, matchPrefixes }) => {
 const active = isActive(matchPrefixes)
 return (
 <Link
 key={href}
 href={href}
 className={`flex-1 flex flex-col items-center justify-center py-2.5 gap-0.5 transition-colors ${active ?'text-sidebar-foreground font-semibold':'text-sidebar-foreground/60'}`}
 >
 <Icon size={21} />
 <span className="text-[10px] font-medium">{label}</span>
 </Link>
 )
 })}
 {/* Mehr button */}
 <button
 onClick={() => setMoreOpen(true)}
 className={`flex-1 flex flex-col items-center justify-center py-2.5 gap-0.5 transition-colors ${moreOpen ?'text-sidebar-foreground font-semibold':'text-sidebar-foreground/60'}`}
 >
 <MoreHorizontal size={21} />
 <span className="text-[10px] font-medium">Mehr</span>
 </button>
 </nav>

 {/* Mobile"Mehr"drawer */}
 {moreOpen && (
 <div className="md:hidden fixed inset-0 z-40 flex flex-col justify-end">
 {/* Backdrop */}
 <div
 className="absolute inset-0 bg-[rgba(31,35,40,0.3)]"
 onClick={() => setMoreOpen(false)}
 />
 {/* Sheet */}
 <div className="relative bg-sidebar rounded-t-sm z-50 pb-safe-or-4">
 {/* Handle + close */}
 <div className="flex items-center justify-between px-5 pt-4 pb-2">
 <div className="w-10 h-1 bg-sidebar-border rounded-full mx-auto absolute left-1/2 -translate-x-1/2 top-3"/>
 <p className="text-xs font-semibold text-sidebar-foreground/50 uppercase tracking-wide">Navigation</p>
 <button
 onClick={() => setMoreOpen(false)}
 className="p-1.5 rounded-sm text-sidebar-foreground/60 hover:text-sidebar-foreground hover:bg-sidebar-accent/50 transition-colors"
 >
 <XIcon size={16} />
 </button>
 </div>

 <nav className="px-3 pb-3 space-y-0.5">
 {DRAWER_ITEMS.map(({ href, label, icon: Icon, matchPrefixes }) => (
 <Link
 key={href}
 href={href}
 className={`flex items-center gap-3 px-3 py-3 rounded-sm text-sm font-medium transition-colors ${
 isActive(matchPrefixes) ?'bg-sidebar-accent text-sidebar-accent-foreground font-semibold border-l-2 border-primary pl-[10px]':'text-sidebar-foreground/80 hover:text-sidebar-foreground hover:bg-sidebar-accent/50'
 }`}
 >
 <Icon size={18} />
 {label}
 </Link>
 ))}

 {/* Admin items — admin+ only */}
 {isAdmin && (
 <>
 <div className="my-2 border-t border-sidebar-border"/>
 <p className="px-3 py-1 text-[11px] font-semibold text-sidebar-foreground/40 uppercase tracking-wide">Administration</p>
 {ADMIN_SUB_ITEMS.map(({ href, label, icon: Icon, matchPrefixes }) => (
 <Link
 key={href}
 href={href}
 className={`flex items-center gap-3 px-3 py-3 rounded-sm text-sm font-medium transition-colors ${
 isActive(matchPrefixes) ?'bg-sidebar-accent text-sidebar-accent-foreground font-semibold border-l-2 border-primary pl-[10px]':'text-sidebar-foreground/80 hover:text-sidebar-foreground hover:bg-sidebar-accent/50'
 }`}
 >
 <Icon size={18} />
 {label}
 </Link>
 ))}
 </>
 )}
 </nav>
 </div>
 </div>
 )}
 </div>
 )
}
