<?php
/**
 * Brentwood Instructors — front-end render.
 *
 * A small bordered card with a title ("Instructors"), a circular user-tie badge
 * in the top-right corner, and a list of Staff names (filtered by the
 * `department` taxonomy). Clicking a name opens the SAME profile modal as the
 * Team Modal block — the trigger button carries the profile in an inert
 * <template class="bw-tm__full"> inside a .bw-tm__cell, and blocks/team-modal/
 * view.js (shared viewScript) clones it into the singleton modal.
 *
 * Mirrors the brentwood.ca course/program "Instructors" card.
 *
 * @var array    $attributes Block attributes.
 * @var string   $content    Inner content (unused — dynamic block).
 * @var WP_Block $block      Block instance.
 */

defined( 'ABSPATH' ) || exit;

require_once get_stylesheet_directory() . '/inc/bw-staff-profile.php';

// Display style: 'card' (bordered card, default), 'grid' (N-column name grid
// with the course-table hover), or 'inline' (comma-separated red text links that
// flow inside surrounding copy, like the live summer-camps "Camp Directors"
// list). All three keep the same shared profile modal.
$ds            = $attributes['displayStyle'] ?? 'card';
$display_style = in_array( $ds, array( 'grid', 'inline' ), true ) ? $ds : 'card';
$columns       = max( 1, min( 6, (int) ( $attributes['columns'] ?? 3 ) ) );

$posts = bw_staff_query( array(
	// Hand-picked staff apply to the inline variant only; other styles keep the
	// department filter (a stray staffIds left over from a style switch is ignored).
	'staffIds'     => ( 'inline' === $display_style ) ? ( $attributes['staffIds'] ?? array() ) : array(),
	'deptTerms'    => $attributes['deptTerms']    ?? array(),
	'deptRelation' => $attributes['deptRelation'] ?? 'IN',
	'orderby'      => $attributes['orderby']      ?? 'name_last',
	'order'        => $attributes['order']        ?? 'asc',
	'limit'        => $attributes['limit']        ?? 0,
	// Hand-picked staff to hide (card/grid only; the inline variant's own
	// hand-picked staffIds list short-circuits the query before this applies).
	'exclude'      => $attributes['exclude']      ?? array(),
) );
if ( empty( $posts ) ) {
	return;
}

$title = trim( (string) ( $attributes['title'] ?? '' ) );
if ( '' === $title ) {
	$title = 'Instructors';
}
$show_icon = ! empty( $attributes['showIcon'] );

// ── inline display ───────────────────────────────────────────────────────────
// One instructor per line: a red text link (opens the bio modal) optionally
// followed by manual text — e.g. "Megan Rae, Dance Program Lead at Brentwood
// College School" — mirroring the live summer-camps "Camp Directors" list. The
// per-name suffix comes from the staffAfter attribute (keyed by staff ID). No
// heading is rendered; place this block under your own "Camp Directors:" copy.
if ( 'inline' === $display_style ) {
	$after_map = ( isset( $attributes['staffAfter'] ) && is_array( $attributes['staffAfter'] ) ) ? $attributes['staffAfter'] : array();
	$rows = '';
	foreach ( $posts as $p ) {
		$name  = get_the_title( $p );
		$after = isset( $after_map[ $p->ID ] ) ? trim( (string) $after_map[ $p->ID ] ) : '';
		// $after comes from an inline RichText field (entity-encoded, no tags), so
		// strip any tags but keep entities as-is — esc_html() would double-encode.
		$after_html = ( '' !== $after )
			? '<span class="bw-instructor-inline__after">' . wp_kses( $after, array() ) . '</span>'
			: '';
		if ( bw_staff_has_profile( $p ) ) {
			$rows .= '<div class="bw-instructor-inline__row bw-tm__cell">'
				. '<button type="button" class="bw-instructor-inline__link bw-tm__open" data-tm-variant="feature" aria-haspopup="dialog">' . esc_html( $name ) . '</button>'
				. '<template class="bw-tm__full">' . bw_staff_profile_html( $p, 'h2', 'feature' ) . '</template>' // phpcs:ignore WordPress.Security.EscapeOutput -- escaped in helper
				. $after_html
				. '</div>';
		} else {
			// No profile → plain (non-clickable) name, still on its own line.
			$rows .= '<div class="bw-instructor-inline__row">'
				. '<span class="bw-instructor-inline__plain">' . esc_html( $name ) . '</span>'
				. $after_html
				. '</div>';
		}
	}

	printf(
		'<div %1$s>%2$s</div>',
		get_block_wrapper_attributes( array( 'class' => 'bw-instructor bw-instructor--inline' ) ), // phpcs:ignore WordPress.Security.EscapeOutput
		$rows // phpcs:ignore WordPress.Security.EscapeOutput -- assembled from escaped parts
	);
	return;
}

// FontAwesome user-tie, matching the live Instructors card badge.
$icon_badge = '';
if ( $show_icon ) {
	$icon_badge = '<span class="bw-instructor__badge" aria-hidden="true">'
		. '<svg viewBox="0 0 448 512" role="img" focusable="false">'
		. '<path fill="currentColor" d="M96 128a128 128 0 1 0 256 0A128 128 0 1 0 96 128zm94.5 200.2l18.6 31L175.8 483.1l-36-146.9c-2-8.1-9.8-13.4-17.9-11.3C51.9 342.4 0 405.8 0 481.3c0 17 13.8 30.7 30.7 30.7H162.5c0 0 0 0 .1 0H168 280h5.5c0 0 0 0 .1 0H417.3c17 0 30.7-13.8 30.7-30.7c0-75.5-51.9-138.9-121.9-156.4c-8.1-2-15.9 3.3-17.9 11.3l-36 146.9L238.9 359.2l18.6-31c6.4-10.7-1.3-24.2-13.7-24.2H224 204.3c-12.4 0-20.1 13.6-13.7 24.2z"/>'
		. '</svg></span>';
}

// ── grid display ─────────────────────────────────────────────────────────────
// A column grid of names (no card chrome), mirroring the course-table look: each
// cell has an underline that turns primary on hover. Clicking still opens the
// shared profile modal — the trigger keeps the bw-tm__cell / bw-tm__open /
// bw-tm__full contract the team-modal view script binds to.
if ( 'grid' === $display_style ) {
	$cells = '';
	foreach ( $posts as $p ) {
		$name = get_the_title( $p );
		if ( bw_staff_has_profile( $p ) ) {
			$cells .= '<div class="bw-instructor-grid__cell bw-tm__cell">'
				. '<button type="button" class="bw-instructor-grid__link bw-tm__open" aria-haspopup="dialog">' . esc_html( $name ) . '</button>'
				. '<template class="bw-tm__full">' . bw_staff_profile_html( $p ) . '</template>' // phpcs:ignore WordPress.Security.EscapeOutput -- escaped in helper
				. '</div>';
		} else {
			$cells .= '<div class="bw-instructor-grid__cell">'
				. '<span class="bw-instructor-grid__link bw-instructor-grid__link--plain">' . esc_html( $name ) . '</span>'
				. '</div>';
		}
	}

	printf(
		'<div %1$s><div class="bw-instructor-grid" style="--bw-ig-cols:%2$d">%3$s</div></div>',
		get_block_wrapper_attributes( array( 'class' => 'bw-instructor bw-instructor--grid' ) ), // phpcs:ignore WordPress.Security.EscapeOutput
		(int) $columns,
		$cells // phpcs:ignore WordPress.Security.EscapeOutput -- assembled from escaped parts above
	);
	return;
}

// ── card display (default) ───────────────────────────────────────────────────
$items = '';
foreach ( $posts as $p ) {
	$name = get_the_title( $p );
	if ( bw_staff_has_profile( $p ) ) {
		$items .= '<div class="bw-instructor__item bw-tm__cell">'
			. '<button type="button" class="bw-instructor__link bw-tm__open" aria-haspopup="dialog">' . esc_html( $name ) . '</button>'
			. '<template class="bw-tm__full">' . bw_staff_profile_html( $p ) . '</template>' // phpcs:ignore WordPress.Security.EscapeOutput -- escaped in helper
			. '</div>';
	} else {
		// Nothing to show in a modal → plain (non-clickable) name.
		$items .= '<div class="bw-instructor__item"><span class="bw-instructor__name">' . esc_html( $name ) . '</span></div>';
	}
}

printf(
	'<div %1$s>%2$s<div class="bw-instructor__head"><span class="bw-instructor__title">%3$s</span></div><div class="bw-instructor__list">%4$s</div></div>',
	get_block_wrapper_attributes( array( 'class' => 'bw-instructor' ) ), // phpcs:ignore WordPress.Security.EscapeOutput
	$icon_badge, // phpcs:ignore WordPress.Security.EscapeOutput -- safe literal SVG
	esc_html( $title ),
	$items // phpcs:ignore WordPress.Security.EscapeOutput -- assembled from escaped parts above
);
