-- item_model.lua

-- 1. SETUP GLOBAL VARIABLES
global.pitchAngle = 0;
global.pitchAngleO = 0;
global.yawAngle = 0;
global.yawAngleO = 0;
global.fall = 0;
global.fall_f = 0;
global.chest_boat_anim = 1;

-- 2. PHYSICS CALCULATION
local l = data.bl and 1 or -1

if not P:isOnGround(data.player) and P:getYSpeed(data.player) * -1 > 0.55 then
    fall_f = fall_f + 0.045 * data.deltaTime * 30;
else
    fall_f = fall_f - 0.07 * data.deltaTime * 30
end
fall_f = M:clamp(fall_f, 0, 1)

local fallSpeed = (-1 * P:getYSpeed(data.player)) * 0.15 * data.deltaTime * 30
fall = fall + fallSpeed * data.deltaTime * 30
fall = fall * M:pow(0.85, data.deltaTime * 30) 

local ptAngle = data.mainHand and pitchAngle or pitchAngleO
local ywAngle = data.mainHand and yawAngle or yawAngleO

-- 3. ANIMATION LOGIC
if I:isIn(data.item, Tags:getVanillaTag("chest_boats")) then

    -- CONFIGURATION
    local LID_START = 0
    local LID_END = 11   

    -- PIVOT POINT (The Hinge)
    -- Y=0.375 is the rim height. Z=0.82 is the back of the chest.
    local PIVOT_X = 0.5
    local PIVOT_Y = 0.375  
    local PIVOT_Z = 0.81   

    -- SENSITIVITY
    local LOOK_WEIGHT = 0.8  
    local BOUNCE_WEIGHT = 20 

    -- === THE ANIMATION ===

    -- 1. CALCULATE RAW ANGLES
    local look_angle = ptAngle * LOOK_WEIGHT
    local bounce_angle = fall * BOUNCE_WEIGHT

    -- 2. APPLY CLOSING BIAS & CLAMP
    -- ' - 5 ' is the Closing Bias. It subtracts 5 degrees, forcing the lid to stay 
    -- tightly shut when you are just standing still or moving slightly.
    local raw_angle = (look_angle + bounce_angle) - 5

    -- Clamp strictly between 0 and 60.
    -- 0 = Fully Closed (Fixes clipping through bottom)
    -- 60 = Max Open (Fixes clipping into player face)
    local total_angle = M:clamp(raw_angle, 0, 60)

    -- 3. APPLY ROTATION
    animator:rotateX(LID_START, LID_END, total_angle * chest_boat_anim, PIVOT_X, PIVOT_Y, PIVOT_Z)
    
end