'use client';

import { useEffect, useState, type ReactNode } from 'react';
import { useRouter } from 'next/navigation';
import { I18nProvider } from '@/lib/i18n';
import { ToastProvider } from '@/components/ui/Toast';
import { Navigation } from '@/components/Navigation';
import { isAuthenticated } from '@/lib/api';

export default function LocaleLayout({
  children,
  params,
}: {
  children: ReactNode;
  params: { locale: string };
}) {
  const router = useRouter();
  const [checked, setChecked] = useState(false);

  // Auth guard: redirect to /login if no token is present
  useEffect(() => {
    if (!isAuthenticated()) {
      router.replace('/login');
      return;
    }
    setChecked(true);
  }, [router]);

  // Show nothing while redirecting (avoids flashing protected content)
  if (!checked) {
    return (
      <div className="flex items-center justify-center h-screen bg-background">
        <div className="text-text-muted text-sm">Loading…</div>
      </div>
    );
  }

  const locale = params.locale === 'en' ? 'en' : 'de';

  return (
    <I18nProvider initialLocale={locale}>
      <ToastProvider>
        <div className="min-h-screen bg-background">
          <Navigation />
          {/* Main content area — offset for sidebar on desktop */}
          <main className="lg:ml-64 p-4 lg:p-8" data-testid="main-content">
            {children}
          </main>
        </div>
      </ToastProvider>
    </I18nProvider>
  );
}
