// src/components/dashboard/DashboardClientWrapper.tsx
'use client';

import { useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { useUserStore } from '@/stores/userStore';
import DashboardSidebar from './DashboardSidebar';
import DashboardHeader from './DashboardHeader';

export default function DashboardClientWrapper({
  children,
}: {
  children: React.ReactNode;
}) {
  const router = useRouter();
  const { user, isAuthenticated, setUser, setAuthenticated } = useUserStore();

  useEffect(() => {
    const checkAuth = async () => {
      if (!isAuthenticated || !user) {
        try {
          const response = await fetch('/api/frontend/user/profile', {
            credentials: 'include',
          });

          if (response.ok) {
            const data = await response.json();
            setUser(data.user);
            setAuthenticated(true);
          } else {
            router.push('/login');
          }
        } catch (error) {
          console.error('Auth check error:', error);
          router.push('/login');
        }
      }
    };

    checkAuth();
  }, [isAuthenticated, user, router, setUser, setAuthenticated]);

  if (!isAuthenticated || !user) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gray-50">
        <div className="text-center">
          <div className="w-16 h-16 border-4 border-gray-200 border-t-[#0066FF] rounded-full animate-spin mx-auto mb-4" />
          <p className="text-gray-600">Loading dashboard...</p>
        </div>
      </div>
    );
  }

  return (
    /*
      Outer wrapper: full viewport, flex ROW.
      - Sidebar sits on the left as a natural flex child (w-64, not fixed).
      - Content column takes all remaining width (flex-1).
      - No padding/margin hacks needed at all.
    */
    <div className="flex min-h-screen bg-gray-50">
      <DashboardSidebar user={user} />

      {/* Content column: flex-col so header stacks above main */}
      <div className="flex flex-col flex-1 min-w-0">
        <DashboardHeader user={user} />
        <main className="flex-1 p-6">
          {children}
        </main>
      </div>
    </div>
  );
}