import React, { useEffect } from 'react';
import { useFocusable } from '@noriginmedia/norigin-spatial-navigation';
import { useInputMode } from '../context/InputModeContext';

export interface FocusableItemProps {
  onFocus: () => void;
  onEnterPress?: () => void;
  children: (focused: boolean) => React.ReactNode;
  className?: string;
  focusKey?: string;
  scrollOptions?: ScrollIntoViewOptions;
  active?: boolean;
  onClick?: () => void;
}

export const FocusableItem = ({ onFocus, onEnterPress, onClick, children, className, focusKey, scrollOptions, active }: FocusableItemProps) => {
  const { mode } = useInputMode();
  const { ref, focused: rawFocused, focusKey: internalFocusKey } = useFocusable({
    onFocus,
    onEnterPress,
    focusKey
  });

  const focused = mode !== 'mouse' ? rawFocused : false;

  useEffect(() => {
    if (mode !== 'mouse' && (focused || active) && ref.current) {
      if (scrollOptions) {
        ref.current.scrollIntoView(scrollOptions);
      } else {
        ref.current.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'center' });
      }
    }
  }, [focused, active, mode, scrollOptions]);

  return (
    <div 
      ref={ref} 
      data-focusable-key={internalFocusKey} 
      className={`${className} ${focused ? 'focused' : ''}`}
      onClick={() => {
        if (onClick) onClick();
      }}
    >
      {children(focused)}
    </div>
  );
};
