import { useEffect, useState, type RefObject } from 'react';
import { Keyboard } from '@capacitor/keyboard';
import { Capacitor } from '@capacitor/core';

const scrollChatToBottom = (container: RefObject<HTMLDivElement | null>) => {
  requestAnimationFrame(() => {
    if (container.current) {
      container.current.scrollTop = container.current.scrollHeight;
    }
  });
};

/**
 * Eleva el área de input del chat cuando aparece el teclado (nativo + fallback web).
 */
export function useChatKeyboard(chatContainerRef: RefObject<HTMLDivElement | null>) {
  const [keyboardOffset, setKeyboardOffset] = useState(0);

  useEffect(() => {
    const onKeyboardOpen = (height: number) => {
      setKeyboardOffset(height);
      document.body.classList.add('keyboard-open');
      setTimeout(() => scrollChatToBottom(chatContainerRef), 80);
      setTimeout(() => scrollChatToBottom(chatContainerRef), 280);
    };

    const onKeyboardClose = () => {
      setKeyboardOffset(0);
      document.body.classList.remove('keyboard-open');
    };

    let showSub: { remove: () => Promise<void> } | undefined;
    let hideSub: { remove: () => Promise<void> } | undefined;

    const setupNative = async () => {
      showSub = await Keyboard.addListener('keyboardWillShow', (info) => {
        onKeyboardOpen(info.keyboardHeight);
      });
      hideSub = await Keyboard.addListener('keyboardWillHide', () => {
        onKeyboardClose();
      });
    };

    const setupVisualViewport = () => {
      const vv = window.visualViewport;
      if (!vv) return () => {};

      const update = () => {
        const offset = Math.max(0, window.innerHeight - vv.height - vv.offsetTop);
        if (offset > 50) {
          onKeyboardOpen(offset);
        } else {
          onKeyboardClose();
        }
      };

      vv.addEventListener('resize', update);
      vv.addEventListener('scroll', update);
      return () => {
        vv.removeEventListener('resize', update);
        vv.removeEventListener('scroll', update);
      };
    };

    let cleanupViewport: (() => void) | undefined;

    if (Capacitor.isNativePlatform()) {
      setupNative();
    } else {
      cleanupViewport = setupVisualViewport();
    }

    return () => {
      showSub?.remove();
      hideSub?.remove();
      cleanupViewport?.();
      document.body.classList.remove('keyboard-open');
    };
  }, [chatContainerRef]);

  const onInputFocus = () => {
    scrollChatToBottom(chatContainerRef);
    setTimeout(() => scrollChatToBottom(chatContainerRef), 300);
  };

  return { keyboardOffset, onInputFocus };
}
