import { useEffect, useRef } from 'react';
import '../styles/MobileBottomSheet.css';

/**
 * Mobile bottom sheet.
 *
 * Slides up from below to cover most of the viewport. Backdrop dismisses on
 * tap. Drag handle at the top is decorative + clickable to close. ESC also
 * closes. Body scroll is locked while open so the user doesn't accidentally
 * pan the page underneath.
 *
 * Animation is CSS transform-based so it stays on the GPU and doesn't trigger
 * layout work — important on low-end devices where slide animations can chug
 * if they go through paint.
 *
 * Compact mode
 * ────────────
 * When `compact` is true, the sheet's max-height shrinks to ~55vh instead of
 * 78vh. The use case is text editing on mobile: the user types in the sheet
 * and watches the result render on the canvas above. With the full-height
 * sheet, the canvas is hidden behind the sheet and the user can't see what
 * they're typing. Compact mode leaves enough viewport above the sheet for
 * the canvas to remain visible.
 */
export function MobileBottomSheet({ open, onClose, children, compact = false }) {
  const sheetRef = useRef(null);

  // Lock body scroll while open. We intentionally toggle a class on <body>
  // rather than mutating style.overflow directly — that way other sources of
  // scroll-lock (e.g. the photo-editor modal) don't stomp each other.
  useEffect(() => {
    if (!open) return;
    document.body.classList.add('has-bottom-sheet');
    return () => document.body.classList.remove('has-bottom-sheet');
  }, [open]);

  // ESC to dismiss.
  useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === 'Escape') onClose?.(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open, onClose]);

  return (
    <div
      className={`mbs${open ? ' is-open' : ''}${compact ? ' is-compact' : ''}`}
      aria-hidden={!open}
    >
      <button
        type="button"
        className="mbs__backdrop"
        aria-label="Close"
        onClick={onClose}
        tabIndex={open ? 0 : -1}
      />
      <div
        ref={sheetRef}
        className="mbs__sheet"
        role="dialog"
        aria-modal="true"
        aria-label="Customization options"
      >
        <button
          type="button"
          className="mbs__handle"
          onClick={onClose}
          aria-label="Close"
        >
          <span className="mbs__handle-grip" aria-hidden="true" />
        </button>
        <div className="mbs__content">
          {children}
        </div>
      </div>
    </div>
  );
}
