<?php
/**
 * File Path: templates/admin/dashboard.php
 *
 * Admin Dashboard — Page Shell (GC3, UX rev 2)
 *
 * Structure:
 *   1. Full-width action bar (5 quick-action tiles)
 *   2. Three-column data grid:
 *      Left   (280px) — hub: stats + recently edited + tier + what's new
 *      Center (1fr)   — status: catalog health + system status
 *      Right  (280px) — news feed + brand monitor
 *
 * @package MyBookShowroom
 * @since   1.1.0
 */

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

// Archive URL for "View Showroom" tile.
$archive_url = get_post_type_archive_link( MBS_POST_TYPE ) ?: home_url( '/' );
?>
<?php
$mbs_persona       = sanitize_key( get_option( 'mbs_setting_dashboard_persona', 'solo' ) );
$mbs_persona_class = 'mbs-persona-' . $mbs_persona;
?>
<div class="wrap mbs-dashboard <?php echo esc_attr( $mbs_persona_class ); ?>">

	<div style="display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:0.5rem;margin-bottom:0;">
	<h1 class="screen-reader-text"><?php esc_html_e( 'My Book Showroom', 'my-book-showroom' ); ?></h1>
	<!-- DASH-2A: Widget preferences gear icon -->
	<button type="button" id="mbs-widget-prefs-toggle" class="button"
	        aria-label="<?php esc_attr_e( 'Dashboard widget settings', 'my-book-showroom' ); ?>"
	        title="<?php esc_attr_e( 'Widget Settings', 'my-book-showroom' ); ?>">
		&#x2699; <?php esc_html_e( 'Widget Settings', 'my-book-showroom' ); ?>
	</button>
</div>

<!-- DASH-2A: Widget settings panel -->
<?php
$_mbs_widget_labels  = MBS_Dashboard_Widget_Prefs::get_widget_labels();
$_mbs_hidden_widgets = MBS_Dashboard_Widget_Prefs::get_hidden_widgets( get_current_user_id() );
?>
<div id="mbs-widget-settings-panel" class="mbs-widget-settings-panel" hidden
     style="background:#fff;border:1px solid #c3c4c7;border-radius:4px;padding:1rem 1.25rem;margin:0.75rem 0;">
	<h3 style="margin-top:0;"><?php esc_html_e( 'Visible Widgets', 'my-book-showroom' ); ?></h3>
	<p class="description"><?php esc_html_e( 'Uncheck to hide a widget from your dashboard. Changes apply to your account only.', 'my-book-showroom' ); ?></p>
	<div style="display:flex;flex-wrap:wrap;gap:0.75rem 2rem;margin:0.75rem 0;">
	<?php foreach ( $_mbs_widget_labels as $slug => $label ) : ?>
		<label style="display:flex;align-items:center;gap:0.4rem;cursor:pointer;">
			<input type="checkbox"
			       class="mbs-widget-pref-cb"
			       data-slug="<?php echo esc_attr( $slug ); ?>"
			       <?php checked( ! in_array( $slug, $_mbs_hidden_widgets, true ) ); ?>>
			<?php echo esc_html( $label ); ?>
		</label>
	<?php endforeach; ?>
	</div>
	<div style="margin-top:0.75rem;display:flex;gap:0.5rem;align-items:center;">
		<button type="button" id="mbs-widget-prefs-save" class="button button-primary">
			<?php esc_html_e( 'Save Preferences', 'my-book-showroom' ); ?>
		</button>
		<button type="button" id="mbs-widget-prefs-reset" class="button">
			<?php esc_html_e( 'Reset to Defaults', 'my-book-showroom' ); ?>
		</button>
		<span id="mbs-widget-prefs-msg" style="display:none;color:green;font-weight:600;">
			<?php esc_html_e( 'Saved.', 'my-book-showroom' ); ?>
		</span>
	</div>
	<script>
	(function(){
		var nonce = '<?php echo esc_js( wp_create_nonce( 'mbs_widget_prefs' ) ); ?>';
		var ajaxurl = '<?php echo esc_js( admin_url( 'admin-ajax.php' ) ); ?>';

		document.getElementById('mbs-widget-prefs-toggle').addEventListener('click', function(){
			var panel = document.getElementById('mbs-widget-settings-panel');
			panel.hidden = ! panel.hidden;
		});

		document.getElementById('mbs-widget-prefs-save').addEventListener('click', function(){
			var hidden = [];
			document.querySelectorAll('.mbs-widget-pref-cb').forEach(function(cb){
				if ( ! cb.checked ) { hidden.push(cb.dataset.slug); }
			});
			var data = new FormData();
			data.append('action', 'mbs_save_widget_prefs');
			data.append('nonce',  nonce);
			hidden.forEach(function(s){ data.append('hidden_widgets[]', s); });
			fetch(ajaxurl, { method: 'POST', body: data, credentials: 'same-origin' })
				.then(function(r){ return r.json(); })
				.then(function(resp){
					if ( resp.success ) {
						var msg = document.getElementById('mbs-widget-prefs-msg');
						msg.style.display = 'inline';
						setTimeout(function(){ msg.style.display = 'none'; location.reload(); }, 800);
					}
				});
		});

		document.getElementById('mbs-widget-prefs-reset').addEventListener('click', function(){
			var data = new FormData();
			data.append('action', 'mbs_save_widget_prefs');
			data.append('nonce',  nonce);
			// No hidden_widgets[] = save empty array = all visible
			fetch(ajaxurl, { method: 'POST', body: data, credentials: 'same-origin' })
				.then(function(r){ return r.json(); })
				.then(function(){ location.reload(); });
		});
	})();
	</script>
</div>

	<!-- ── Logo + Quick-Action Bar ──────────────────────────────────────────── -->
	<div class="mbs-header-zone">

		<div class="mbs-header-logo">
			<img
				src="<?php echo esc_url( MBS_ASSETS_URL . 'images/mbs-logo.png' ); ?>"
				alt="<?php esc_attr_e( 'My Book Showroom', 'my-book-showroom' ); ?>"
				class="mbs-dashboard-logo"
			>
		</div><!-- .mbs-header-logo -->

		<div class="mbs-action-bar">

		<a href="<?php echo esc_url( admin_url( 'post-new.php?post_type=' . MBS_POST_TYPE ) ); ?>"
		   class="mbs-quick-action">
			<?php echo mbs_icon( 'action-add-book', array( 'size' => '20px', 'aria_label' => '' ) ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
			<?php esc_html_e( 'Add Book', 'my-book-showroom' ); ?>
		</a>

		<a href="<?php echo esc_url( admin_url( 'admin.php?page=my-book-showroom-settings&tab=import-export' ) ); ?>"
		   class="mbs-quick-action">
			<?php echo mbs_icon( 'action-import', array( 'size' => '20px', 'aria_label' => '' ) ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
			<?php esc_html_e( 'Import', 'my-book-showroom' ); ?>
		</a>

		<a href="<?php echo esc_url( admin_url( 'admin.php?page=my-book-showroom-settings&tab=appearance' ) ); ?>"
		   class="mbs-quick-action">
			<?php echo mbs_icon( 'action-appearance', array( 'size' => '20px', 'aria_label' => '' ) ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
			<?php esc_html_e( 'Appearance', 'my-book-showroom' ); ?>
		</a>

		<a href="<?php echo esc_url( admin_url( 'admin.php?page=my-book-showroom-settings&tab=dashboard' ) ); ?>"
		   class="mbs-quick-action">
			<?php echo mbs_icon( 'action-settings', array( 'size' => '20px', 'aria_label' => '' ) ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
			<?php esc_html_e( 'Settings', 'my-book-showroom' ); ?>
		</a>

		<a href="<?php echo esc_url( $archive_url ); ?>"
		   class="mbs-quick-action" target="_blank" rel="noopener">
			<?php echo mbs_icon( 'action-preview', array( 'size' => '20px', 'aria_label' => '' ) ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
			<?php esc_html_e( 'Showroom', 'my-book-showroom' ); ?>
		</a>

		<a href="<?php echo esc_url( admin_url( 'admin.php?page=mbs-buy-link-analytics' ) ); ?>"
		   class="mbs-quick-action">
			<?php echo mbs_icon( 'action-analytics', array( 'size' => '20px', 'aria_label' => '' ) ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
			<?php esc_html_e( 'Buy Link Analytics', 'my-book-showroom' ); ?>
		<?php if ( ! mbs_is_pro() ) : ?><span class="mbs-pro-badge"><?php esc_html_e( 'PRO', 'my-book-showroom' ); ?></span><?php endif; ?>
		</a>

		<a href="<?php echo esc_url( admin_url( 'admin.php?page=mbs-activity-log' ) ); ?>"
		   class="mbs-quick-action">
			<?php echo mbs_icon( 'action-reading-lists', array( 'size' => '20px', 'aria_label' => '' ) ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
			<?php esc_html_e( 'Activity Log', 'my-book-showroom' ); ?>
		<?php if ( ! mbs_is_pub() ) : ?><span class="mbs-pro-badge" style="background:#fde8a0;color:#92400e;"><?php esc_html_e( 'PUB', 'my-book-showroom' ); ?></span><?php endif; ?>
		</a>

		<?php if ( class_exists( 'MBS_Tutorial_Admin_Page' ) ) : ?>
		<button type="button" id="mbs-tutorial-tile"
		        class="mbs-quick-action"
		        aria-expanded="false"
		        aria-controls="mbs-tutorial-panel"
		        style="font-family:inherit;cursor:pointer;">
			<?php echo mbs_icon( 'action-tutorial', array( 'size' => '20px', 'aria_label' => '' ) ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
			<?php esc_html_e( 'Tutorial Data', 'my-book-showroom' ); ?>
		</button>
		<?php endif; ?>

		</div><!-- .mbs-action-bar -->

	</div><!-- .mbs-header-zone -->

	<!-- ── Tutorial Data Panel (toggled by tile) ────────────────────────────── -->
	<?php if ( class_exists( 'MBS_Tutorial_Admin_Page' ) ) : ?>
	<div id="mbs-tutorial-panel" hidden
	     style="background:#fff;border:1px solid #c3c4c7;border-radius:4px;padding:1rem 1.25rem;margin:0 0 16px;">
		<?php MBS_Tutorial_Admin_Page::render_panel_content(); ?>
	</div>
	<script>
	(function(){
		var tile  = document.getElementById('mbs-tutorial-tile');
		var panel = document.getElementById('mbs-tutorial-panel');
		if ( ! tile || ! panel ) { return; }
		tile.addEventListener('click', function(){
			var open = panel.hidden;
			panel.hidden = ! open;
			tile.setAttribute('aria-expanded', open ? 'true' : 'false');
			tile.style.boxShadow = open
				? 'inset 0 2px 6px rgba(0,0,0,.15)'
				: '';
		});
	}());
	</script>
	<?php endif; ?>


	<!-- ── License Status Hero ─────────────────────────────────────────────── -->
	<?php
	$_mbs_tier        = mbs_get_license_tier_label();
	$_mbs_sites_used  = (int) get_option( 'mbs_license_sites_used', 0 );
	$_mbs_sites_allow = (int) get_option( 'mbs_license_sites_allowed', 0 );
	$_mbs_act_at      = (int) get_option( 'mbs_license_activated_at', 0 );
	if ( ! $_mbs_act_at ) {
		$_mbs_act_at = (int) get_option( 'mbs_license_last_ping', 0 );
	}
	$_mbs_act_disp    = '';
	if ( $_mbs_act_at ) {
		$_mbs_tz       = MBS_Timezone_Helper::resolve_current_timezone();
		$_mbs_act_disp = wp_date(
			get_option( 'date_format' ) . ' ' . get_option( 'time_format' ),
			$_mbs_act_at,
			new DateTimeZone( $_mbs_tz )
		);
	}
	$_mbs_is_registered = mbs_is_registered();
	$_mbs_is_keyless    = mbs_is_keyless();
	?>
	<div class="mbs-license-status-hero mbs-hero-<?php echo esc_attr( $_mbs_tier ); ?><?php echo ( $_mbs_is_registered && 'free' === $_mbs_tier ) ? ' mbs-hero-free-registered' : ''; ?>" style="margin-bottom:16px;">
		<span class="mbs-badge mbs-badge-<?php echo esc_attr( $_mbs_tier ); ?> mbs-badge-large">
			<?php if ( 'pub' === $_mbs_tier ) : ?>
				&#9733;&nbsp;<?php echo esc_html( strtoupper( $_mbs_tier ) ); ?>
			<?php else : ?>
				<?php echo esc_html( strtoupper( $_mbs_tier ) ); ?>
			<?php endif; ?>
		</span>
		<span class="mbs-license-status-label">
			<?php
			if ( 'pub' === $_mbs_tier ) {
				esc_html_e( 'Publisher Active — full features on up to 3 sites', 'my-book-showroom' );
			} elseif ( 'pro' === $_mbs_tier ) {
				esc_html_e( 'PRO Active — full features on 1 site', 'my-book-showroom' );
			} elseif ( $_mbs_is_registered ) {
				esc_html_e( 'FREE — registered. Upgrade to PRO to unlock all features.', 'my-book-showroom' );
			} elseif ( $_mbs_is_keyless ) {
				esc_html_e( 'FREE — register your free key to enable settings export.', 'my-book-showroom' );
			} else {
				esc_html_e( 'FREE — activate your key to enable settings export.', 'my-book-showroom' );
			}
			?>
		</span>
		<?php if ( $_mbs_act_disp ) : ?>
			<span class="mbs-license-since"><?php echo esc_html( sprintf(
				/* translators: %s: formatted local date and time of license activation */
				__( 'since %s', 'my-book-showroom' ),
				$_mbs_act_disp
			) ); ?></span>
		<?php endif; ?>
		<?php if ( 'pub' === $_mbs_tier && $_mbs_sites_allow > 0 ) : ?>
			<span class="mbs-license-sites-counter"><?php echo esc_html( sprintf(
				/* translators: %1$d: sites currently active, %2$d: maximum sites for this license */
				__( '%1$d of %2$d sites active', 'my-book-showroom' ),
				$_mbs_sites_used,
				$_mbs_sites_allow
			) ); ?></span>
		<?php endif; ?>
		<a href="<?php echo esc_url( admin_url( 'admin.php?page=my-book-showroom-settings&tab=license' ) ); ?>"
		   class="mbs-license-manage-link">
			<?php esc_html_e( 'Manage →', 'my-book-showroom' ); ?>
		</a>
	</div><!-- .mbs-license-status-hero -->

	<!-- ── Three-column Data Grid ──────────────────────────────────────────── -->
	<div class="mbs-dashboard-wrapper">
		<div class="mbs-dashboard-grid">

			<!-- Left: stats + recently edited + tier + what's new -->
			<div class="mbs-dashboard-col">
				<?php mbs_get_template_part( 'admin/dashboard-hub' ); ?>
			</div>

			<!-- Center: feature table (FREE/keyless) + catalog health + system status -->
			<div class="mbs-dashboard-col">
				<?php if ( mbs_is_keyless() || ( ! mbs_is_pro() && (bool) get_option( 'mbs_license_registered', false ) ) ) : ?>
					<?php mbs_get_template_part( 'admin/dashboard-register' ); ?>
				<?php endif; ?>
				<?php mbs_get_template_part( 'admin/dashboard-status' ); ?>
			</div>

			<!-- Right: news feed + brand monitor -->
			<div class="mbs-dashboard-col">
				<?php mbs_get_template_part( 'admin/dashboard-news' ); ?>
				<?php mbs_get_template_part( 'admin/dashboard-brand' ); ?>
			</div>

		</div><!-- .mbs-dashboard-grid -->
	</div><!-- .mbs-dashboard-wrapper -->

	<?php do_action( 'mbs_dashboard_after_grid' );  // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- mbs_/MBS_ prefix is correct; scanner not configured with plugin prefix ?>
</div><!-- .wrap.mbs-dashboard -->
