import { useMemo } from "react";
import { useLocation, useMatches, useNavigate } from "react-router-dom";
import { Header } from "../components/Header";
import { BottomNav } from "../components/BottomNav";
import { AnimatedOutlet } from "../components/AnimatedOutlet";
import { AppBackground } from "../components/shared/AppBackground";
import { getLayoutBackgroundByPath } from "../../config/backgroundConfig";
import { defaultHeader, type AppRouteHandle } from "../navigation";

export function AppShell() {
  const location = useLocation();
  const navigate = useNavigate();
  const matches = useMatches();
  const isPublicChatPage = location.pathname === "/public-chat";

  const headerConfig = useMemo(() => {
    for (let index = matches.length - 1; index >= 0; index -= 1) {
      const handle = (matches[index].handle as AppRouteHandle | undefined)?.header;
      if (handle) {
        return handle;
      }
    }
    return defaultHeader;
  }, [matches]);

  return (
    <div className="app-viewport">
      <AppBackground
        position="fixed"
        zIndex={0}
        imageUrl={getLayoutBackgroundByPath(location.pathname)}
      />

      <div className="app-shell-frame">
        <div className="app-shell">
          <Header
            title={headerConfig.title}
            action={headerConfig.action}
            showBack={Boolean(headerConfig.showBack)}
            onBack={headerConfig.showBack ? () => navigate(headerConfig.backTo ?? "/") : undefined}
            onActionClick={
              headerConfig.action === "history"
                ? () => window.dispatchEvent(new CustomEvent("public-chat:history"))
                : undefined
            }
          />

          <AnimatedOutlet />

          {!isPublicChatPage && <BottomNav fixed={false} />}
        </div>
      </div>
    </div>
  );
}
