<?php
/**
 * Layout-oriented section builders for wp-agent/upsert-pattern.
 *
 * @package WPAgentCompanion
 */

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

/* ---------------------------------------------------------------------------
 * Sektions-Builder
 * ------------------------------------------------------------------------- */

/**
 * Hero: vollbreiter Block, zentriert. Grosse H1 (xx-large), gedämpfte Subheading
 * (large), optionaler Hook-Absatz und ein gefüllter Button.
 *
 * Ohne image_url ist der Hero ein farbiger core/group (backgroundColor + textColor).
 * MIT image_url wird er zu einem core/cover: das Bild ist der Hintergrund, darüber
 * liegt ein Farb-Overlay (overlayColor = aufgelöste Hero-Hintergrundfarbe, dimRatio
 * Default 50) und der bisherige Inhalt steht im inner-container. Damit der Text auf
 * dem Overlay lesbar bleibt, wird der Inhalt in einen core/group mit einer gegen den
 * Overlay-Slug aufgelösten, gut lesbaren Textfarbe gelegt (der core/heading-Helfer
 * trägt selbst keine Farbe, deshalb der umschliessende group statt Einzelfarben).
 */
function wpagent_pattern_build_hero( array $section ): string {
	$bg           = wpagent_pattern_pick_color( $section, 'backgroundColor', array( 'accent-3', 'primary', 'accent', 'secondary', 'tertiary' ) );
	$default_text = '' !== $bg ? wpagent_pattern_readable_text_color( $bg ) : wpagent_pattern_default_color( array( 'contrast', 'foreground', 'black', 'primary' ) );
	$text         = wpagent_pattern_pick_color( $section, 'textColor', array( $default_text ) );
	if ( '' === $bg && in_array( $text, array( 'base', 'background', 'white' ), true ) ) {
		$text = wpagent_pattern_default_color( array( 'contrast', 'foreground', 'black', 'primary' ), $text );
	}
	$inner = array();

	$heading = (string) ( $section['heading'] ?? '' );
	if ( '' !== trim( $heading ) ) {
		$inner[] = wpagent_pattern_block_heading( $heading, 1, 'xx-large', 'center' );
	}
	$sub = (string) ( $section['subheading'] ?? '' );
	if ( '' !== trim( $sub ) ) {
		$inner[] = wpagent_pattern_block_paragraph( $sub, 'large', 'center' );
	}
	$hook = (string) ( $section['text'] ?? '' );
	if ( '' !== trim( $hook ) ) {
		$inner[] = wpagent_pattern_block_paragraph( $hook, 'medium', 'center' );
	}
	list( $label, $url ) = wpagent_pattern_pick_button( $section, 'cta', 'button' );
	if ( '' !== $label ) {
		$inner[] = wpagent_pattern_block_button( $label, $url );
	}
	$inner_markup = implode( "\n\n", $inner );

	// Hintergrundbild-Variante: core/cover mit Farb-Overlay statt farbigem group.
	$image_url = trim( (string) ( $section['image_url'] ?? '' ) );
	if ( '' !== $image_url ) {
		$overlay = '' !== $bg
			? $bg
			: wpagent_pattern_default_color( array( 'contrast', 'primary', 'accent-3', 'foreground' ) );

		$dim_raw = $section['dimRatio'] ?? 50;
		$dim     = is_numeric( $dim_raw ) ? (int) $dim_raw : 50;
		$dim     = max( 0, min( 100, $dim ) );

		// Inhalt in einen group mit lesbarer Textfarbe legen (Heading kann keine Farbe tragen).
		$cover_text  = '' !== $overlay ? wpagent_pattern_readable_text_color( $overlay ) : '';
		$inner_group = wpagent_pattern_group(
			$inner_markup,
			array(
				'textColor' => $cover_text,
				'blockGap'  => '40',
				'layout'    => array( 'type' => 'constrained' ),
			)
		);

		return wpagent_pattern_block_cover(
			$image_url,
			trim( (string) ( $section['image_alt'] ?? '' ) ),
			$overlay,
			$dim,
			$inner_group,
			'full'
		);
	}

	return wpagent_pattern_group(
		$inner_markup,
		array(
			'align'           => 'full',
			'backgroundColor' => $bg,
			'textColor'       => $text,
			'padding'         => array( 'top' => '80', 'right' => '40', 'bottom' => '80', 'left' => '40' ),
			'blockGap'        => '40',
			'layout'          => array( 'type' => 'constrained' ),
		)
	);
}

/**
 * Features: vollbreites Band mit abwechselndem Hintergrund aus der Theme-Palette,
 * zentriertem H2 (x-large) plus optionaler Subheading und einem responsiven
 * Karten-Raster (core/group mit Grid-Layout) statt zerquetschter Spalten.
 */
function wpagent_pattern_build_features( array $section, int $parity = 0 ): string {
	$default_bg_candidates = 0 === $parity % 2
		? array( 'base', 'background', 'base-2' )
		: array( 'accent-5', 'base-2', 'tertiary', 'secondary' );
	$section_bg            = wpagent_pattern_pick_color( $section, 'backgroundColor', $default_bg_candidates );
	$section_text          = wpagent_pattern_pick_color( $section, 'textColor' );
	$card_bg               = wpagent_pattern_default_color(
		array( 'accent-5', 'base-2', 'tertiary', 'base', 'background' ),
		$section_bg
	);
	$muted_color           = '' !== $section_text ? '' : wpagent_pattern_muted_color();

	$inner = array();
	$heading = (string) ( $section['heading'] ?? '' );
	if ( '' !== trim( $heading ) ) {
		$inner[] = wpagent_pattern_block_heading( $heading, 2, 'x-large', 'center' );
	}
	$sub = (string) ( $section['subheading'] ?? '' );
	if ( '' !== trim( $sub ) ) {
		$inner[] = wpagent_pattern_block_paragraph( $sub, 'medium', 'center', $muted_color );
	}

	$grid = wpagent_pattern_build_card_grid( $section, $card_bg, '16rem' );
	if ( '' !== $grid ) {
		$inner[] = $grid;
	}

	return wpagent_pattern_group(
		implode( "\n\n", $inner ),
		array(
			'align'           => 'full',
			'backgroundColor' => $section_bg,
			'textColor'       => $section_text,
			'padding'         => array( 'top' => '70', 'right' => '40', 'bottom' => '70', 'left' => '40' ),
			'blockGap'        => '50',
			'layout'          => array( 'type' => 'constrained' ),
		)
	);
}

/**
 * Baut das Karten-Raster einer features-Sektion: pro Item eine Karte
 * (core/group mit Hintergrund, Rahmen, Radius, Padding) mit optionalem Badge,
 * H3-Titel, Absatz und optionalem Umriss-Button (cta_label/cta_url oder
 * button_label/button_url). Alle Karten liegen in einem Grid-core/group.
 */
function wpagent_pattern_build_card_grid( array $section, string $card_bg, string $min_col_width ): string {
	$items        = isset( $section['items'] ) && is_array( $section['items'] ) ? $section['items'] : array();
	$cards        = array();
	$badge_color  = wpagent_pattern_badge_color();
	$border_color = wpagent_pattern_border_color();
	$card_text    = '' !== $card_bg ? wpagent_pattern_card_text_color( $card_bg ) : '';

	foreach ( $items as $item ) {
		if ( ! is_array( $item ) ) {
			continue;
		}
		$card_inner = array();

		// Optionales Icon oben in der Karte (über Titel). Unbekannter/leerer Name
		// liefert '' und wird übersprungen (Karte bleibt valide).
		$icon = trim( (string) ( $item['icon'] ?? '' ) );
		if ( '' !== $icon ) {
			$icon_block = wpagent_pattern_block_icon( $icon );
			if ( '' !== $icon_block ) {
				$card_inner[] = $icon_block;
			}
		}

		$card_image = trim( (string) ( $item['image_url'] ?? '' ) );
		if ( '' !== $card_image ) {
			$card_alt     = trim( (string) ( $item['image_alt'] ?? ( $item['title'] ?? '' ) ) );
			$card_inner[] = wpagent_pattern_block_image( $card_image, $card_alt );
		}

		$badge = trim( (string) ( $item['badge'] ?? ( $item['label'] ?? '' ) ) );
		if ( '' !== $badge ) {
			$card_inner[] = wpagent_pattern_block_paragraph( $badge, 'small', '', $badge_color );
		}
		$title = (string) ( $item['title'] ?? '' );
		if ( '' !== trim( $title ) ) {
			$card_inner[] = wpagent_pattern_block_heading( $title, 3, 'large' );
		}
		$text = (string) ( $item['text'] ?? '' );
		if ( '' !== trim( $text ) ) {
			$card_inner[] = wpagent_pattern_block_paragraph( $text, 'medium' );
		}
		list( $label, $url ) = wpagent_pattern_pick_button( $item, 'cta', 'button' );
		if ( '' !== $label ) {
			$card_inner[] = wpagent_pattern_block_button( $label, $url, true );
		}

		if ( array() === $card_inner ) {
			continue;
		}

		$cards[] = wpagent_pattern_group(
			implode( "\n\n", $card_inner ),
			array(
				'backgroundColor' => $card_bg,
				'textColor'       => $card_text,
				'borderColor'     => $border_color,
				'borderWidth'     => '1px',
				'radius'          => '12px',
				'padding'         => array( 'top' => '40', 'right' => '40', 'bottom' => '40', 'left' => '40' ),
				'blockGap'        => '20',
				'layout'          => array( 'type' => 'constrained' ),
			)
		);
	}

	if ( array() === $cards ) {
		return '';
	}

	// align "wide": das Raster nutzt wideSize (1340px) statt contentSize (645px),
	// damit 3-4 Karten pro Reihe passen. Überschrift/Subheading bleiben mittig
	// auf contentSize (gute Lesebreite), nur das Raster geht in die Breite.
	return wpagent_pattern_group(
		implode( "\n\n", $cards ),
		array(
			'align'    => 'wide',
			'blockGap' => '40',
			'layout'   => array( 'type' => 'grid', 'minimumColumnWidth' => $min_col_width ),
		)
	);
}

/**
 * Media-Text: vollbreites Band mit einem core/media-text-Split-Layout (Bild neben
 * Text). Der Inhaltsbereich trägt H2, eine Unterzeile (text oder subheading) und
 * einen optionalen Button (cta_* oder button_*). Die Bildseite wechselt anhand von
 * $index (gerade: Bild links, ungerade: Bild rechts), sofern mediaPosition nicht
 * ausdrücklich gesetzt ist. Das media-text steht mit align "wide" in einem
 * vollbreiten, constrained core/group-Band mit optionalem Hintergrund.
 *
 * image_url ist Pflichtfeld dieser Sektion. Fehlt es, degradiert die Sektion sauber
 * zu einem zentrierten Textband (valide Core-Blöcke), statt ein leeres oder
 * ungültiges Medienfeld zu erzeugen.
 */
function wpagent_pattern_build_media_text( array $section, int $index = 0 ): string {
	$section_bg   = wpagent_pattern_pick_color( $section, 'backgroundColor' );
	$section_text = wpagent_pattern_pick_color( $section, 'textColor' );
	$muted_color  = '' !== $section_text ? '' : wpagent_pattern_muted_color();

	$image_url     = trim( (string) ( $section['image_url'] ?? '' ) );
	$content_align = '' === $image_url ? 'center' : '';

	// Inhaltsspalte: H2, Unterzeile (text bevorzugt, sonst subheading), Button.
	// Ohne Bild wird dieselbe Textfläche als zentriertes Fallback-Band gerendert.
	$content = array();
	$heading = (string) ( $section['heading'] ?? '' );
	if ( '' !== trim( $heading ) ) {
		$content[] = wpagent_pattern_block_heading( $heading, 2, 'x-large', $content_align );
	}
	$body = trim( (string) ( $section['text'] ?? '' ) );
	if ( '' === $body ) {
		$body = trim( (string) ( $section['subheading'] ?? '' ) );
	}
	if ( '' !== $body ) {
		$content[] = wpagent_pattern_block_paragraph( $body, 'medium', $content_align, $muted_color );
	}
	list( $label, $url ) = wpagent_pattern_pick_button( $section, 'cta', 'button' );
	if ( '' !== $label ) {
		$content[] = wpagent_pattern_block_button( $label, $url );
	}
	$inner = implode( "\n\n", $content );

	// Rückfall ohne Bild: zentriertes Textband statt eines leeren media-text.
	if ( '' === $image_url ) {
		return wpagent_pattern_group(
			$inner,
			array(
				'align'           => 'full',
				'backgroundColor' => $section_bg,
				'textColor'       => $section_text,
				'padding'         => array( 'top' => '70', 'right' => '40', 'bottom' => '70', 'left' => '40' ),
				'blockGap'        => '30',
				'layout'          => array( 'type' => 'constrained' ),
			)
		);
	}

	$image_alt = trim( (string) ( $section['image_alt'] ?? '' ) );
	$position  = strtolower( trim( (string) ( $section['mediaPosition'] ?? '' ) ) );
	if ( 'left' !== $position && 'right' !== $position ) {
		$position = 0 === $index % 2 ? 'left' : 'right';
	}

	$media_text = wpagent_pattern_block_media_text( $image_url, $image_alt, $inner, $position, 'wide' );

	return wpagent_pattern_group(
		$media_text,
		array(
			'align'           => 'full',
			'backgroundColor' => $section_bg,
			'textColor'       => $section_text,
			'padding'         => array( 'top' => '60', 'right' => '40', 'bottom' => '60', 'left' => '40' ),
			'blockGap'        => '40',
			'layout'          => array( 'type' => 'constrained' ),
		)
	);
}

/**
 * Logos ("bekannt aus"): vollbreites Band, optionales kleines Label und eine
 * mittige, umbrechende Reihe aus Text- oder Bild-Logos.
 */
function wpagent_pattern_build_logos( array $section ): string {
	$bg    = wpagent_pattern_pick_color( $section, 'backgroundColor', array( 'accent-5', 'base-2', 'tertiary', 'secondary', 'background' ) );
	$text  = wpagent_pattern_pick_color( $section, 'textColor' );
	$muted = '' !== $text ? '' : wpagent_pattern_muted_color();
	$inner = array();

	$heading = trim( (string) ( $section['heading'] ?? '' ) );
	if ( '' !== $heading ) {
		$inner[] = wpagent_pattern_block_paragraph( $heading, 'small', 'center', $muted );
	}

	$items = isset( $section['items'] ) && is_array( $section['items'] ) ? $section['items'] : array();
	$logos = array();
	foreach ( $items as $item ) {
		if ( ! is_array( $item ) ) {
			continue;
		}
		$img  = trim( (string) ( $item['image_url'] ?? '' ) );
		$name = trim( (string) ( $item['title'] ?? ( $item['text'] ?? '' ) ) );
		if ( '' !== $img ) {
			$logos[] = wpagent_pattern_block_image( $img, $name );
		} elseif ( '' !== $name ) {
			$logos[] = wpagent_pattern_block_paragraph( $name, 'large', '', $muted );
		}
	}

	if ( array() !== $logos ) {
		$inner[] = wpagent_pattern_group(
			implode( "\n\n", $logos ),
			array(
				'blockGap' => '40',
				'layout'   => array(
					'type'              => 'flex',
					'flexWrap'          => 'wrap',
					'justifyContent'    => 'center',
					'verticalAlignment' => 'center',
				),
			)
		);
	}

	return wpagent_pattern_group(
		implode( "\n\n", $inner ),
		array(
			'align'           => 'full',
			'backgroundColor' => $bg,
			'textColor'       => $text,
			'padding'         => array( 'top' => '60', 'right' => '40', 'bottom' => '60', 'left' => '40' ),
			'blockGap'        => '40',
			'layout'          => array( 'type' => 'constrained' ),
		)
	);
}

/**
 * CTA: vollbreiter, farbiger Block (Standard accent-1 gelb), zentriert, H2
 * (xx-large) plus optionale Subheading und ein prominenter Button. Akzeptiert
 * button_label/button_url UND cta_label/cta_url.
 */
function wpagent_pattern_build_cta( array $section ): string {
	$bg           = wpagent_pattern_pick_color( $section, 'backgroundColor', array( 'accent-1', 'primary', 'accent', 'secondary', 'tertiary' ) );
	$default_text = '' !== $bg ? wpagent_pattern_readable_text_color( $bg ) : wpagent_pattern_default_color( array( 'contrast', 'foreground', 'black' ) );
	$text         = wpagent_pattern_pick_color( $section, 'textColor', array( $default_text ) );
	$inner        = array();

	$heading = (string) ( $section['heading'] ?? '' );
	if ( '' !== trim( $heading ) ) {
		$inner[] = wpagent_pattern_block_heading( $heading, 2, 'xx-large', 'center' );
	}
	$sub = (string) ( $section['subheading'] ?? '' );
	if ( '' !== trim( $sub ) ) {
		$inner[] = wpagent_pattern_block_paragraph( $sub, 'large', 'center' );
	}
	list( $label, $url ) = wpagent_pattern_pick_button( $section, 'button', 'cta' );
	if ( '' !== $label ) {
		$inner[] = wpagent_pattern_block_button( $label, $url );
	}

	return wpagent_pattern_group(
		implode( "\n\n", $inner ),
		array(
			'align'           => 'full',
			'backgroundColor' => $bg,
			'textColor'       => $text,
			'padding'         => array( 'top' => '80', 'right' => '40', 'bottom' => '80', 'left' => '40' ),
			'blockGap'        => '40',
			'layout'          => array( 'type' => 'constrained' ),
		)
	);
}

/**
 * Pricing: vollbreites Band, H2 plus optionale Subheading und ein Karten-Raster
 * aus Preis-Plänen. Pro Plan: optionaler Badge, Plan-Name (H3), hervorgehobene
 * Preiszeile, Beschreibung und ein Button. featured hebt eine Karte mit einer
 * vorhandenen Akzentfarbe hervor und gibt ihr einen gefüllten statt Umriss-Button.
 */
function wpagent_pattern_build_pricing( array $section ): string {
	$section_bg   = wpagent_pattern_pick_color( $section, 'backgroundColor', array( 'accent-5', 'base-2', 'tertiary', 'secondary', 'background' ) );
	$section_text = wpagent_pattern_pick_color( $section, 'textColor' );
	$muted_color  = '' !== $section_text ? '' : wpagent_pattern_muted_color();
	$badge_color  = wpagent_pattern_badge_color();
	$border_color = wpagent_pattern_border_color();

	$inner = array();
	$heading = (string) ( $section['heading'] ?? '' );
	if ( '' !== trim( $heading ) ) {
		$inner[] = wpagent_pattern_block_heading( $heading, 2, 'x-large', 'center' );
	}
	$sub = (string) ( $section['subheading'] ?? '' );
	if ( '' !== trim( $sub ) ) {
		$inner[] = wpagent_pattern_block_paragraph( $sub, 'medium', 'center', $muted_color );
	}

	$items = isset( $section['items'] ) && is_array( $section['items'] ) ? $section['items'] : array();
	$cards = array();
	foreach ( $items as $item ) {
		if ( ! is_array( $item ) ) {
			continue;
		}
		$featured = ! empty( $item['featured'] );
		$card_bg  = $featured
			? wpagent_pattern_default_color( array( 'accent-1', 'primary', 'accent', 'secondary' ), $section_bg )
			: wpagent_pattern_default_color( array( 'base', 'background', 'base-2' ), $section_bg );
		$card_text = '' !== $card_bg ? wpagent_pattern_card_text_color( $card_bg ) : '';

		$card_inner = array();
		$card_image = trim( (string) ( $item['image_url'] ?? '' ) );
		if ( '' !== $card_image ) {
			$card_alt     = trim( (string) ( $item['image_alt'] ?? ( $item['title'] ?? '' ) ) );
			$card_inner[] = wpagent_pattern_block_image( $card_image, $card_alt );
		}
		$badge      = trim( (string) ( $item['badge'] ?? ( $item['label'] ?? '' ) ) );
		if ( '' !== $badge ) {
			$card_inner[] = wpagent_pattern_block_paragraph( $badge, 'small', 'center', $badge_color );
		}
		$title = trim( (string) ( $item['title'] ?? '' ) );
		if ( '' !== $title ) {
			$card_inner[] = wpagent_pattern_block_heading( $title, 3, 'large', 'center' );
		}
		$price = trim( (string) ( $item['price'] ?? '' ) );
		if ( '' !== $price ) {
			$card_inner[] = wpagent_pattern_block_paragraph( $price, 'xx-large', 'center', $card_text );
		}
		$text = trim( (string) ( $item['text'] ?? '' ) );
		if ( '' !== $text ) {
			$card_inner[] = wpagent_pattern_block_paragraph( $text, 'medium', 'center', $muted_color );
		}
		list( $label, $url ) = wpagent_pattern_pick_button( $item, 'cta', 'button' );
		if ( '' !== $label ) {
			$card_inner[] = wpagent_pattern_block_button( $label, $url, ! $featured );
		}

		if ( array() === $card_inner ) {
			continue;
		}

		$cards[] = wpagent_pattern_group(
			implode( "\n\n", $card_inner ),
			array(
				'backgroundColor' => $card_bg,
				'textColor'       => $card_text,
				'borderColor'     => $border_color,
				'borderWidth'     => '1px',
				'radius'          => '12px',
				'padding'         => array( 'top' => '50', 'right' => '40', 'bottom' => '50', 'left' => '40' ),
				'blockGap'        => '20',
				'layout'          => array( 'type' => 'constrained' ),
			)
		);
	}

	if ( array() !== $cards ) {
		$inner[] = wpagent_pattern_group(
			implode( "\n\n", $cards ),
			array(
				'align'    => 'wide',
				'blockGap' => '40',
				'layout'   => array( 'type' => 'grid', 'minimumColumnWidth' => '18rem' ),
			)
		);
	}

	return wpagent_pattern_group(
		implode( "\n\n", $inner ),
		array(
			'align'           => 'full',
			'backgroundColor' => $section_bg,
			'textColor'       => $section_text,
			'padding'         => array( 'top' => '70', 'right' => '40', 'bottom' => '70', 'left' => '40' ),
			'blockGap'        => '50',
			'layout'          => array( 'type' => 'constrained' ),
		)
	);
}
