import { Platform } from 'react-native';

/**
 * Adapted for HarmonyOS: UIManager.measure is not supported in Fabric mode.
 * Instead, we use ref.current.measure() which is the modern Fabric-compatible API.
 *
 * This function measures the component's position and calls ref._currentPosition
 * with the pageX/pageY coordinates, same as the original UIManager.measure approach.
 */
function updatePosition(ref: any, debug?: boolean): void {
  if (!ref) {
    return;
  }

  // Use ref.current.measure() for Fabric compatibility (works on all platforms including HarmonyOS)
  const measureTarget = ref.current || ref;
  if (measureTarget && typeof measureTarget.measure === 'function') {
    setTimeout(() => {
      measureTarget.measure(
        (x: number, y: number, width: number, height: number, pageX: number, pageY: number) => {
          if (debug) {
            console.log('updatePosition measure:', x, y, width, height, pageX, pageY);
          }
          if (ref._currentPosition) {
            ref._currentPosition(pageX, pageY);
          } else if (ref.current && ref.current._currentPosition) {
            ref.current._currentPosition(pageX, pageY);
          }
        }
      );
    }, 0);
  } else if (Platform.OS !== 'harmony') {
    // Fallback for non-HarmonyOS platforms: try UIManager.measure
    try {
      const ReactNative = require('react-native');
      const handle = ReactNative.findNodeHandle(ref);
      if (handle) {
        setTimeout(() => {
          ReactNative.NativeModules.UIManager.measure(
            handle,
            (x: number, y: number, width: number, height: number, pageX: number, pageY: number) => {
              if (debug) {
                console.log('updatePosition UIManager:', x, y, width, height, pageX, pageY);
              }
              if (ref && ref._currentPosition) {
                ref._currentPosition(pageX, pageY);
              }
            }
          );
        }, 0);
      }
    } catch (e) {
      if (debug) {
        console.log('updatePosition: measure failed', e);
      }
    }
  }
}

export default updatePosition;