// Main app shell: top nav + content area. Used after login.

import { useEffect, useState } from 'react'
import { Link, useLocation } from 'wouter'
import { motion, AnimatePresence } from 'framer-motion'
import { Activity, Bell, Command, Cpu, LogOut, Radio, Wifi } from 'lucide-react'
import { api, setToken } from '../lib/api'
import { Pill } from './ui'
import { useQuery } from '@tanstack/react-query'

const nav = [
  { href: '/', label: 'Overview', icon: Activity },
  { href: '/routers', label: 'Routers', icon: Radio },
  { href: '/events', label: 'Events', icon: Cpu },
  { href: '/commands', label: 'Commands', icon: Command },
  { href: '/alerts', label: 'Alerts', icon: Bell },
] as const

export function Shell({ children }: { children: React.ReactNode }) {
  const [location] = useLocation()
  const [, navigate] = useLocation()
  const [user, setUser] = useState<{ username: string; role: string } | null>(null)

  useEffect(() => {
    api.me()
      .then((u) => setUser({ username: u.username, role: u.role }))
      .catch(() => navigate('/login'))
  }, [navigate])

  const { data: alerts } = useQuery({
    queryKey: ['alerts', 'unack-count'],
    queryFn: () => api.alerts({ unack: true, limit: 1 }),
    refetchInterval: 30_000,
  })
  const unackCount = alerts?.alerts.length ?? 0

  const logout = () => {
    setToken(null)
    navigate('/login')
  }

  return (
    <div className="min-h-screen flex flex-col">
      {/* Top nav */}
      <header className="sticky top-0 z-30 backdrop-blur-xl bg-black/40 border-b border-white/5">
        <div className="max-w-7xl mx-auto px-6 lg:px-10 h-16 flex items-center justify-between">
          <Link href="/">
            <a className="flex items-center gap-2.5 group">
              <div className="w-8 h-8 rounded-lg bg-gradient-to-br from-[#0a84ff] to-[#5856d6] flex items-center justify-center">
                <Wifi className="w-4 h-4 text-white" strokeWidth={2.5} />
              </div>
              <span className="font-semibold text-body tracking-tight">client2server</span>
            </a>
          </Link>

          <nav className="hidden md:flex items-center gap-8 text-small">
            {nav.map((n) => {
              const active = n.href === '/' ? location === '/' : location.startsWith(n.href)
              return (
                <Link key={n.href} href={n.href}>
                  <a className={`nav-link inline-flex items-center gap-1.5 ${active ? 'active' : ''}`}>
                    <n.icon className="w-3.5 h-3.5" />
                    {n.label}
                    {n.href === '/alerts' && unackCount > 0 && (
                      <span className="ml-1 px-1.5 py-0.5 text-[10px] font-semibold rounded-full bg-rose-500/20 text-rose-300">
                        {unackCount}
                      </span>
                    )}
                  </a>
                </Link>
              )
            })}
          </nav>

          <div className="flex items-center gap-3">
            {user && (
              <div className="hidden sm:flex items-center gap-2 text-caption text-ink-400">
                <Pill tone={user.role === 'system_admin' ? 'info' : 'neutral'}>{user.role}</Pill>
                <span>{user.username}</span>
              </div>
            )}
            <button
              onClick={logout}
              className="p-2 rounded-lg hover:bg-white/5 text-ink-400 hover:text-ink-200 transition-colors"
              title="Sign out"
            >
              <LogOut className="w-4 h-4" />
            </button>
          </div>
        </div>
      </header>

      {/* Main */}
      <main className="flex-1 max-w-7xl w-full mx-auto px-6 lg:px-10 py-10">
        <AnimatePresence mode="wait">
          <motion.div
            key={location}
            initial={{ opacity: 0, y: 8 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: -8 }}
            transition={{ duration: 0.25, ease: [0.16, 1, 0.3, 1] }}
          >
            {children}
          </motion.div>
        </AnimatePresence>
      </main>

      {/* Footer */}
      <footer className="border-t border-white/5 mt-10">
        <div className="max-w-7xl mx-auto px-6 lg:px-10 py-6 flex items-center justify-between text-caption text-ink-500">
          <span>client2server v2.1</span>
          <span className="flex items-center gap-1.5">
            <span className="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse" />
            Connected
          </span>
        </div>
      </footer>
    </div>
  )
}
