var DEFAULT_CONFIG = {
    bogiePosition: 7.0,     
    soundId: "mtr:joint",   // 再生するサウンドID (ResourceLocation形式)
    volume: 1.0,            
    pitch: 1.0,
    playJointSound: true
};

function getConfig() {
    if (typeof JOINT_CONFIG !== 'undefined') {
        return {
            bogiePosition: JOINT_CONFIG.bogiePosition || DEFAULT_CONFIG.bogiePosition,
            soundId: JOINT_CONFIG.soundId || DEFAULT_CONFIG.soundId,
            volume: (JOINT_CONFIG.volume !== undefined) ? JOINT_CONFIG.volume : DEFAULT_CONFIG.volume,
            pitch: (JOINT_CONFIG.pitch !== undefined) ? JOINT_CONFIG.pitch : DEFAULT_CONFIG.pitch,
            playJointSound: (JOINT_CONFIG.playJointSound !== undefined) ? JOINT_CONFIG.playJointSound : DEFAULT_CONFIG.playJointSound
        };
    }
    return DEFAULT_CONFIG;
}

function create(ctx, state, train) {
    if (!state) state = {};
    state.bogieRailIds = {};
}

function render(ctx, state, train) {
    if (!state || !state.bogieRailIds) {
        state.bogieRailIds = {};
    }

    var config = getConfig();
    if (!config.playJointSound) return;

    var speed = train.speed() * 20; 
    if (Math.abs(speed) < 0.3) return;

    var carCount = train.trainCars();
    if (!carCount || carCount <= 0) return;

    var spacing = 20.0; 
    if (typeof train.spacing === 'function') {
        spacing = train.spacing();
    } else if (train.spacing) {
        spacing = train.spacing;
    }

    // ★ パス（ルート情報）の取得
    var path = train.path();
    if (!path) return; // ルートが設定されていない（車庫など）場合は終了

    var bogieOffsetFront = spacing / 2.0 - config.bogiePosition;
    var bogieOffsetRear  = spacing / 2.0 + config.bogiePosition;

    var pitch = speed / 12.5;
    var gain = pitch < 0.5 ? 2 * pitch : 1;

    for (var c = 0; c < carCount; c++) {
        var carProgress = (typeof train.getRailProgress === 'function') ? train.getRailProgress(c) : (train.railProgress() - (c * spacing));

        var bogies = [
            { offsetProgress: bogieOffsetFront, key: c + "_front" },
            { offsetProgress: bogieOffsetRear,  key: c + "_rear" }
        ];

        for (var i = 0; i < bogies.length; i++) {
            if (bogies[i].offsetProgress < 0) continue; 
            
            var bogieProgress = carProgress - bogies[i].offsetProgress;
            var railIndex = (typeof train.getRailIndex === 'function') ? train.getRailIndex(bogieProgress, false) : Math.floor(bogieProgress / 25.0);
            
            var lastIndex = state.bogieRailIds[bogies[i].key];
            
            if (lastIndex !== undefined && lastIndex !== railIndex) {
                // ★ railIndex が path の範囲内かチェック
                if (railIndex >= 0 && railIndex < path.size()) {
                    var pathData = path.get(railIndex);
                    if (pathData && pathData.startingPos) {
                        // BlockPos (int) から座標を取得
                        var bPos = pathData.startingPos;
                        
                        var soundPos = new Vector3f(bPos);
                        
                        playJointSound(config, soundPos, gain, pitch);
                    }
                }
            }
            state.bogieRailIds[bogies[i].key] = railIndex;
        }
    }
}

function dispose(ctx, state, train) {
    if (state && state.bogieRailIds) {
        state.bogieRailIds = null;
    }
}

function playJointSound(config, pos, gain, pitch) {
    var dynamicVolume = Math.min(1.0, gain * config.volume);
    var dynamicPitch = pitch * config.pitch;

    var soundId = Resources.id(config.soundId);

    // TickableSound を作成し、正確な「継ぎ目の座標」をセット
    var sound = new TickableSound(soundId);
    sound.setData(dynamicVolume, dynamicPitch, pos);
    sound.setLooping(false);
    SoundHelper.play(sound);
}