import { Outlet } from "react-router-dom";
import { useIsFetching } from "@tanstack/react-query";
import { cn } from "@/lib/utils";
import { Sidebar } from "./Sidebar";
import { SkipLink } from "@/components/ui/skip-link";
import { SearchBar } from "./SearchBar";

/**
 * App shell. Three columns:
 *  - Sidebar (240px, fixed)
 *  - Top bar (sticky, lightweight utility row)
 *  - Outlet (page content, max-w-[1400px] centered)
 *
 * The hairline scan element at the very top of the viewport is a 1px
 * line that slides an accent bar across the entire width whenever
 * the React Query layer has an in-flight request. The intent is to
 * surface "we're doing something" without a spinner — a moving line
 * reads as a sensor sweep, not a loading state.
 */
export function Layout() {
  const isFetching = useIsFetching();
  const showScan = isFetching > 0;

  return (
    <div className="relative min-h-screen z-10">
      <SkipLink />
      <div
        className="fixed top-0 left-0 right-0 z-50 h-px overflow-hidden pointer-events-none transition-opacity duration-200"
        style={{ opacity: showScan ? 1 : 0 }}
        aria-hidden
      >
        <div
          className="h-full w-1/3 bg-accent animate-scan"
          style={{ boxShadow: "0 0 8px hsl(var(--accent) / 0.5)" }}
        />
      </div>
      <Sidebar />
      <main
        id="main-content"
        tabIndex={-1}
        className="md:pl-60 outline-none"
      >
        <div
          className="sticky top-0 z-20 mx-auto max-w-[1400px] px-6 lg:px-8 h-12 flex items-center justify-end gap-3 bg-background/70 backdrop-blur-md border-b border-border/40"
          data-print="hide"
        >
          {/* Tailing pill on the left edge of the top bar — a tiny
              global "system is alive" indicator. It lights up whenever
              any query is in flight, complementing the hairline scan. */}
          <div className="mr-auto flex items-center gap-2 text-[10.5px] mono uppercase tracking-[0.14em] text-muted-foreground/60">
            <span className="relative inline-flex h-1.5 w-1.5">
              <span
                className={cn(
                  "absolute inline-flex h-full w-full rounded-full bg-[hsl(var(--success))] opacity-60",
                  showScan && "animate-ping"
                )}
              />
              <span className="relative inline-flex h-1.5 w-1.5 rounded-full bg-[hsl(var(--success))]" />
            </span>
            {showScan ? "Working" : "Idle"}
          </div>
          <SearchBar />
        </div>
        <div className="mx-auto max-w-[1400px] px-6 lg:px-8 py-8 lg:py-10">
          <Outlet />
        </div>
      </main>
    </div>
  );
}
