import React, { useState, useEffect } from "react";
import Sidebar from "./Sidebar";
import axios from "axios";

export default function Layout({ children }) {
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchUser = async () => {
      try {
        const response = await axios.get("/api/me");
        setUser(response.data);
      } catch (error) {
        console.error("Auth error:", error);
        window.location.href = "/login";
      } finally {
        setLoading(false);
      }
    };

    fetchUser();
  }, []);

  if (loading) {
    return (
      <div className="flex items-center justify-center h-screen bg-gradient-to-br from-gray-50 to-primary-50">
        <div className="flex flex-col items-center gap-4">
          <div className="animate-spin rounded-full h-16 w-16 border-4 border-primary-600 border-t-transparent"></div>
          <p className="text-gray-600 font-medium">
            Loading Sarkin Mota Group...
          </p>
        </div>
      </div>
    );
  }

  return (
    <div className="flex min-h-screen bg-gradient-to-br from-slate-50 via-primary-50/20 to-slate-50">
      <Sidebar user={user} />
      <main className="flex-1 ml-0 lg:ml-64 transition-all duration-300">
        <div className="p-4">{React.cloneElement(children, { user })}</div>
      </main>
    </div>
  );
}
