"use client";

import { useEffect, useRef, useState, type ReactNode } from "react";
import { useMediaQuery } from "@enode/core/use-media-query";

// Responsive left sidebar. Two modes driven by viewport width:
//   ≥1024px ("lg" breakpoint, the persistent threshold): renders inline as
//     a fixed-width column that takes up its own slot in the page flex row.
//     Toggling `open` animates the column width between `width` (expanded)
//     and either `railWidth` (when a `rail` is supplied — a thin always-on
//     spine) or 0 (when it isn't — fully collapsed).
//   <1024px: renders as a fixed-position overlay panel that slides in from
//     the left, with a tap-to-dismiss backdrop and Escape handling. When a
//     `rail` is supplied it also keeps an inline spine column so the toggle
//     and any spine actions stay reachable while collapsed.
//
// Children are instantiated once in either branch — the persistent column
// keeps them mounted across collapse/expand so their internal state
// survives the toggle.

const PERSISTENT_QUERY = "(min-width: 1024px)";
const DEFAULT_WIDTH = 320;
const DEFAULT_RAIL_WIDTH = 56;
const ANIMATION_MS = 300;

type Props = {
  open: boolean;
  onClose: () => void;
  ariaLabel: string;
  // Width of the expanded panel in px. Used for both modes so the open
  // sidebar reads the same on mobile and desktop.
  width?: number;
  // Optional collapsed-state content. When supplied, the collapsed sidebar
  // shrinks to a thin always-visible spine (`railWidth`) rendering this
  // instead of disappearing — host the expand toggle and any global actions
  // here. When omitted, the collapsed sidebar animates to 0 width (legacy).
  rail?: ReactNode;
  // Width of the collapsed spine in px. Only meaningful with `rail`.
  railWidth?: number;
  // Panel surface treatment. "flush" (default) paints the aside surface and
  // a right divider. "card" leaves the aside transparent with a 16px gutter
  // so the children render as a floating rounded card. (The collapsed `rail`
  // always renders flush/full-bleed even in card mode — see below — so a
  // spine can paint its own edge-to-edge background.) "bare" leaves the
  // persistent column transparent with no divider and no gutter, so the
  // children sit directly on the host's background (the portal, whose content
  // column is the card instead); its overlay panel (<1024px) looks like
  // "flush", since a drawer over the page needs a surface of its own.
  surface?: "flush" | "card" | "bare";
  // Collapsed-rail behaviour below the persistent breakpoint. "inline"
  // (default) keeps the spine in the page flow, reserving `railWidth`. "overlay"
  // drops the inline spine entirely on phones so the main content takes the full
  // width — the expanded panel is reached via the overlay (e.g. an edge-swipe or
  // floating toggle owned by the host).
  mobileRail?: "inline" | "overlay";
  // Min-width media query above which the sidebar is an inline column (rail
  // pinned / animated width) rather than a fixed overlay. Defaults to the lg
  // breakpoint; the tracking station shell lowers it so the rail pins on pads.
  persistentQuery?: string;
  // Applied to the panel surface (aside) in both modes.
  className?: string;
  children: ReactNode;
};

export function Sidebar({
  open,
  onClose,
  ariaLabel,
  width = DEFAULT_WIDTH,
  rail,
  railWidth = DEFAULT_RAIL_WIDTH,
  surface = "flush",
  mobileRail = "inline",
  persistentQuery = PERSISTENT_QUERY,
  className = "",
  children,
}: Props) {
  // SSR fallback `false` → static markup renders the overlay branch closed,
  // which produces no DOM. The first client tick re-evaluates and flips
  // to the persistent branch on wide viewports.
  const persistent = useMediaQuery(persistentQuery, false);
  const hasRail = rail != null;
  const isCard = surface === "card";
  const isBare = surface === "bare";
  // Card mode reserves a 16px gutter on every side (p-4) — enough room for
  // the card's shadow to live inside the overflow-hidden aside; the inner
  // content is sized to fill what's left so it doesn't reflow during the
  // animation. The gutter applies only to the EXPANDED panel: the collapsed
  // spine renders flush so it can paint an edge-to-edge background.
  const GUTTER = 32;

  if (persistent) {
    // Only the expanded panel floats inside the card gutter; the collapsed
    // spine is full-bleed.
    const gutterActive = isCard && open;
    const asideWidth = open ? width : hasRail ? railWidth : 0;
    const innerWidth = (open ? width : railWidth) - (gutterActive ? GUTTER : 0);
    const content = open ? children : hasRail ? rail : null;
    return (
      <aside
        aria-label={ariaLabel}
        style={{ width: asideWidth }}
        className={`shrink-0 overflow-hidden transition-[width] duration-300 ease-out ${
          isCard
            ? // Gutter only around the expanded panel; the spine and a
              // collapsed, rail-less card both render without padding. The
              // bottom gutter composes the safe-area inset so the floating
              // card ends above the Android gesture/task bar (edge-to-edge).
              gutterActive && content
              ? "px-4 pt-4 pb-[calc(1rem+env(safe-area-inset-bottom))]"
              : ""
            : isBare
              ? ""
              : `bg-surface-base ${
                open || hasRail ? "border-r border-surface-stroke" : ""
              }`
        } ${className}`}
      >
        {content && (
          <div style={{ width: innerWidth }} className="flex h-full flex-col">
            {content}
          </div>
        )}
      </aside>
    );
  }

  // Overlay (<1024px). With `mobileRail="inline"` the spine, when present,
  // stays inline so it reserves its own width in the page flow. With
  // `mobileRail="overlay"` the inline spine is dropped so the main content
  // takes the full width; the panel is reached through the overlay only.
  return (
    <>
      {hasRail && mobileRail === "inline" && (
        <aside
          aria-label={ariaLabel}
          style={{ width: railWidth }}
          className={`shrink-0 overflow-hidden ${
            isCard ? "" : "border-r border-surface-stroke bg-surface-base"
          } ${className}`}
        >
          <div style={{ width: railWidth }} className="flex h-full flex-col">
            {rail}
          </div>
        </aside>
      )}
      <OverlaySidebar
        open={open}
        onClose={onClose}
        ariaLabel={ariaLabel}
        width={width}
        isCard={isCard}
        className={className}
      >
        {children}
      </OverlaySidebar>
    </>
  );
}

function OverlaySidebar({
  open,
  onClose,
  ariaLabel,
  width,
  isCard,
  className,
  children,
}: {
  open: boolean;
  onClose: () => void;
  ariaLabel: string;
  width: number;
  isCard: boolean;
  className: string;
  children: ReactNode;
}) {
  // Mirrors the Sheet/DrawerStack lifecycle: `mounted` controls DOM presence,
  // `shown` drives the slide. Always start unmounted so the panel first paints
  // off-screen (-translate-x-full), then slides in — never rendered already-open.
  const [mounted, setMounted] = useState(false);
  const [shown, setShown] = useState(false);
  const panelRef = useRef<HTMLElement>(null);

  /* eslint-disable react-hooks/set-state-in-effect */
  // Mount on open; keep mounted through the slide-out before unmounting.
  useEffect(() => {
    if (open) {
      setMounted(true);
      return;
    }
    setShown(false);
    const t = window.setTimeout(() => setMounted(false), ANIMATION_MS);
    return () => window.clearTimeout(t);
  }, [open]);

  // Deterministic enter (same technique as DrawerStack/Sheet): once mounted and
  // still opening, force a reflow so the off-screen "from" transform is committed
  // to the layout, THEN flip `shown` to slide in. A forced reflow — not a fragile
  // double-rAF — makes the slide-in fire every time.
  useEffect(() => {
    if (!mounted || !open || shown) return;
    const el = panelRef.current;
    if (el) void el.offsetHeight;
    setShown(true);
  }, [mounted, open, shown]);
  /* eslint-enable react-hooks/set-state-in-effect */

  useEffect(() => {
    if (!mounted || !open) return;
    const handler = (e: KeyboardEvent) => {
      if (e.key === "Escape") onClose();
    };
    document.addEventListener("keydown", handler);
    return () => document.removeEventListener("keydown", handler);
  }, [mounted, open, onClose]);

  if (!mounted) return null;

  return (
    <>
      <div
        aria-hidden="true"
        onClick={onClose}
        className={`fixed inset-0 z-40 bg-black/40 transition-opacity duration-300 ${
          shown ? "opacity-100" : "pointer-events-none opacity-0"
        }`}
      />
      <aside
        ref={panelRef}
        role="dialog"
        aria-modal="true"
        aria-label={ariaLabel}
        // Cap to the viewport so the drawer never exceeds a narrow screen —
        // prefers `width`, shrinks below it on phones, always leaving a
        // backdrop strip to tap-dismiss.
        style={{ width: `min(${width}px, 85vw)` }}
        // Fixed overlay → escapes the body's global safe-area padding, so it pads
        // its own top for the status bar (portrait; env() ~0 on web / landscape).
        // The inset goes into each branch's top padding directly: pairing a `p-4`
        // shorthand with a separate env()-based top padding utility let the two
        // clobber each other, leaving the panel with no real top gutter.
        className={`fixed inset-y-0 left-0 z-50 flex flex-col transition-transform duration-300 ease-out ${
          isCard
            ? "px-4 pb-[calc(1rem+env(safe-area-inset-bottom))] pt-[calc(1rem+env(safe-area-inset-top))]"
            : "border-r border-surface-stroke bg-surface-base pt-[env(safe-area-inset-top)]"
        } ${shown ? "translate-x-0" : "-translate-x-full"} ${className}`}
      >
        {children}
      </aside>
    </>
  );
}
