import React, { useState, useEffect, useCallback } from "react";
import { Outlet } from "react-router";
import { useAuth } from "../contexts/AuthContext";
import Navbar from "./Navbar";
import Footer from "./Footer";
import AuthModal from "./AuthModal";
import FeedbackButton from "./FeedbackButton";
import { TwoFactorVerifyModal } from "./TwoFactor";

const RootLayout: React.FC = () => {
  const { showAuthModal, authModalMode, closeAuthModal, user } = useAuth();

  // Step-up authentication state
  const [showStepUpModal, setShowStepUpModal] = useState(false);
  const [stepUpAction, setStepUpAction] = useState<string | undefined>();
  const [stepUpMethods, setStepUpMethods] = useState<("totp" | "email" | "recovery")[]>([]);

  // Listen for step-up authentication required events
  useEffect(() => {
    const handleStepUpRequired = (event: CustomEvent) => {
      const { action, methods } = event.detail;
      setStepUpAction(action);
      setStepUpMethods(methods || ["totp", "email", "recovery"]);
      setShowStepUpModal(true);
    };

    window.addEventListener("stepUpRequired", handleStepUpRequired as EventListener);

    return () => {
      window.removeEventListener("stepUpRequired", handleStepUpRequired as EventListener);
    };
  }, []);

  const handleStepUpSuccess = useCallback(() => {
    setShowStepUpModal(false);
    setStepUpAction(undefined);
    // Dispatch event so pending actions can auto-retry
    window.dispatchEvent(new CustomEvent("stepUpSuccess"));
  }, []);

  const handleStepUpClose = useCallback(() => {
    setShowStepUpModal(false);
    setStepUpAction(undefined);
  }, []);

  return (
    <>
      <div className="d-flex flex-column min-vh-100">
        <Navbar />
        <main className="flex-grow-1">
          <Outlet />
        </main>
        <Footer />
      </div>

      <AuthModal
        show={showAuthModal}
        onHide={closeAuthModal}
        initialMode={authModalMode}
      />

      {/* Show feedback button for authenticated users */}
      {user && <FeedbackButton />}

      {/* Global Step-Up Authentication Modal */}
      <TwoFactorVerifyModal
        show={showStepUpModal}
        onHide={handleStepUpClose}
        onSuccess={handleStepUpSuccess}
        action={stepUpAction}
        methods={stepUpMethods}
      />
    </>
  );
};

export default RootLayout;
