'use client';

import { useEffect } from 'react';
import { usePathname } from 'next/navigation';
import { useAuth } from '@/lib/auth-context';
import { RealtimeProvider, useRealtime } from '@/lib/realtime';
import { menuItemFor } from '@/lib/menu';
import Sidebar from '@/components/Sidebar';
import Header from '@/components/Header';
import Footer from '@/components/Footer';
import LockScreen from '@/components/LockScreen';

// Opening a page clears its menu badge (for pages that opt in via clearOnVisit).
function BadgeClearer() {
  const pathname = usePathname();
  const { accessToken } = useAuth();
  const { markRead } = useRealtime();
  useEffect(() => {
    const item = menuItemFor(pathname);
    if (!accessToken || !item?.badge || !item.clearOnVisit) return;
    const t = setTimeout(() => markRead(item.badge!), 800);
    return () => clearTimeout(t);
  }, [pathname, accessToken, markRead]);
  return null;
}

// middleware.ts lets the request through when the session cookie exists. What the person sees next:
//   • session valid            → the page
//   • session locked (idle / PC was off) → the page stays mounted underneath and the
//     lock screen asks for the 6-digit code only — nothing typed so far is lost
//   • no session at all        → the password login
export default function DashboardLayout({ children }: { children: React.ReactNode }) {
  const { user, loading, locked } = useAuth();
  const pathname = usePathname();

  if (loading) {
    return <div className="min-h-screen flex items-center justify-center text-sm text-gray-500 animate-fadeIn">Loading…</div>;
  }
  if (!user && !locked) {
    if (typeof window !== 'undefined') window.location.href = '/login';
    return null;
  }

  return (
    <RealtimeProvider>
      <BadgeClearer />
      <div className="flex">
        <Sidebar />
        <div className="flex-1 min-h-screen flex flex-col min-w-0">
          <Header />
          {/* key={pathname} remounts on route change, re-triggering the fade-in. */}
          <main key={pathname} className="p-6 animate-fadeInUp flex-1">{children}</main>
          <Footer />
        </div>
      </div>
      {locked && <LockScreen />}
    </RealtimeProvider>
  );
}
