'use client';

import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { useAuth } from '@/lib/auth-context';
import { useRealtime } from '@/lib/realtime';
import { MENU, MenuEntry } from '@/lib/menu';

function Badge({ n }: { n: number }) {
  if (!n) return null;
  return (
    <span className="ml-auto min-w-[18px] h-[18px] px-1.5 rounded-full bg-brand-live text-white text-[10px] font-bold flex items-center justify-center animate-scaleIn">
      {n > 99 ? '99+' : n}
    </span>
  );
}

export default function Sidebar() {
  const pathname = usePathname();
  const { user, hasPermission } = useAuth();
  const { counts, connected } = useRealtime();

  // Filter first, so a section heading whose every item is filtered out
  // doesn't render as an orphaned label with nothing underneath it.
  const visible: MenuEntry[] = [];
  for (let i = 0; i < MENU.length; i++) {
    const item = MENU[i];
    if ('section' in item) {
      const next = MENU.slice(i + 1).findIndex((m) => 'section' in m);
      const sectionItems = MENU.slice(i + 1, next === -1 ? undefined : i + 1 + next);
      if (sectionItems.some((m) => !('section' in m) && hasPermission(m.permission))) visible.push(item);
    } else if (hasPermission(item.permission)) {
      visible.push(item);
    }
  }

  return (
    <aside className="w-[260px] bg-brand-charcoal text-white h-screen sticky top-0 overflow-y-auto shrink-0">
      <div className="p-4 border-b border-white/10 flex items-center gap-3">
        <div className="w-8 h-8 rounded bg-white flex items-center justify-center overflow-hidden">
          {/* eslint-disable-next-line @next/next/no-img-element */}
          <img src="/logo.png" alt="LUSSAVARA" className="w-6 h-6 object-contain" />
        </div>
        <div className="flex-1">
          <p className="font-bold text-sm">LUSSAVARA OS</p>
          <p className="text-[10px] text-white/60">admin.lussavara.co.tz</p>
        </div>
        <span title={connected ? 'Live updates on' : 'Reconnecting — pages refresh automatically every 30 s'}
          className={`w-2 h-2 rounded-full ${connected ? 'bg-green-400' : 'bg-amber-400 animate-pulse'}`} />
      </div>
      <nav className="p-2">
        {visible.map((item, i) => {
          if ('section' in item) {
            return <p key={`section-${i}`} className="text-[10px] uppercase tracking-wide text-white/30 px-3 pt-3 pb-1">{item.section}</p>;
          }
          const active = item.path === '/' ? pathname === '/' : pathname === item.path || pathname.startsWith(item.path + '/');
          return (
            <Link key={item.path} href={item.path}
              className={`flex items-center gap-2 px-3 py-2 rounded text-sm mb-1 transition-colors duration-150 ${active ? 'bg-brand-red text-white' : 'text-white/70 hover:bg-white/10'}`}>
              <item.icon size={16} />
              <span className={item.badge && counts.bySection[item.badge] ? 'font-semibold text-white' : ''}>{item.label}</span>
              {item.badge && <Badge n={counts.bySection[item.badge] || 0} />}
            </Link>
          );
        })}
      </nav>
      <div className="p-3 mt-auto border-t border-white/10 text-[10px] text-white/40">
        <p>{user?.role || '—'}</p>
      </div>
    </aside>
  );
}
