"use client";
// pages/_app.tsx

import { useEffect, useState } from "react";
import { Provider } from "react-redux";
import store, { useAppDispatch } from "../redux/store";
import { loadWindowVariables } from "../utils/loadWindowVariables";
import Header from "../components/header/Header";
import Navigation from "../components/navigation/Navigation";
import Footer from "../components/footer/Footer";
import WindowVariablesInitializer from "../components/WindowVariablesInitializer";
import "../styles/globals.css";
import { AppProps } from "next/app";

function MyApp({ Component, pageProps }: AppProps) {
  return (
    <Provider store={store}>
      <AppContent Component={Component} pageProps={pageProps} />
    </Provider>
  );
}

function AppContent({ Component, pageProps }: AppProps) {
  const dispatch = useAppDispatch();
  const [sessionExpired, setSessionExpired] = useState(false);

  useEffect(() => {
    const loadAndStoreVariables = async () => {
      try {
        const variables = await loadWindowVariables();
        if (!variables) throw new Error("Sitzungsfehler");

        //console.log("✅ Window-Variablen geladen:", variables);

        const { ...restVariables } = variables;

        setSessionExpired(false);
      } catch (error) {
        console.error("❌ Fehler beim Laden der Sitzung:", error);
        setSessionExpired(true);
      }
    };

    if (typeof window !== "undefined") {
      loadAndStoreVariables();

      const intervalId = setInterval(loadAndStoreVariables, 10000);
      return () => clearInterval(intervalId);
    }
  }, []);

  //---------------------------------------------------------

  return (
    <div className="flex flex-col h-screen overflow-hidden">
      <WindowVariablesInitializer />
      <Header />
      <div className="flex flex-grow w-full">
        <Navigation className="w-1/5" />
        <main className="w-full flex-grow">
          {sessionExpired && (
            <div className="bg-red-500 text-white p-4 text-center">
              ❌ Ihre Sitzung ist abgelaufen oder die Verbindung ist
              unterbrochen. Bitte laden Sie die Seite neu.
            </div>
          )}
          <Component {...pageProps} />
        </main>
      </div>
      <Footer />
    </div>
  );
}

export default MyApp;
