"use client";

import type { ReactNode } from "react";

/**
 * A section that eases open and shut around whatever it wraps.
 *
 * @param open - Whether the content is revealed. The children stay mounted
 *   either way, so state inside them survives a collapse.
 *
 * @remarks
 * Animates `grid-template-rows` from `0fr` to `1fr` rather than a height or a
 * `max-height`. That means the open height is the content's natural height — no
 * measuring, and no max-height guess that clips tall content or adds a pause
 * before short content finishes opening. The inner `min-h-0 overflow-hidden`
 * wrapper is what makes the grid row actually shrink.
 *
 * While closed the wrapper is `inert`, so the hidden content is neither
 * focusable nor in the accessibility tree; pair the trigger with
 * `aria-expanded` so the state is announced. The transition only runs on a
 * change of `open`, so an initially open section renders at full height with no
 * mount animation. Under `prefers-reduced-motion` the section switches without
 * a transition.
 *
 * Drop-in for `{expanded && <Body />}`:
 * `<Collapsible open={expanded}><Body /></Collapsible>`.
 */
export function Collapsible({
  open,
  children,
}: {
  open: boolean;
  children: ReactNode;
}) {
  return (
    <div
      className="grid w-full transition-[grid-template-rows,opacity] duration-300 ease-out motion-reduce:transition-none"
      style={{
        gridTemplateRows: open ? "1fr" : "0fr",
        opacity: open ? 1 : 0,
      }}
      inert={!open}
    >
      <div className="min-h-0 overflow-hidden">{children}</div>
    </div>
  );
}
