<?php
/**
 * Brentwood curved divider — a curved edge matching brentwood.ca (academics,
 * etc.), where a coloured text column bulges into the adjacent image with a
 * smooth convex edge.
 *
 * Available both as a block (bw/curve — choose Left/Right in the sidebar) and
 * as a [bw_curve] shortcode (kept for existing content). Both emit the same
 * marker; bw-curve.js relocates it into the adjacent image column and copies
 * the text section's background colour, so the curve follows the section colour
 * automatically.
 *
 * Knobs:
 *   side   right | left  — which neighbour the curve bulges into
 *   bleed  how far the curve bulges into the image (default 1rem, like live)
 *   width  ellipse width / gentleness (default 8rem, like live's w-32)
 *   height ellipse height as % of the section (default 150%, like live)
 *   color  force a colour (overrides the automatic section-colour detection)
 *
 * @package Kadence-Child
 */

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

add_action(
	'init',
	function () {
		$theme = get_stylesheet_directory();
		$uri   = get_stylesheet_directory_uri();
		wp_register_style( 'bw-curve', $uri . '/assets/bw-curve.css', array(), filemtime( $theme . '/assets/bw-curve.css' ) );
		wp_register_script( 'bw-curve', $uri . '/assets/bw-curve.js', array(), filemtime( $theme . '/assets/bw-curve.js' ), true );
	}
);

/**
 * Build the curve marker HTML and enqueue its assets. Shared by the shortcode
 * and the bw/curve block so both render identically.
 *
 * @param array $args side, color, bleed, width, height.
 * @return string
 */
function bw_curve_markup( $args ) {
	$a = wp_parse_args(
		$args,
		array(
			'side'   => 'right',
			'color'  => '',
			'bleed'  => '',
			'width'  => '',
			'height' => '',
		)
	);

	wp_enqueue_style( 'bw-curve' );
	wp_enqueue_script( 'bw-curve' );

	$side = ( 'left' === strtolower( (string) $a['side'] ) ) ? 'left' : 'right';

	$vars = array(
		'--bw-curve-color'  => $a['color'],
		'--bw-curve-bleed'  => $a['bleed'],
		'--bw-curve-width'  => $a['width'],
		'--bw-curve-height' => $a['height'],
	);
	$styles = array();
	foreach ( $vars as $prop => $val ) {
		if ( '' !== trim( (string) $val ) ) {
			$styles[] = $prop . ':' . $val;
		}
	}
	$style_attr = $styles ? ' style="' . esc_attr( implode( ';', $styles ) ) . '"' : '';
	$data_color = '' !== trim( (string) $a['color'] ) ? ' data-color="' . esc_attr( $a['color'] ) . '"' : '';

	return '<span class="bw-curve bw-curve--' . esc_attr( $side ) . '"' . $data_color . $style_attr
		. ' aria-hidden="true"><span class="bw-curve__shape"></span></span>';
}

/**
 * Bulge-as-a-Column-setting: instead of dropping a bw/curve block inside a
 * column, authors can flip "Column Curve" on the Kadence Column itself.
 * The editor UI (assets/bw-bulge-editor.js) declares the attributes; here we
 * (a) load that script early and (b) inject the same curve marker on render.
 */
add_action(
	'enqueue_block_editor_assets',
	function () {
		$theme = get_stylesheet_directory();
		$file  = $theme . '/assets/bw-bulge-editor.js';
		if ( ! file_exists( $file ) ) {
			return;
		}
		wp_enqueue_script(
			'bw-bulge-editor',
			get_stylesheet_directory_uri() . '/assets/bw-bulge-editor.js',
			array( 'wp-blocks', 'wp-element', 'wp-block-editor', 'wp-components', 'wp-compose', 'wp-hooks', 'wp-i18n' ),
			filemtime( $file ),
			true
		);
	},
	1 // before Kadence registers kadence/column, so our attribute filter is in place
);

/**
 * Load the curve preview stylesheet into the Gutenberg editor CANVAS so the
 * curve shows while editing (the front-end curve comes from bw-curve.css +
 * bw-curve.js, which can't run in the editor — see assets/bw-curve-editor.css).
 *
 * enqueue_block_assets fires for both contexts; styles enqueued here reach the
 * iframed canvas (unlike enqueue_block_editor_assets, which only reaches the
 * outer editor document). Gated on is_admin() so it loads in the editor only;
 * filemtime keeps it cache-busted on every edit. Mirrors the Red Border setup.
 */
add_action(
	'enqueue_block_assets',
	function () {
		if ( ! is_admin() ) {
			return;
		}
		$theme = get_stylesheet_directory();
		$file  = $theme . '/assets/bw-curve-editor.css';
		if ( ! file_exists( $file ) ) {
			return;
		}
		wp_enqueue_style(
			'bw-curve-editor',
			get_stylesheet_directory_uri() . '/assets/bw-curve-editor.css',
			array(),
			filemtime( $file )
		);
	}
);

/**
 * Front end: when a Kadence Column has the bulge enabled, inject the shared
 * curve marker just inside its inner wrapper. bw-curve.js then relocates it into
 * the adjacent image column and copies the section colour — identical to the
 * standalone bw/curve block, just sourced from the column's own setting.
 *
 * @param string $html  Rendered block HTML.
 * @param array  $block Parsed block (blockName, attrs, …).
 * @return string
 */
function bw_bulge_render_column( $html, $block ) {
	if ( ( $block['blockName'] ?? '' ) !== 'kadence/column' || ! function_exists( 'bw_curve_markup' ) ) {
		return $html;
	}
	$side = $block['attrs']['bwBulge'] ?? 'none';
	if ( 'left' !== $side && 'right' !== $side ) {
		return $html;
	}
	$marker = bw_curve_markup(
		array(
			'side'   => $side,
			'bleed'  => $block['attrs']['bwBleed'] ?? '',
			'width'  => $block['attrs']['bwWidth'] ?? '',
			'height' => $block['attrs']['bwHeight'] ?? '',
			'color'  => $block['attrs']['bwColor'] ?? '',
		)
	);
	// Inject as the first child of the column's INNER wrapper (.kt-inside-inner-col).
	// This matters: the column's background colour lives on .kt-inside-inner-col, and
	// bw-curve.js detects the colour by walking UP from the marker — so the marker must
	// sit inside that wrapper, exactly where the original nested bw/curve block lived.
	// preg_replace_callback avoids $-interpolation in the replacement.
	$count = 0;
	$out   = preg_replace_callback(
		'/<div\b[^>]*\bkt-inside-inner-col\b[^>]*>/',
		function ( $m ) use ( $marker ) {
			return $m[0] . $marker;
		},
		$html,
		1,
		$count
	);
	return $count ? $out : $marker . $html;
}
add_filter( 'render_block', 'bw_bulge_render_column', 12, 2 );

/**
 * [bw_curve] shortcode — thin wrapper over bw_curve_markup().
 *
 * @param array $atts Shortcode attributes.
 * @return string
 */
function bw_curve_shortcode( $atts ) {
	$a = shortcode_atts(
		array(
			'side'   => 'right',
			'color'  => '',
			'bleed'  => '',
			'width'  => '',
			'height' => '',
		),
		$atts,
		'bw_curve'
	);
	return bw_curve_markup( $a );
}
add_shortcode( 'bw_curve', 'bw_curve_shortcode' );
