import { Toaster } from "@/components/ui/sonner";
import { useSaveBar, useSettingsLoader } from "@/hooks/useSettings";
import { useUnsavedWarning } from "@/hooks/useUnsavedWarning";
import { __ } from "@wordpress/i18n";
import { Outlet, useLocation } from "react-router";
import AppHeader from "./components/AppHeader";
import SetupBanner from "./components/SetupBanner";
import LoadingState from "./components/LoadingState";
import SaveBar from "./components/SaveBar";

/**
 * Admin page frame: loads the settings, then shows the header with tabs,
 * the current tab and a sticky footer with the save status and buttons.
 */
export const RootLayout = () => {
  const { isLoading, isError } = useSettingsLoader();
  const { dirty } = useSaveBar();
  const wizard = useLocation().pathname === "/wizard";

  useUnsavedWarning(dirty);

  let content = <Outlet />;
  if (isLoading) {
    content = <LoadingState />;
  } else if (isError) {
    content = (
      <p role="alert" className="ino:text-sm ino:text-destructive">
        {__(
          "The settings couldn't be loaded. Reload the page to try again.",
          "product-comparison-for-woocommerce",
        )}
      </p>
    );
  }

  // The setup wizard has its own header and footer.
  if (wizard) {
    return (
      <div className="ino:min-h-screen ino:bg-muted/40 ino:font-sans ino:text-foreground">
        {content}
        <Toaster position="bottom-right" richColors />
      </div>
    );
  }

  return (
    <div className="ino:flex ino:min-h-screen ino:flex-col ino:bg-muted/40 ino:font-sans ino:text-foreground">
      <AppHeader />
      <main className="ino:flex-1 ino:px-8 ino:pt-7 ino:pb-12">
        {!isLoading && !isError && <SetupBanner />}
        {content}
      </main>
      {!isLoading && !isError && (
        <footer className="ino:sticky ino:bottom-0 ino:z-20 ino:flex ino:justify-end ino:border-t ino:border-border ino:bg-background/95 ino:px-8 ino:py-3 ino:backdrop-blur">
          <SaveBar />
        </footer>
      )}
      <Toaster position="bottom-right" richColors />
    </div>
  );
};

export default RootLayout;
