import React, { useEffect, useState } from 'react';

type SheetProps = {
  opened: boolean;
  onClose: () => void;
  children: React.ReactNode;
  className?: string;
};

const Sheet = ({ opened, onClose, children, className = '' }: SheetProps) => {
  const [mounted, setMounted] = useState(opened);
  const [show, setShow] = useState(false);

  useEffect(() => {
    if (opened) {
      setMounted(true);
      requestAnimationFrame(() => setShow(true));
    } else {
      setShow(false);
      const t = setTimeout(() => setMounted(false), 220);
      return () => clearTimeout(t);
    }
  }, [opened]);

  if (!mounted) return null;

  return (
    <div className="fixed inset-0 z-[200] flex items-end justify-center">
      <div
        className={`absolute inset-0 bg-black/40 transition-opacity duration-200 ${
          show ? 'opacity-100' : 'opacity-0'
        }`}
        onClick={onClose}
      />
      <div
        className={`relative w-full max-w-[600px] rounded-t-2xl bg-[var(--tg-bg)]
          shadow-2xl pb-[max(env(safe-area-inset-bottom),12px)]
          transition-transform duration-200 ${className}
          ${show ? 'translate-y-0' : 'translate-y-full'}
        `}
      >
        <div className="flex justify-center pt-2">
          <div className="w-10 h-1 rounded-full bg-[var(--tg-divider)]" />
        </div>
        {children}
      </div>
    </div>
  );
};

export default Sheet;
