<?php
/**
 * Overflow trait — PHP CSS emit. Single primitive flat-suffix attr
 * `overflow` with explicit-clear sentinel handling. Mirrors JS
 * `buildOverflowDecls` byte-for-byte. NOT hover-aware (structural).
 *
 * @package Blocksify
 */

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

class Blocksify_Overflow_Trait {

	/**
	 * Attribute schema fragment. Mirror of `src/shared/traits/overflow.js`
	 * `attributes` const. See spacing trait header for rationale + sync rule.
	 */
	public static function attributes() {
		return array(
			'overflow'        => array( 'type' => array( 'string', 'null' ) ),
			'overflowTablet'  => array( 'type' => array( 'string', 'null' ) ),
			'overflowMobile'  => array( 'type' => array( 'string', 'null' ) ),
		);
	}

	/**
	 * Wrapper-rule overflow decl for one device + per-device explicit-
	 * clear sentinel (tablet/mobile null over a meaningful upstream emits
	 * `overflow:visible;`).
	 *
	 * @param string $part_prefix Optional part name (SPEC-trait-parts §3.3).
	 *                            Empty = root behavior (existing 6 blocks
	 *                            unchanged). Set = read prefixed attrs
	 *                            (`tabOverflow` / `tabOverflowTablet`).
	 */
	public static function emit_decls( $attrs, $device, $part_prefix = '' ) {
		$key   = Blocksify_Attrs::part_key( $part_prefix, 'overflow', $device );
		$value = isset( $attrs[ $key ] ) ? $attrs[ $key ] : null;
		$decls = self::build_decls( $value );
		if ( 'desktop' !== $device ) {
			$decls .= self::emit_explicit_clear( $attrs, $device, $part_prefix );
		}
		return $decls;
	}

	protected static function build_decls( $value ) {
		if ( ! is_string( $value ) || '' === $value ) {
			return '';
		}
		$allowed = array( 'visible', 'hidden', 'clip', 'auto', 'scroll' );
		if ( ! in_array( $value, $allowed, true ) ) {
			return '';
		}
		return 'overflow:' . $value . ';';
	}

	protected static function emit_explicit_clear( $attrs, $device, $part_prefix = '' ) {
		$base       = '' === $part_prefix ? 'overflow' : $part_prefix . 'Overflow';
		$key        = Blocksify_Attrs::part_key( $part_prefix, 'overflow', $device );
		if ( array_key_exists( $key, $attrs ) && is_null( $attrs[ $key ] )
			&& Blocksify_Attrs::has_upstream_value( $attrs, $base, $device ) ) {
			return 'overflow:visible;';
		}
		return '';
	}
}
