import { useState, useRef, useCallback } from 'react';

export default function BottomSheet({ tabs, activeTab, onTabChange, children, className = '' }) {
  const [expanded, setExpanded] = useState(false);
  const startY = useRef(0);

  const handleTouchStart = useCallback((e) => {
    startY.current = e.touches[0].clientY;
  }, []);

  const handleTouchEnd = useCallback((e) => {
    const deltaY = e.changedTouches[0].clientY - startY.current;
    if (deltaY < -30) setExpanded(true);
    if (deltaY > 30) setExpanded(false);
  }, []);

  return (
    <div
      className={`bottom-sheet ${expanded ? 'expanded' : 'collapsed'} ${className}`}
      onTouchStart={handleTouchStart}
      onTouchEnd={handleTouchEnd}
    >
      <div className="bottom-sheet-handle" onClick={() => setExpanded(v => !v)}>
        <div className="bottom-sheet-handle-bar" />
        {!expanded && !tabs && (
          <span className="bottom-sheet-peek-label">Modulos ▲</span>
        )}
      </div>

      {tabs && tabs.length > 0 && (
        <div className="bottom-sheet-tabs" onClick={() => !expanded && setExpanded(true)}>
          {tabs.map(tab => (
            <button
              key={tab.id}
              className={`bottom-sheet-tab ${activeTab === tab.id ? 'active' : ''}`}
              onClick={() => { onTabChange?.(tab.id); setExpanded(true); }}
            >
              {tab.label}
              {activeTab === tab.id && <div className="bottom-sheet-tab-line" />}
            </button>
          ))}
        </div>
      )}

      {expanded && (
        <div className="bottom-sheet-content">
          {children}
        </div>
      )}
    </div>
  );
}
