'use client';

import type { Metadata } from "next";
import { Geist, Geist_Mono } from "next/font/google";
import { ThemeProvider } from 'next-themes';
import ThemeToggle from '@/components/ThemeToggle';
import "./globals.css";
import { useEffect, useState } from "react";
import axios from 'axios';
import MaintenanceView from "@/components/layout/MaintenanceView";
import {jwtDecode} from 'jwt-decode';
import { API_BASE_URL } from "../../lib/api-config";

import Navbar from "@/components/layout/Navbar";

const geistSans = Geist({
  variable: "--font-geist-sans",
  subsets: ["latin"],
});

const geistMono = Geist_Mono({
  variable: "--font-geist-mono",
  subsets: ["latin"],
});

export default function RootLayout ({ children }: { children: React.ReactNode }) {

  const [isMaintenance, setIsMaintenance] = useState(false);
  const [isAdmin, setIsAdmin] = useState(false);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
   const checkStatus = async () => {
      try {
        const res = await axios.get(`${API_BASE_URL}/api/system-status`);
        setIsMaintenance(res.data.maintenanceMode);

        const token = document.cookie.split('; ').find(row => row.startsWith('wtihub_token'))?.split('=')[1];
        if (token) {
          const decoded: any = jwtDecode(token);
          if(decoded.role === 'admin') setIsAdmin(true);
        }

      } catch (error) {

        console.error('Error fetching system status:', error);

      } finally {
        setLoading(false);
      }
    }
    checkStatus();
  }, []);

  return (
    <html lang="en" className={`${geistSans.variable} ${geistMono.variable} h-full antialised`} suppressHydrationWarning>
      <body className="min-h-full flex flex-col bg-wtihub-bg text-wtihub-text"> <ThemeProvider attribute="class" defaultTheme="dark" enableSystem={false}>
        { loading ? (
           <div className="flex-1 flex items-center justify-center animate-pulse text-wtihub-green">
             Initializing Infrastructure...
           </div>
        ) : isMaintenance && !isAdmin ? (
          <MaintenanceView />
        ) : (
          <div className="min-h-screen flex flex-col">
            <Navbar />
            <main className="flex-1 flex flex-col">
               {children}
            </main>
            <ThemeToggle />
          </div>
        )} 
        </ThemeProvider>
      </body>
    </html>
  )
}