import { useEffect, useRef } from "react";
import { Outlet, useLocation } from "react-router-dom";
import { useTranslation } from "react-i18next";

import { LangSwitch } from "./lang-switch";
import { ThemeSwitch } from "./theme-switch";
import { Sidebar } from "./sidebar";
import { BreadcrumbProvider } from "./breadcrumb-provider";
import { Breadcrumb } from "./breadcrumb";
import { HeaderSearch } from "./header-search";
import { UserMenu } from "./user-menu";

export function AppShell() {
  const { t } = useTranslation();
  const location = useLocation();
  const mainRef = useRef<HTMLElement>(null);
  const didMount = useRef(false);

  useEffect(() => {
    if (!didMount.current) {
      didMount.current = true;
      return;
    }
    mainRef.current?.focus();
  }, [location.pathname]);

  return (
    <div className="flex min-h-screen">
      <a
        href="#main-content"
        className="sr-only focus:not-sr-only focus:absolute focus:left-2 focus:top-2 focus:z-50 focus:rounded-md focus:border focus:bg-background focus:px-3 focus:py-2 focus:text-sm focus:ring-3 focus:ring-ring/50"
      >
        {t("common.skipToContent")}
      </a>
      <Sidebar />
      <BreadcrumbProvider>
        <div className="flex flex-1 flex-col">
          <header className="flex items-center gap-4 border-b px-4 py-2">
            <Breadcrumb />
            <HeaderSearch />
            <ThemeSwitch />
            <LangSwitch />
            <UserMenu />
          </header>
          <main ref={mainRef} id="main-content" tabIndex={-1} className="flex-1 overflow-hidden outline-none">
            <Outlet />
          </main>
        </div>
      </BreadcrumbProvider>
    </div>
  );
}
