<?php
/**
 * Public Blog Review page (no login).
 *
 * Defaults to a clean read-only PREVIEW of the post; an Edit button reveals the
 * editor. Reuses the transcript-viewer shell (sitestaffr-tv-*) for chrome.
 *
 * Variables set by SiteStaffr_Blog_Review::render_page():
 *
 * @var WP_Post $post, string $post_status, $business_name, $logo_url, $csrf,
 *      $permalink, $thumb, $meta_title, $meta_desc, $body_html, $form_action, $notice.
 *
 * @package SiteStaffr
 * @since   1.28.0
 */

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

$is_draft = ( 'draft' === $post_status || 'pending' === $post_status );

$sitestaffr_page_title = ! empty( $business_name )
	? $business_name . ' — Review your post'
	: __( 'Review your post', 'sitestaffr' );
?><!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<meta name="robots" content="noindex, nofollow">
	<title><?php echo esc_html( $sitestaffr_page_title ); ?></title>
	<?php wp_head(); ?>
</head>
<body>

	<div class="sitestaffr-tv-topbar">
		<div class="sitestaffr-tv-topbar-inner">
			<img src="<?php echo esc_url( $logo_url ); ?>" alt="SiteStaffr">
			<?php if ( $is_draft ) : ?>
				<button type="button" class="sitestaffr-br-menu-toggle" id="sitestaffr-br-menu-toggle" aria-expanded="false" aria-controls="sitestaffr-br-actionbar">
					<span class="sitestaffr-br-menu-icon" aria-hidden="true"></span>
					<?php esc_html_e( 'Actions', 'sitestaffr' ); ?>
				</button>
			<?php endif; ?>
		</div>
		<?php if ( $is_draft ) : ?>
			<!-- ============ CONTEXTUAL ACTION BAR ============
			     Desktop: a slim fixed sidebar in the right margin. Mobile/mid: a
			     dropdown folded into this sticky bar, opened by the Actions toggle,
			     so the page keeps a single clean sticky nav. The submit buttons sit
			     outside the review form, so they bind to it via form="". Only the
			     current mode's actions render. -->
			<div class="sitestaffr-br-actionbar" id="sitestaffr-br-actionbar" hidden>
				<div class="sitestaffr-br-actionbar-inner">
					<div class="sitestaffr-br-actiongroup" id="sitestaffr-br-actions-preview">
						<span class="sitestaffr-br-mode"><?php esc_html_e( 'Review', 'sitestaffr' ); ?></span>
						<button type="submit" form="sitestaffr-br-form" class="sitestaffr-br-btn sitestaffr-br-publish" data-action="publish"><?php esc_html_e( 'Publish', 'sitestaffr' ); ?></button>
						<button type="button" class="sitestaffr-br-btn sitestaffr-br-secondary" id="sitestaffr-br-edit-toggle"><?php esc_html_e( 'Edit', 'sitestaffr' ); ?></button>
						<button type="submit" form="sitestaffr-br-form" class="sitestaffr-br-btn sitestaffr-br-discard" data-action="discard"><?php esc_html_e( 'Discard', 'sitestaffr' ); ?></button>
					</div>
					<div class="sitestaffr-br-actiongroup" id="sitestaffr-br-actions-edit" hidden>
						<span class="sitestaffr-br-mode"><?php esc_html_e( 'Editing', 'sitestaffr' ); ?></span>
						<button type="submit" form="sitestaffr-br-form" class="sitestaffr-br-btn sitestaffr-br-save" data-action="save"><?php esc_html_e( 'Save', 'sitestaffr' ); ?></button>
						<button type="button" class="sitestaffr-br-btn sitestaffr-br-secondary" id="sitestaffr-br-cancel"><?php esc_html_e( 'Cancel', 'sitestaffr' ); ?></button>
					</div>
				</div>
			</div>
		<?php endif; ?>
	</div>

	<div class="sitestaffr-tv-container">

		<?php if ( ! empty( $business_name ) ) : ?>
			<div class="sitestaffr-tv-biz-header">
				<h1><?php echo esc_html( $business_name ); ?></h1>
			</div>
		<?php endif; ?>

		<?php if ( 'published' === $notice ) : ?>
			<div class="sitestaffr-br-notice sitestaffr-br-success">
				<?php esc_html_e( 'Published! Your post is now live.', 'sitestaffr' ); ?>
				<?php if ( $permalink ) : ?><a href="<?php echo esc_url( $permalink ); ?>" target="_blank" rel="noopener"><?php esc_html_e( 'View live post', 'sitestaffr' ); ?></a><?php endif; ?>
			</div>
		<?php elseif ( 'discarded' === $notice ) : ?>
			<div class="sitestaffr-br-notice"><?php esc_html_e( 'This post was discarded (moved to Trash).', 'sitestaffr' ); ?></div>
		<?php elseif ( 'saved' === $notice ) : ?>
			<div class="sitestaffr-br-notice sitestaffr-br-success"><?php esc_html_e( 'Changes saved.', 'sitestaffr' ); ?></div>
		<?php elseif ( 'csrf' === $notice ) : ?>
			<div class="sitestaffr-br-notice sitestaffr-br-error"><?php esc_html_e( 'Your session expired. We refreshed the page — please try again.', 'sitestaffr' ); ?></div>
		<?php elseif ( 'error' === $notice ) : ?>
			<div class="sitestaffr-br-notice sitestaffr-br-error"><?php esc_html_e( 'Something went wrong. Your changes were not saved — please try again.', 'sitestaffr' ); ?></div>
		<?php endif; ?>

		<?php if ( 'publish' === $post_status && 'published' !== $notice ) : ?>
			<div class="sitestaffr-br-notice"><?php esc_html_e( 'This post is already published.', 'sitestaffr' ); ?>
				<?php if ( $permalink ) : ?><a href="<?php echo esc_url( $permalink ); ?>" target="_blank" rel="noopener"><?php esc_html_e( 'View live post', 'sitestaffr' ); ?></a><?php endif; ?>
			</div>
		<?php elseif ( 'trash' === $post_status ) : ?>
			<div class="sitestaffr-br-notice"><?php esc_html_e( 'This post was discarded.', 'sitestaffr' ); ?></div>
		<?php elseif ( $is_draft ) : ?>
			<form method="post" action="<?php echo esc_url( $form_action ); ?>" enctype="multipart/form-data" class="sitestaffr-br-form" id="sitestaffr-br-form">
				<input type="hidden" name="csrf" value="<?php echo esc_attr( $csrf ); ?>" />
				<input type="hidden" name="review_action" id="sitestaffr-br-action" value="save" />

				<!-- ============ READ-ONLY PREVIEW (default) ============ -->
				<div id="sitestaffr-br-preview" class="sitestaffr-br-card">
					<?php if ( $thumb ) : ?>
						<img src="<?php echo esc_url( $thumb ); ?>" alt="" class="sitestaffr-br-preview-image" />
					<?php endif; ?>
					<h1 class="sitestaffr-br-preview-title"><?php echo esc_html( get_the_title( $post ) ); ?></h1>
					<div class="sitestaffr-br-preview-body sitestaffr-blog-content"><?php echo wp_kses_post( $body_html ); ?></div>

					<div class="sitestaffr-br-seo-summary">
						<p><span class="sitestaffr-br-seo-key"><?php esc_html_e( 'SEO title', 'sitestaffr' ); ?></span><?php echo $meta_title ? esc_html( $meta_title ) : '<em>' . esc_html__( 'not set', 'sitestaffr' ) . '</em>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></p>
						<p><span class="sitestaffr-br-seo-key"><?php esc_html_e( 'Meta description', 'sitestaffr' ); ?></span><?php echo $meta_desc ? esc_html( $meta_desc ) : '<em>' . esc_html__( 'not set', 'sitestaffr' ) . '</em>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></p>
					</div>
				</div>

				<!-- ============ EDIT MODE (hidden until Edit) ============ -->
				<div id="sitestaffr-br-edit" class="sitestaffr-br-card" hidden>
					<label class="sitestaffr-br-label" for="sitestaffr-br-title"><?php esc_html_e( 'Title', 'sitestaffr' ); ?></label>
					<input type="text" id="sitestaffr-br-title" name="post_title" class="sitestaffr-br-title" value="<?php echo esc_attr( get_the_title( $post ) ); ?>" />

					<label class="sitestaffr-br-label"><?php esc_html_e( 'Featured image', 'sitestaffr' ); ?></label>
					<img src="<?php echo $thumb ? esc_url( $thumb ) : ''; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>" alt="" class="sitestaffr-br-thumb" id="sitestaffr-br-thumb"<?php echo $thumb ? '' : ' hidden'; ?> />
					<input type="file" name="featured_image" id="sitestaffr-br-file" accept="image/jpeg,image/png,image/gif,image/webp" class="sitestaffr-br-file" />
					<p class="sitestaffr-br-hint"><?php esc_html_e( 'Upload a JPG, PNG, GIF, or WebP (max 8 MB) to replace the featured image.', 'sitestaffr' ); ?></p>

					<label class="sitestaffr-br-label" for="sitestaffr-br-body-textarea"><?php esc_html_e( 'Body', 'sitestaffr' ); ?></label>
					<textarea id="sitestaffr-br-body-textarea" name="body_html" class="sitestaffr-br-body sitestaffr-blog-content"><?php echo esc_textarea( $body_html ); ?></textarea>

					<label class="sitestaffr-br-label" for="sitestaffr-br-meta-title"><?php esc_html_e( 'SEO title', 'sitestaffr' ); ?></label>
					<input type="text" id="sitestaffr-br-meta-title" name="meta_title" class="sitestaffr-br-title sitestaffr-br-seo-input" value="<?php echo esc_attr( $meta_title ); ?>" />

					<label class="sitestaffr-br-label" for="sitestaffr-br-meta"><?php esc_html_e( 'Meta description', 'sitestaffr' ); ?></label>
					<textarea id="sitestaffr-br-meta" name="meta_description" class="sitestaffr-br-meta" rows="2"><?php echo esc_textarea( (string) $meta_desc ); ?></textarea>
				</div>
			</form>

			<script>
			( function () {
				var preview = document.getElementById( 'sitestaffr-br-preview' );
				var edit = document.getElementById( 'sitestaffr-br-edit' );
				var textarea = document.getElementById( 'sitestaffr-br-body-textarea' );
				var actionField = document.getElementById( 'sitestaffr-br-action' );
				var actionsPreview = document.getElementById( 'sitestaffr-br-actions-preview' );
				var actionsEdit = document.getElementById( 'sitestaffr-br-actions-edit' );
				var editToggle = document.getElementById( 'sitestaffr-br-edit-toggle' );
				var cancelBtn = document.getElementById( 'sitestaffr-br-cancel' );
				var actionbar = document.getElementById( 'sitestaffr-br-actionbar' );
				var menuToggle = document.getElementById( 'sitestaffr-br-menu-toggle' );
				var confirmDiscard = <?php echo wp_json_encode( __( 'Discard this post? It will be moved to Trash.', 'sitestaffr' ) ); ?>;
				var editorId = 'sitestaffr-br-body-textarea';
				var editorReady = false;

				// Initialize WordPress's bundled TinyMCE on first Edit. Done lazily (and
				// only after the edit panel is visible) so the editor mounts into a sized
				// container. If wp.editor is unavailable on this logged-out front-end page,
				// the plain <textarea> stays usable as a graceful fallback.
				function initEditor() {
					if ( editorReady ) { return; }
					editorReady = true;
					if ( window.wp && wp.editor && typeof wp.editor.initialize === 'function' ) {
						wp.editor.initialize( editorId, {
							tinymce: {
								toolbar1: 'formatselect,bold,italic,bullist,numlist,blockquote,link,unlink,undo,redo',
								block_formats: 'Paragraph=p;Heading 2=h2;Heading 3=h3',
								menubar: false,
								height: 480,
								// Keep the status bar so the editor gets a drag-to-resize grip in
								// its bottom-right corner (like the meta-description textarea).
								statusbar: true,
								resize: true,
								branding: false,
								content_style: 'body{font-family:-apple-system,BlinkMacSystemFont,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif;font-size:17px;line-height:1.75;color:#2c3338;} h2{color:#00838F;font-weight:700;} h3{color:#004D40;font-weight:700;} a{color:#1FB6CC;} blockquote{border-left:4px solid #1FB6CC;background:#E0F7FA;padding:8px 18px;color:#004D40;border-radius:0 8px 8px 0;}'
							},
							quicktags: { buttons: 'strong,em,link,ul,ol,li,blockquote,close' },
							mediaButtons: false
						} );
					}
				}

				function showEdit( on ) {
					edit.hidden = ! on;
					preview.hidden = on;
					actionsEdit.hidden = ! on;
					actionsPreview.hidden = on;
					if ( on ) { initEditor(); }
				}
				editToggle.addEventListener( 'click', function () { showEdit( true ); } );
				cancelBtn.addEventListener( 'click', function () { showEdit( false ); } );

				// Live preview of a newly chosen featured image, shown immediately in the
				// edit panel (before the upload happens on save).
				var fileInput = document.getElementById( 'sitestaffr-br-file' );
				var thumbImg = document.getElementById( 'sitestaffr-br-thumb' );
				if ( fileInput && thumbImg && window.FileReader ) {
					fileInput.addEventListener( 'change', function () {
						var file = fileInput.files && fileInput.files[0];
						if ( ! file ) { return; }
						var reader = new FileReader();
						reader.onload = function ( e ) {
							thumbImg.src = e.target.result;
							thumbImg.hidden = false;
						};
						reader.readAsDataURL( file );
					} );
				}

				// Mobile/mid: the action bar is a dropdown folded into the sticky logo
				// bar, toggled open by the "Actions" button. On desktop the bar is a
				// fixed sidebar (CSS keeps it visible and the toggle hidden).
				function setMenu( open ) {
					if ( ! actionbar ) { return; }
					actionbar.hidden = ! open;
					if ( menuToggle ) { menuToggle.setAttribute( 'aria-expanded', open ? 'true' : 'false' ); }
				}
				if ( menuToggle ) {
					menuToggle.addEventListener( 'click', function () { setMenu( actionbar.hidden ); } );
				}

				// The action buttons live outside the form (in the sticky bar) and bind
				// to it via the form="" attribute, so query them on the bar, not the form.
				actionbar.querySelectorAll( 'button[type=submit]' ).forEach( function ( btn ) {
					btn.addEventListener( 'click', function ( e ) {
						var act = btn.getAttribute( 'data-action' );
						if ( 'discard' === act && ! window.confirm( confirmDiscard ) ) {
							e.preventDefault();
							return;
						}
						actionField.value = act;
						if ( edit.hidden ) {
							// Submitted from the read-only preview: leave the body untouched
							// (a disabled field is not posted, so handle_write keeps the content).
							textarea.disabled = true;
						} else {
							// Flush TinyMCE's content back into the textarea before submit.
							if ( window.tinymce ) { window.tinymce.triggerSave(); }
							textarea.disabled = false;
						}
					} );
				} );
			} )();
			</script>
		<?php endif; ?>

		<p class="sitestaffr-br-footer"><?php esc_html_e( 'Powered by SiteStaffr Blog Agent', 'sitestaffr' ); ?></p>
	</div>
	<?php wp_footer(); ?>
</body>
</html>
