"use client";

import * as React from "react";

import { cn } from "@/lib/utils";

/**
 * Action bar (spec 01 §12.5): the end of a form. Right-aligned Cancel then the primary (rightmost); a
 * destructive action for the record sits on the left, apart from Save. `sticky` keeps it at the bottom of
 * long forms, with a shadow only while content is scrolling under it.
 *
 * "Under it" is measured, not guessed: a sentinel sits right after the bar in the flow; while the bar is
 * stuck, the sentinel is further down than the bar's bottom edge.
 */
export function ActionBar({ destructive, children, sticky = false, note, className }: { destructive?: React.ReactNode; children: React.ReactNode; sticky?: boolean; note?: React.ReactNode; className?: string }) {
  const barRef = React.useRef<HTMLDivElement>(null);
  const sentinelRef = React.useRef<HTMLDivElement>(null);
  const [stuck, setStuck] = React.useState(false);

  React.useEffect(() => {
    if (!sticky) return;
    const check = () => {
      const bar = barRef.current?.getBoundingClientRect();
      const end = sentinelRef.current?.getBoundingClientRect();
      if (bar && end) setStuck(end.top - bar.bottom > 1);
    };
    check();
    // Capture: also hears scrolls of any scrolling ancestor, not only the window.
    window.addEventListener("scroll", check, { capture: true, passive: true });
    window.addEventListener("resize", check);
    return () => {
      window.removeEventListener("scroll", check, { capture: true });
      window.removeEventListener("resize", check);
    };
  }, [sticky]);

  return (
    <>
      <div
        ref={barRef}
        role="group"
        aria-label="Form actions"
        className={cn(
          "flex flex-wrap items-center gap-2 bg-card py-3",
          sticky && "sticky bottom-0 z-10 -mx-4 border-t border-[var(--color-border-subtle)] px-4 transition-shadow",
          sticky && stuck && "shadow-[0_-4px_12px_-6px_rgb(0_17_16/0.18)]",
          className,
        )}
        data-stuck={sticky ? stuck : undefined}
      >
        {destructive ? <div className="mr-auto">{destructive}</div> : null}
        {note ? <p className={cn("text-xs text-muted-foreground", !destructive && "mr-auto")}>{note}</p> : null}
        {/* ml-auto keeps Cancel and the primary on the right, also when the bar wraps onto two lines. */}
        <div className="ml-auto flex items-center gap-2">{children}</div>
      </div>
      {sticky ? <div ref={sentinelRef} aria-hidden className="h-px" /> : null}
    </>
  );
}
