<?php
/**
 * Audace — Convert each core/column's inline `flex-basis` into `width`,
 * adjusting for the columns container gap so N columns of X% really fit
 * X% of the visible row each.
 *
 * Formula: width = calc(VALUE - (var(--wp--style--block-gap, 0px) * (N-1) / N))
 */

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

add_filter( 'render_block_core/columns', function ( $content, $block ) {
    $children = isset( $block['innerBlocks'] ) ? $block['innerBlocks'] : array();
    $cols     = 0;
    foreach ( $children as $child ) {
        if ( isset( $child['blockName'] ) && $child['blockName'] === 'core/column' ) {
            $cols++;
        }
    }
    if ( $cols < 1 ) {
        return $content;
    }

    $factor = $cols > 1 ? ( $cols - 1 ) . '/' . $cols : '0';

    // Rewrite each inner column's flex-basis -> width.
    $content = preg_replace_callback(
        '/(<div\b[^>]*class="[^"]*\bwp-block-column\b[^"]*"[^>]*style=")([^"]*)(")/i',
        function ( $m ) use ( $factor ) {
            $style = $m[2];
            if ( ! preg_match( '/flex-basis\s*:\s*([^;]+)/i', $style, $fb ) ) {
                return $m[0];
            }
            $value = trim( $fb[1] );
            $style = preg_replace( '/flex-basis\s*:\s*[^;]+;?/i', '', $style );
            $style = trim( $style, " \t\n\r;" );

            $is_percent = (bool) preg_match( '/%\s*$/', $value );
            if ( $is_percent && $factor !== '0' ) {
                $width = "calc({$value} - (var(--wp--style--block-gap, 0px) * {$factor}))";
            } else {
                $width = $value;
            }

            $style .= ( $style === '' ? '' : ';' ) . 'width:' . $width;
            return $m[1] . $style . $m[3];
        },
        $content
    );

    return $content;
}, 10, 2 );
