// mariusson — PanelMount
// Animates a panel/dialog/drawer in AND out. Without this, panels using
// `{flag && <Panel />}` pop out instantly because React unmounts them on
// the same frame the flag flips false.
//
// Usage:
//   <PanelMount open={detailOpen}>
//     {(visible) => <DetailModal visible={visible} onClose={...} />}
//   </PanelMount>
//
// The child receives `visible` — true while it should be onscreen, false
// during exit. Inner components read `visible` to drive opacity/transform.
//
// Total exit duration is governed by `duration` (default 320ms).

function PanelMount({ open, duration = 320, children }) {
  const [rendered, setRendered] = React.useState(open);
  const [visible, setVisible] = React.useState(false);

  React.useEffect(() => {
    if (open) {
      setRendered(true);
      // Two RAFs: paint at "hidden" first, then transition to "visible".
      const r = requestAnimationFrame(() => {
        requestAnimationFrame(() => setVisible(true));
      });
      return () => cancelAnimationFrame(r);
    } else {
      setVisible(false);
      const t = setTimeout(() => setRendered(false), duration);
      return () => clearTimeout(t);
    }
  }, [open, duration]);

  if (!rendered) return null;
  return children(visible);
}

window.PanelMount = PanelMount;
