#include "PCSwitchShadowNode-custom.h"

#include <react/renderer/core/LayoutConstraints.h>
#include <algorithm>

namespace facebook::react {

Size MeasuringPCSwitchShadowNode::measureContent(
    const LayoutContext& /*layoutContext*/,
    const LayoutConstraints& layoutConstraints) const {

  // Native measures the switch and reports the row's one-line width and its
  // height at the laid-out width; Yoga clamps the width to the space there
  // is, and native reports the taller wrapped height after that layout.
  const auto& stateData = this->getStateData();
  Float measuredW = stateData.frameSize.width;
  Float measuredH = stateData.frameSize.height;

#ifdef __ANDROID__
  const Float fallbackHeight = static_cast<Float>(kFallbackHeightAndroid);
  const Float fallbackWidth = static_cast<Float>(kFallbackWidthAndroid);
#else
  const Float fallbackHeight = static_cast<Float>(kFallbackHeightIOS);
  const Float fallbackWidth = static_cast<Float>(kFallbackWidthIOS);
#endif

  const bool usingFallback = (measuredH <= 0);
  if (usingFallback) {
    measuredH = fallbackHeight;
  }
  if (measuredW <= 0) {
    measuredW = fallbackWidth;
  }

  const Float kHuge = static_cast<Float>(1.0e9);

  measuredW = std::max<Float>(measuredW, layoutConstraints.minimumSize.width);
  if (layoutConstraints.maximumSize.width > 0 && layoutConstraints.maximumSize.width < kHuge) {
    measuredW = std::min<Float>(measuredW, layoutConstraints.maximumSize.width);
  }

  measuredH = std::max<Float>(measuredH, layoutConstraints.minimumSize.height);
  // Only clamp to max height if we have real measured data (not fallback)
  if (!usingFallback && layoutConstraints.maximumSize.height > 0 && layoutConstraints.maximumSize.height < kHuge) {
    measuredH = std::min<Float>(measuredH, layoutConstraints.maximumSize.height);
  }

  return Size{measuredW, measuredH};
}

} // namespace facebook::react
