using UnityEngine;

public static class PhysicalRaiseSelectionMath
{
    public static int ChipsInColumn(int totalChips, int column, int stackHeight)
    {
        if (totalChips <= 0 || column < 0) return 0;
        int height = Mathf.Max(1, stackHeight);
        return Mathf.Clamp(totalChips - column * height, 0, height);
    }

public static int SelectionCount(float columnTopWorldY, float handWorldY,
        float chipWorldHeight, int displayedChips, int stackHeight)
    {
        if (displayedChips <= 0 || chipWorldHeight <= 0f) return 0;
        float depth = (columnTopWorldY - handWorldY) / chipWorldHeight;
        int maximum = Mathf.Min(displayedChips, Mathf.Max(1, stackHeight));
        return Mathf.Clamp(Mathf.CeilToInt(depth - 0.0001f), 0, maximum);
    }

    /// <summary>
    /// World position for the carried amount readout. The hand's forward axis is treated as the
    /// arm-to-hand direction, and the offset vector hangs off the end of that "stick" in a frame
    /// whose +Z follows the arm and whose +Y stays world up, so the readout tracks hand motion
    /// without flipping between hands.
    /// </summary>
public static Vector3 HandPoint(Vector3 handPosition, Quaternion handRotation, Vector3 handOffset)
    {
        Quaternion frame;
        if (!TryArmFrame(handRotation, out frame)) return handPosition;
        return handPosition + frame * handOffset;
    }

    /// <summary>
    /// The arm-aligned frame shared by <see cref="HandPoint"/> and <see cref="SolveHandOffset"/>: +Z along the
    /// arm-to-hand direction, +Y world up (falling back to the hand's own up when the arm points straight up/down).
    /// </summary>
    public static bool TryArmFrame(Quaternion handRotation, out Quaternion frame)
    {
        frame = Quaternion.identity;
        Vector3 armToHand = handRotation * Vector3.forward;
        if (armToHand.sqrMagnitude < 0.000001f) return false;
        armToHand.Normalize();
        Vector3 up = Vector3.up;
        if (Mathf.Abs(Vector3.Dot(armToHand, up)) > 0.999f) up = handRotation * Vector3.up;
        frame = Quaternion.LookRotation(armToHand, up);
        return true;
    }

    /// <summary>
    /// Inverse of <see cref="HandPoint"/>: the arm-frame offset that places the hand point on targetWorld.
    /// Returns false when the arm pose is unusable (degenerate rotation, or pointing within ~25 degrees of
    /// vertical where the frame flips between up references).
    /// </summary>
    public static bool SolveHandOffset(Vector3 handPosition, Quaternion handRotation, Vector3 targetWorld,
        out Vector3 offset)
    {
        offset = Vector3.zero;
        Quaternion frame;
        if (!TryArmFrame(handRotation, out frame)) return false;
        if (Mathf.Abs(Vector3.Dot(handRotation * Vector3.forward, Vector3.up)) > 0.9f) return false;
        offset = Quaternion.Inverse(frame) * (targetWorld - handPosition);
        return true;
    }

    /// <summary>
    /// Offsets are stored in left-hand space. In the arm frame +X is to the right of the arm, so a right hand needs
    /// the lateral component flipped to sit on the same spot relative to the body. It is its own inverse, so it
    /// also converts a right-hand calibration into left-hand space. In VR both hands' forward axes point along the
    /// arm, so only the lateral component differs.
    /// </summary>
    public static Vector3 MirrorOffsetForHand(Vector3 offset, bool isRightHand)
    {
        return isRightHand ? new Vector3(-offset.x, offset.y, offset.z) : offset;
    }

    /// <summary>Avatar scale relative to the 0.8m eye height that the tuned offsets were authored for.</summary>
    public static float ScaleFactor(float eyeHeightMeters)
    {
        if (float.IsNaN(eyeHeightMeters) || eyeHeightMeters <= 0f) return 1f;
        return Mathf.Clamp(eyeHeightMeters / ReferenceEyeHeight, MinScale, MaxScale);
    }

    public const float ReferenceEyeHeight = 0.8f;
    public const float MinScale = 0.2f;
    public const float MaxScale = 5f;
    public const float MaxOffsetComponent = 0.3f;

    public static bool IsPlausibleOffset(Vector3 offset)
    {
        return IsFinite(offset.x) && IsFinite(offset.y) && IsFinite(offset.z)
            && Mathf.Abs(offset.x) <= MaxOffsetComponent
            && Mathf.Abs(offset.y) <= MaxOffsetComponent
            && Mathf.Abs(offset.z) <= MaxOffsetComponent;
    }

    private static bool IsFinite(float value)
    {
        return !float.IsNaN(value) && !float.IsInfinity(value);
    }
}
