<?php
/**
 * File Path: templates/admin/author-card.php
 *
 * Admin Template — Single Author Card
 *
 * Renders the collapsible <details>/<summary> card for one author term on
 * the Settings → Authors tab. Wraps the card in its own <form> so each
 * author saves independently via the PRG pattern in MBS_Tab_Authors.
 *
 * Expected variables (passed via mbs_get_template_part() $args):
 *   WP_Term $author         The author taxonomy term.
 *   int     $term_id        Author term ID.
 *   int     $photo_id       Attachment ID of current photo (0 if none).
 *   string  $bio            Author bio (may contain basic HTML).
 *   string  $website        Author website URL (sanitized).
 *   string  $birth_year     Four-digit birth year (LOC authority control); '' if unknown.
 *   string  $term_layout    Saved per-term layout slug ('' = use global default).
 *   string  $photo_url      Current photo URL (empty string if none).
 *   int     $book_count     Number of books assigned to this author.
 *   bool    $is_open        Whether this card should start expanded.
 *   string  $initial        First character of author name (for placeholder avatar).
 *   string  $edit_url       URL to the WordPress term-edit screen for this author.
 *   array   $social_links   Decoded social links from mbs_author_social_links meta.
 *   array   $platforms       MBS_Author_Social_Links::PLATFORMS grouped platform registry.
 *   bool    $is_featured         Whether this author is marked as featured (F-015).
 *   string  $name_titles_before  Honorific / title before name (Dr., Sir, Prof.).
 *   string  $name_before_key     First name(s) / middle name (ONIX NamesBeforeKey).
 *   string  $name_prefix_to_key  Surname particle (van der, de, von) (ONIX PrefixToKey).
 *   string  $name_key            Sorting surname / key name (ONIX KeyNames).
 *   string  $name_after_key      Generational suffix (Jr., III) (ONIX NamesAfterKey).
 *   string  $name_letters        Professional credentials (PhD, OBE) (ONIX LettersAfterNames).
 *   string  $name_inverted       Inverted name (ONIX PersonNameInverted); auto-computed when blank.
 *
 * @package MyBookShowroom
 * @since   1.0.0
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- template-scope variables injected by mbs_get_template_part(); not global vars

$author_name_lower = function_exists( 'mb_strtolower' ) ? mb_strtolower( $author->name ) : strtolower( $author->name );
?>
<form method="post" action="" class="mbs-author-card-form mbs-entity-card-form" data-name="<?php echo esc_attr( $author_name_lower ); ?>">
	<details class="mbs-settings-card mbs-author-card mbs-entity-card"<?php echo $is_open ? ' open' : ''; ?>>
		<summary class="mbs-author-card-summary mbs-entity-card-summary">
			<?php if ( $photo_url ) : ?>
				<img class="mbs-author-card-thumb" src="<?php echo esc_url( $photo_url ); ?>" alt="">
			<?php else : ?>
				<span class="mbs-author-card-thumb-placeholder" aria-hidden="true"><?php echo esc_html( strtoupper( $initial ) ); ?></span>
			<?php endif; ?>
			<span class="mbs-author-card-heading mbs-entity-card-heading">
				<span class="mbs-author-card-name mbs-entity-card-name"><?php echo esc_html( $author->name ); ?></span>
				<span class="mbs-author-card-meta mbs-entity-card-meta">
					<?php /* translators: %d: number of books */ printf( esc_html( _n( '%d book', '%d books', $book_count, 'my-book-showroom' ) ), $book_count ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- esc_html(_n()) escapes format string; $book_count is a term count integer ?>
				</span>
			</span>
		</summary>

		<div class="mbs-author-card-body mbs-entity-card-body">

			<div class="mbs-entity-card-nav-links">
				<a class="mbs-author-card-edit-term mbs-entity-card-edit-link" href="<?php echo esc_url( $edit_url ); ?>">
					<?php esc_html_e( 'Edit slug in WordPress →', 'my-book-showroom' ); ?>
				</a>
				<?php
				$_mbs_view_url = get_term_link( $author );
				if ( ! is_wp_error( $_mbs_view_url ) ) :
				?>
				<a class="mbs-author-card-view-term mbs-entity-card-view-link button button-secondary button-small"
				   href="<?php echo esc_url( $_mbs_view_url ); ?>"
				   target="_blank"
				   rel="noopener noreferrer">
					<?php esc_html_e( 'View Author →', 'my-book-showroom' ); ?>
				</a>
				<?php endif; ?>
			</div>

			<?php wp_nonce_field( 'mbs_authors_save', 'mbs_authors_nonce' ); ?>
			<input type="hidden" name="mbs_save_author_id" value="<?php echo esc_attr( $term_id ); ?>">

			<?php mbs_get_template_part( 'admin/author-photo-field', array(
				'term_id'    => $term_id,
				'photo_id'   => $photo_id,
				'photo_url'  => $photo_url,
				'preview_id' => 'mbs-author-photo-preview-' . $term_id,
				'input_id'   => 'mbs-author-photo-id-' . $term_id,
			) ); ?>

			<details class="mbs-author-name-structure">
				<summary><?php esc_html_e( 'Name structure (for sorting &amp; ONIX)', 'my-book-showroom' ); ?></summary>
				<div class="mbs-author-name-structure-body">
					<p class="description"><?php esc_html_e( 'Optional. Used for last-name sorting and ONIX export. Leave blank if not applicable.', 'my-book-showroom' ); ?></p>
					<div class="mbs-author-name-grid">
						<div class="mbs-settings-field-cell">
							<label for="mbs-name-titles-before-<?php echo esc_attr( $term_id ); ?>"><?php esc_html_e( 'Title / Honorific', 'my-book-showroom' ); ?></label>
							<input type="text"
							       id="mbs-name-titles-before-<?php echo esc_attr( $term_id ); ?>"
							       name="mbs_name_titles_before[<?php echo esc_attr( $term_id ); ?>]"
							       value="<?php echo esc_attr( $name_titles_before ); ?>"
							       placeholder="<?php esc_attr_e( 'Dr., Sir, Prof.', 'my-book-showroom' ); ?>">
						</div>
						<div class="mbs-settings-field-cell">
							<label for="mbs-name-before-key-<?php echo esc_attr( $term_id ); ?>"><?php esc_html_e( 'First / middle name(s)', 'my-book-showroom' ); ?></label>
							<input type="text"
							       id="mbs-name-before-key-<?php echo esc_attr( $term_id ); ?>"
							       name="mbs_name_before_key[<?php echo esc_attr( $term_id ); ?>]"
							       value="<?php echo esc_attr( $name_before_key ); ?>"
							       placeholder="<?php esc_attr_e( 'Mary Jo, John A.', 'my-book-showroom' ); ?>">
						</div>
						<div class="mbs-settings-field-cell">
							<label for="mbs-name-prefix-to-key-<?php echo esc_attr( $term_id ); ?>"><?php esc_html_e( 'Surname prefix', 'my-book-showroom' ); ?></label>
							<input type="text"
							       id="mbs-name-prefix-to-key-<?php echo esc_attr( $term_id ); ?>"
							       name="mbs_name_prefix_to_key[<?php echo esc_attr( $term_id ); ?>]"
							       value="<?php echo esc_attr( $name_prefix_to_key ); ?>"
							       placeholder="<?php esc_attr_e( 'van der, de, von', 'my-book-showroom' ); ?>">
						</div>
						<div class="mbs-settings-field-cell">
							<label for="mbs-name-key-<?php echo esc_attr( $term_id ); ?>"><?php esc_html_e( 'Surname / Last Name (key name)', 'my-book-showroom' ); ?></label>
							<input type="text"
							       id="mbs-name-key-<?php echo esc_attr( $term_id ); ?>"
							       name="mbs_name_key[<?php echo esc_attr( $term_id ); ?>]"
							       value="<?php echo esc_attr( $name_key ); ?>"
							       placeholder="<?php esc_attr_e( 'Smith, van der Berg', 'my-book-showroom' ); ?>">
						</div>
						<div class="mbs-settings-field-cell">
							<label for="mbs-name-after-key-<?php echo esc_attr( $term_id ); ?>"><?php esc_html_e( 'Suffix', 'my-book-showroom' ); ?></label>
							<input type="text"
							       id="mbs-name-after-key-<?php echo esc_attr( $term_id ); ?>"
							       name="mbs_name_after_key[<?php echo esc_attr( $term_id ); ?>]"
							       value="<?php echo esc_attr( $name_after_key ); ?>"
							       placeholder="<?php esc_attr_e( 'Jr., III', 'my-book-showroom' ); ?>">
						</div>
						<div class="mbs-settings-field-cell">
							<label for="mbs-name-letters-<?php echo esc_attr( $term_id ); ?>"><?php esc_html_e( 'Letters after name', 'my-book-showroom' ); ?></label>
							<input type="text"
							       id="mbs-name-letters-<?php echo esc_attr( $term_id ); ?>"
							       name="mbs_name_letters[<?php echo esc_attr( $term_id ); ?>]"
							       value="<?php echo esc_attr( $name_letters ); ?>"
							       placeholder="<?php esc_attr_e( 'PhD, OBE, CBE', 'my-book-showroom' ); ?>">
						</div>
					</div>
					<div class="mbs-author-name-inverted-row">
						<label for="mbs-name-inverted-<?php echo esc_attr( $term_id ); ?>"><?php esc_html_e( 'Inverted name (sort / ONIX PersonNameInverted)', 'my-book-showroom' ); ?></label>
						<input type="text"
						       id="mbs-name-inverted-<?php echo esc_attr( $term_id ); ?>"
						       name="mbs_name_inverted[<?php echo esc_attr( $term_id ); ?>]"
						       value="<?php echo esc_attr( $name_inverted ); ?>"
						       placeholder="<?php esc_attr_e( 'Auto-computed from fields above when left blank', 'my-book-showroom' ); ?>">
						<p class="description"><?php esc_html_e( 'Leave blank to auto-compute from surname + first name fields.', 'my-book-showroom' ); ?></p>
					</div>
				</div>
			</details>

			<div class="mbs-settings-field-cell mbs-author-field-wide">
				<label for="mbs-author-bio-<?php echo esc_attr( $term_id ); ?>">
					<?php esc_html_e( 'Bio', 'my-book-showroom' ); ?>
				</label>
				<textarea id="mbs-author-bio-<?php echo esc_attr( $term_id ); ?>"
				          name="mbs_author_bio[<?php echo esc_attr( $term_id ); ?>]"
				          rows="3"
				          placeholder="<?php esc_attr_e( 'Short author biography…', 'my-book-showroom' ); ?>"><?php echo esc_textarea( $bio ); ?></textarea>
			</div>

			<div class="mbs-settings-field-cell mbs-author-field-wide">
				<label for="mbs-author-website-<?php echo esc_attr( $term_id ); ?>">
					<?php esc_html_e( 'Website URL', 'my-book-showroom' ); ?>
				</label>
				<input type="url"
				       id="mbs-author-website-<?php echo esc_attr( $term_id ); ?>"
				       name="mbs_author_website_url[<?php echo esc_attr( $term_id ); ?>]"
				       value="<?php echo esc_attr( $website ); ?>"
				       placeholder="https://authorsite.com">
			</div>

			<div class="mbs-settings-field-cell">
				<label for="mbs-author-birth-year-<?php echo esc_attr( $term_id ); ?>">
					<?php esc_html_e( 'Birth Year', 'my-book-showroom' ); ?>
				</label>
				<input type="number"
				       id="mbs-author-birth-year-<?php echo esc_attr( $term_id ); ?>"
				       name="mbs_author_birth_year[<?php echo esc_attr( $term_id ); ?>]"
				       value="<?php echo esc_attr( $birth_year ); ?>"
				       min="1000" max="9999" step="1"
				       class="small-text"
				       placeholder="<?php esc_attr_e( 'e.g. 1975', 'my-book-showroom' ); ?>">
				<p class="description"><?php esc_html_e( 'Used for Library of Congress authority control.', 'my-book-showroom' ); ?></p>
			</div>

			<section class="mbs-author-social-section" data-term-id="<?php echo esc_attr( $term_id ); ?>">
				<h4><?php esc_html_e( 'Social Media Platforms', 'my-book-showroom' ); ?></h4>

				<!-- Hidden JSON input synced by mbs-admin-social-links.js before submit -->
				<input type="hidden"
				       class="mbs-social-links-json"
				       name="mbs_author_social_links[<?php echo esc_attr( $term_id ); ?>]"
				       value="<?php echo esc_attr( wp_json_encode( $social_links ) ); ?>">

				<!-- Added platforms list (jQuery UI Sortable) -->
				<ul class="mbs-social-sortable" data-term-id="<?php echo esc_attr( $term_id ); ?>">
				<?php foreach ( $social_links as $entry ) :
					$_slug   = sanitize_key( $entry['platform'] ?? '' );
					$_sinfo  = MBS_Author_Social_Links::get_platform_info( $_slug );
					$_slabel = ( 'custom' === $_slug && ! empty( $entry['label'] ) )
						? sanitize_text_field( $entry['label'] )
						: $_sinfo['label'];
				?>
					<li class="mbs-social-row" data-platform="<?php echo esc_attr( $_slug ); ?>">
						<?php MBS_Sortable_UI::drag_handle( true ); ?>
						<?php MBS_Sortable_UI::reorder_buttons(
							__( 'Move up', 'my-book-showroom' ),
							__( 'Move down', 'my-book-showroom' )
						); ?>
						<span class="mbs-social-icon mbs-social-icon-<?php echo esc_attr( $_slug ); ?>"><?php echo esc_html( $_sinfo['abbr'] ); ?></span>
						<span class="mbs-social-row-label"><?php echo esc_html( $_slabel ); ?></span>
						<input type="url"
						       class="mbs-social-url-input"
						       value="<?php echo esc_attr( $entry['url'] ?? '' ); ?>"
						       placeholder="<?php echo esc_attr( $_sinfo['placeholder'] ); ?>"
						       aria-label="<?php echo esc_attr( $_slabel . ' URL' ); ?>">
						<?php if ( 'custom' === $_slug ) : ?>
						<input type="text"
						       class="mbs-social-custom-label-input"
						       value="<?php echo esc_attr( $_slabel ); ?>"
						       placeholder="<?php esc_attr_e( 'Platform name', 'my-book-showroom' ); ?>"
						       aria-label="<?php esc_attr_e( 'Custom platform name', 'my-book-showroom' ); ?>">
						<?php endif; ?>
						<button type="button"
						        class="mbs-social-remove-btn button-link"
						        data-platform="<?php echo esc_attr( $_slug ); ?>"
						        aria-label="<?php echo esc_attr( sprintf( __( 'Remove %s', 'my-book-showroom' ), $_slabel ) ); // phpcs:ignore WordPress.WP.I18n.MissingTranslatorsComment -- single placeholder, platform name is not translatable context ?>">&#10005;</button>
					</li>
				<?php endforeach; ?>
				</ul>

				<?php if ( empty( $social_links ) ) : ?>
				<p class="mbs-social-empty-state description">
					<?php esc_html_e( 'No platforms added yet. Use the picker below to add some.', 'my-book-showroom' ); ?>
				</p>
				<?php endif; ?>

				<!-- Platform picker (collapsible) -->
				<details class="mbs-social-picker-wrapper">
					<summary class="mbs-social-picker-toggle button button-secondary">
						<?php esc_html_e( '+ Add Social Media Platform', 'my-book-showroom' ); ?>
					</summary>
					<div class="mbs-social-picker">
						<input type="search"
						       class="mbs-social-picker-search"
						       placeholder="<?php esc_attr_e( 'Search platforms...', 'my-book-showroom' ); ?>"
						       aria-label="<?php esc_attr_e( 'Search social platforms', 'my-book-showroom' ); ?>">
						<?php foreach ( $platforms as $_gkey => $_group ) : ?>
						<div class="mbs-social-picker-group" data-group="<?php echo esc_attr( $_gkey ); ?>">
							<span class="mbs-social-picker-group-label"><?php echo esc_html( $_group['label'] ); ?></span>
							<div class="mbs-social-picker-buttons">
							<?php foreach ( $_group['items'] as $_pslug => $_pinfo ) :
								$_padded = false;
								foreach ( $social_links as $_ex ) {
									if ( ( $_ex['platform'] ?? '' ) === $_pslug ) { $_padded = true; break; }
								}
							?>
								<button type="button"
								        class="mbs-social-picker-btn button button-small<?php echo $_padded ? ' mbs-social-picker-btn--added' : ''; ?>"
								        data-platform="<?php echo esc_attr( $_pslug ); ?>"
								        data-label="<?php echo esc_attr( $_pinfo['label'] ); ?>"
								        data-placeholder="<?php echo esc_attr( $_pinfo['placeholder'] ); ?>"
								        data-abbr="<?php echo esc_attr( $_pinfo['abbr'] ); ?>"
								        aria-pressed="<?php echo $_padded ? 'true' : 'false'; ?>"
								        <?php echo $_padded ? 'disabled' : ''; ?>>
									<?php echo esc_html( $_pinfo['label'] ); ?>
								</button>
							<?php endforeach; ?>
							</div>
						</div>
						<?php endforeach; ?>
						<div class="mbs-social-picker-group mbs-social-picker-group--custom">
							<span class="mbs-social-picker-group-label"><?php esc_html_e( 'Other', 'my-book-showroom' ); ?></span>
							<div class="mbs-social-picker-buttons">
								<button type="button"
								        class="mbs-social-picker-btn mbs-social-picker-btn--custom button button-small"
								        data-platform="custom"
								        data-label="Custom"
								        data-placeholder="https://..."
								        data-abbr="?"
								        aria-pressed="false">
									<?php esc_html_e( 'Other / Custom', 'my-book-showroom' ); ?>
								</button>
							</div>
						</div>
					</div>
				</details>

			</section>

			<div class="mbs-settings-field-cell">
				<span class="mbs-label-tip-pair">
					<label>
						<input type="checkbox"
						       name="mbs_author_featured[<?php echo esc_attr( $term_id ); ?>]"
						       value="1"
						       <?php checked( $is_featured ); ?>>
						<?php esc_html_e( 'Featured author', 'my-book-showroom' ); ?>
					</label>
					<?php mbs_help_tip( __( 'Featured author appears at the top of the Author Directory ahead of non-featured authors. If more than one author is marked Featured, they appear together as a group at the top — sorted alphabetically among themselves — followed by all non-featured authors below.', 'my-book-showroom' ), __( 'Featured Author', 'my-book-showroom' ), 'mbs-help-tip--wide' ); ?>
				</span>
			</div>

			<?php
			$layout_options = MBS_Layout_Registry::get_layout_options();
			$show_all       = mbs_is_pro() || mbs_is_pub();
			$free_slugs     = MBS_Layout_Registry::get_free_layout_slugs();
			if ( mbs_is_registered() ) :
			?>
			<div class="mbs-settings-field-cell">
				<label for="mbs_term_layout_<?php echo esc_attr( $term_id ); ?>">
					<?php esc_html_e( 'Book Grid Layout', 'my-book-showroom' ); ?>
				</label>
				<select name="mbs_term_layout[<?php echo esc_attr( $term_id ); ?>]"
				        id="mbs_term_layout_<?php echo esc_attr( $term_id ); ?>">
					<option value=""><?php esc_html_e( '— Use global default —', 'my-book-showroom' ); ?></option>
					<?php foreach ( $layout_options as $slug => $meta ) : ?>
						<?php if ( ! $show_all && ! in_array( $slug, $free_slugs, true ) ) { continue; } ?>
						<option value="<?php echo esc_attr( $slug ); ?>"
						        <?php selected( $term_layout, $slug ); ?>>
							<?php echo esc_html( $meta['label'] ); ?>
						</option>
					<?php endforeach; ?>
				</select>
				<p class="description">
					<?php esc_html_e( 'Override the global default layout for this term\'s book grid. Leave blank to use the global default from Settings → Formatting.', 'my-book-showroom' ); ?>
				</p>
			</div>
			<?php endif; ?>

			<p class="mbs-settings-actions">
				<?php submit_button( __( 'Save', 'my-book-showroom' ), 'primary', 'submit', false ); ?>
			</p>

		</div>
	</details>
</form>
