'use client';

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

interface TableWrapperProps {
  children: React.ReactNode;
}

export default function TableWrapper({ children }: TableWrapperProps) {
  const wrapperRef = useRef<HTMLDivElement>(null);
  const [canScrollLeft, setCanScrollLeft] = useState(false);
  const [canScrollRight, setCanScrollRight] = useState(false);

  const updateScrollState = () => {
    if (!wrapperRef.current) return;

    const { scrollLeft, scrollWidth, clientWidth } = wrapperRef.current;
    setCanScrollLeft(scrollLeft > 0);
    setCanScrollRight(scrollLeft < scrollWidth - clientWidth - 1);
  };

  useEffect(() => {
    const wrapper = wrapperRef.current;
    if (!wrapper) return;

    // Initial check
    updateScrollState();

    // Update on scroll
    wrapper.addEventListener('scroll', updateScrollState);

    // Update on resize
    const resizeObserver = new ResizeObserver(updateScrollState);
    resizeObserver.observe(wrapper);

    // Check periodically for dynamic content
    const interval = setInterval(updateScrollState, 100);

    return () => {
      wrapper.removeEventListener('scroll', updateScrollState);
      resizeObserver.disconnect();
      clearInterval(interval);
    };
  }, []);

  return (
    <div
      ref={wrapperRef}
      className={`table-wrapper ${canScrollLeft ? 'scrollable-left' : ''} ${canScrollRight ? 'scrollable-right' : ''}`}
      style={{ overflowX: 'auto', margin: '2rem 0', width: '100%' }}
    >
      {children}
    </div>
  );
}

