'use client';

import { useEffect, useRef } from 'react';

interface SheetProps {
  open: boolean;
  onClose: () => void;
  children: React.ReactNode;
}

/**
 * Sheet Component - Slide-up modal component
 *
 * A mobile-first slide-up sheet that displays content from the bottom.
 * On mobile, it takes full screen. On desktop (sm+), it shows as a centered card.
 *
 * Features:
 * - Backdrop dim overlay with tap-to-close
 * - Keyboard navigation (Escape to close)
 * - Responsive: full-screen on mobile, centered card on desktop
 * - Prevents body scroll when open
 * - Focus trap inside sheet when open
 */
export function Sheet({ open, onClose, children }: SheetProps) {
  const sheetRef = useRef<HTMLDivElement>(null);
  const previousActiveElement = useRef<HTMLElement | null>(null);

  // Handle Escape key
  useEffect(() => {
    const handleEscape = (e: KeyboardEvent) => {
      if (e.key === 'Escape' && open) {
        onClose();
      }
    };

    document.addEventListener('keydown', handleEscape);
    return () => document.removeEventListener('keydown', handleEscape);
  }, [open, onClose]);

  // Prevent body scroll when sheet is open
  useEffect(() => {
    if (open) {
      document.body.style.overflow = 'hidden';
      // Store current focused element to restore later
      previousActiveElement.current = document.activeElement as HTMLElement;

      // Focus the sheet when it opens
      setTimeout(() => {
        sheetRef.current?.focus();
      }, 100);
    } else {
      document.body.style.overflow = '';
      // Restore focus when closed
      if (previousActiveElement.current) {
        previousActiveElement.current.focus();
      }
    }

    return () => {
      document.body.style.overflow = '';
    };
  }, [open]);

  // Handle backdrop click
  const handleBackdropClick = (e: React.MouseEvent) => {
    if (e.target === e.currentTarget) {
      onClose();
    }
  };

  if (!open) {
    return null;
  }

  return (
    <div
      data-testid="sheet-backdrop"
      className="fixed inset-0 z-50 bg-black/50 animate-in fade-in duration-300"
      onClick={handleBackdropClick}
    >
      <div
        ref={sheetRef}
        tabIndex={-1}
        data-testid="sheet-content"
        className="fixed inset-x-0 bottom-0 z-50 bg-background shadow-lg animate-in slide-in-from-bottom-10 duration-300 sm:inset-y-auto sm:top-1/2 sm:-translate-y-1/2 sm:left-1/2 sm:-translate-x-1/2 sm:max-w-[600px] sm:w-full sm:max-h-[85vh] sm:rounded-lg sm:border h-[85vh] sm:h-auto sm:max-h-[85vh] overflow-y-auto"
        onClick={(e) => e.stopPropagation()} // Prevent click from propagating to backdrop
      >
        {children}
      </div>
    </div>
  );
}
