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

/**
 * Altura extra (px) para elevar overlays fijos sobre el teclado.
 *
 * - iOS nativo: Capacitor Keyboard (keyboardWillShow).
 * - Android nativo: 0 — capacitor.config Keyboard.resize "body" ya encoge el WebView;
 *   sumar keyboardHeight duplica el espacio y achica el sheet.
 * - Web: visualViewport.
 */
export function useKeyboardOffset(active: boolean) {
  const [keyboardOffset, setKeyboardOffset] = useState(0);

  useEffect(() => {
    if (!active) {
      setKeyboardOffset(0);
      return;
    }

    const isAndroidNative = Capacitor.isNativePlatform() && Capacitor.getPlatform() === 'android';
    if (isAndroidNative) {
      return;
    }

    const open = (height: number) => {
      setKeyboardOffset(Math.max(0, Math.round(height)));
    };
    const close = () => setKeyboardOffset(0);

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

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

    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) {
          open(offset);
        } else {
          close();
        }
      };

      vv.addEventListener('resize', update);
      vv.addEventListener('scroll', update);
      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?.();
      setKeyboardOffset(0);
    };
  }, [active]);

  return keyboardOffset;
}

export function isAndroidNativeApp(): boolean {
  return Capacitor.isNativePlatform() && Capacitor.getPlatform() === 'android';
}
