<?php
/**
 * PS_Label_Stepper — native PHP renderer for the 3-stage label flow.
 *
 * 3-column layout with Stage 1 (consent), Stage 2 (sender), Stage 3 (size picker / Oracle QR).
 * Each stage: pending → active (orange/blue accents) → done (green + minimized).
 *
 * Button handlers call WordPress admin-ajax.php; sender form POSTs to Parcselect_Label_Embed::ajax_save_sender.
 *
 * @package ParcelSelector
 * @since   4.1.3
 */

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

class Parcselect_Label_Stepper {

	/**
	 * Render the 3-column stage layout. Drop-in replacement for VPS iframe.
	 *
	 * @param WC_Order $order
	 */
	public static function render_stages( $order ) {
		$order_id      = $order->get_id();
		$nonce         = wp_create_nonce( 'parcselect_label_consent' );
		$has_service   = 'yes' === $order->get_meta( '_ps_label_consent', true );
		$has_sender    = 'yes' === $order->get_meta( '_ps_label_sender_confirmed', true );
		// v4.1.9 REQUEST-22: admin może wyłączyć Stage 2 dla każdego klienta (po wstępnej konfiguracji w panelu admina).
		// Option `parcselect_label_skip_sender_stage` (yes/no, default no). Jeśli yes + dane nadawcy są w wp_options
		// (parcselect_label_sender_*) → auto-mark sender_confirmed=yes bez wyświetlania okienka.
		if ( ! $has_sender && 'yes' === (string) get_option( 'parcselect_label_skip_sender_stage', 'no' ) ) {
			$_snd_check_name = (string) get_option( 'parcselect_label_sender_name', '' );
			$_snd_check_st   = (string) get_option( 'parcselect_label_sender_street', '' );
			if ( '' !== $_snd_check_name && '' !== $_snd_check_st ) {
				$order->update_meta_data( '_ps_label_sender_confirmed', 'yes' );
				$order->save();
				$has_sender = true;
			}
		}
		$has_receiver  = 'yes' === $order->get_meta( '_ps_label_receiver_confirmed', true );
		$awaiting      = 'awaiting_payment' === (string) $order->get_meta( '_ps_label_status', true );
		$paid          = 'paid' === (string) $order->get_meta( '_ps_label_status', true );
		$payload_json  = (string) $order->get_meta( '_ps_label_pscp_payload', true );
		$s1_state      = $has_service ? 'done' : 'active';
		$s2_state      = $has_service ? ( $has_sender ? 'done' : 'active' ) : 'pending';
		$sR_state      = ( $has_service && $has_sender ) ? ( $has_receiver ? 'done' : 'active' ) : 'pending';
		$show_consent  = ! $has_service || ! $has_sender || ! $has_receiver;

		// Sender defaults from wp_options.
		$snd = array(
			'name'     => (string) get_option( 'parcselect_label_sender_name',     get_option( 'blogname', '' ) ),
			'company'  => (string) get_option( 'parcselect_label_sender_company',  '' ),
			'street'   => (string) get_option( 'parcselect_label_sender_street',   trim( (string) get_option( 'woocommerce_store_address', '' ) . ' ' . (string) get_option( 'woocommerce_store_address_2', '' ) ) ),
			'postcode' => (string) get_option( 'parcselect_label_sender_postcode', (string) get_option( 'woocommerce_store_postcode', '' ) ),
			'city'     => (string) get_option( 'parcselect_label_sender_city',     (string) get_option( 'woocommerce_store_city', '' ) ),
			'phone'    => (string) get_option( 'parcselect_label_sender_phone',    '' ),
			'email'    => (string) get_option( 'parcselect_label_sender_email',    (string) get_option( 'admin_email', '' ) ),
		);

		self::print_css();
		?>
		<div class="psle-layout3" id="psle-stages" data-order-id="<?php echo absint( $order_id ); ?>">

			<?php // ─── STAGE 1: Service consent ─── ?>
			<div class="psle-progress-col s1 <?php echo esc_attr( $s1_state ); ?>" id="psle-stage1" data-mini-label="<?php echo esc_attr__( 'Consent', 'parcel-selector' ); ?>">
				<div class="psle-stage-head">
					<div class="psle-stage-num"><?php echo 'done' === $s1_state ? '&#10003;' : '1'; ?></div>
					<div class="psle-stage-title">
						<h3><?php esc_html_e( 'Data processing consent', 'parcel-selector' ); ?></h3>
						<div class="psle-stage-sub"><?php echo 'done' === $s1_state ? esc_html__( 'Accepted', 'parcel-selector' ) : esc_html__( 'Step 1 of 2', 'parcel-selector' ); ?></div>
					</div>
				</div>
				<div class="psle-stage-content">
					<div class="psle-stage-body">
						<p><strong><?php esc_html_e( 'Note! &#128578;', 'parcel-selector' ); ?></strong> <?php esc_html_e( 'To use the label tool, all you need to do is grant consent for data processing.', 'parcel-selector' ); ?></p>
						<p><?php esc_html_e( 'By clicking "I accept", you agree to transfer the necessary information to the ParcelSelector.com service — solely to prepare a shipping label for you.', 'parcel-selector' ); ?></p>
					</div>
					<div class="psle-bonus-box">
						<h4><?php esc_html_e( 'And now the good news! &#127881;', 'parcel-selector' ); ?></h4>
						<ul>
							<li><strong><?php esc_html_e( 'No registration', 'parcel-selector' ); ?></strong></li>
							<li><strong><?php esc_html_e( 'No hidden fees', 'parcel-selector' ); ?></strong></li>
							<li><strong><?php esc_html_e( 'No subscription', 'parcel-selector' ); ?></strong></li>
							<li><strong><?php esc_html_e( 'No KYC', 'parcel-selector' ); ?></strong></li>
							<li><?php esc_html_e( 'You pay only for the specific shipment', 'parcel-selector' ); ?></li>
						</ul>
					</div>
					<div class="psle-privacy-link">
						<?php esc_html_e( 'Data processing policy:', 'parcel-selector' ); ?>
						<a href="https://parcelselector.com/parcelselector-konstytucja/" target="_blank" rel="noopener noreferrer">parcelselector.com/parcelselector-konstytucja</a>
					</div>
					<?php // v4.2 SPEC/11 — kanoniczny regulamin v1.0 + 3-punkt label + 2 linki ?>
					<?php if ( class_exists( 'Parcselect_Label_Terms' ) ) : ?>
					<details class="psle-terms-box" style="margin:12px 0;border:1px solid #d1d5db;border-radius:8px;background:#f9fafb">
						<summary style="cursor:pointer;padding:10px 12px;font-weight:600;color:#1f2937"><?php /* translators: %s = terms version number */ printf( esc_html__( '📜 Mini Terms of the Label Tool v%s (click to expand)', 'parcel-selector' ), esc_html( Parcselect_Label_Terms::version() ) ); ?></summary>
						<div class="psle-terms-text" style="max-height:240px;overflow-y:auto;padding:12px;font-size:13px;line-height:1.5;white-space:pre-wrap;color:#374151;background:white;border-top:1px solid #d1d5db" id="psle-terms-scrollbox"><?php echo esc_html( Parcselect_Label_Terms::canonical_text() ); ?></div>
					</details>
					<?php endif; ?>
					<label class="psle-checkbox">
						<input type="checkbox" id="psle-cb-service">
						<span>
							<strong><?php esc_html_e( 'I accept:', 'parcel-selector' ); ?></strong>
							<ul style="margin:6px 0 0 20px;padding:0;list-style:disc;font-size:13px;line-height:1.5">
								<li><?php esc_html_e( 'the label tool terms', 'parcel-selector' ); ?></li>
								<li><?php esc_html_e( 'the transfer of my data to ParcelSelector.com', 'parcel-selector' ); ?></li>
								<li><?php esc_html_e( 'the non-refundable nature of the label fee', 'parcel-selector' ); ?></li>
							</ul>
						</span>
					</label>
					<div style="margin:8px 0;font-size:12px;color:#6b7280">
						<?php esc_html_e( 'Full terms:', 'parcel-selector' ); ?>
						<a href="https://parcelselector.com/en/parcelselector-konstytucja" target="_blank" rel="noopener noreferrer">ParcelSelector</a> ·
						<a href="https://inpost.pl/regulaminy" target="_blank" rel="noopener noreferrer">InPost</a>
					</div>
					<button type="button" id="psle-btn-service" class="psle-btn psle-btn-primary"><?php esc_html_e( 'I accept and continue &rarr;', 'parcel-selector' ); ?></button>
				</div>
				<div class="psle-stage-done-msg">
					<div class="psle-done-icon">&#10003;</div>
					<div class="psle-done-text"><?php esc_html_e( 'Processing accepted', 'parcel-selector' ); ?></div>
					<div class="psle-done-sub"><?php esc_html_e( 'Step completed', 'parcel-selector' ); ?></div>
				</div>
			</div>

			<?php // ─── STAGE 2: Sender data ─── ?>
			<div class="psle-progress-col s2 <?php echo esc_attr( $s2_state ); ?>" id="psle-stage2" data-mini-label="<?php echo esc_attr__( 'Sender', 'parcel-selector' ); ?>">
				<div class="psle-stage-head">
					<div class="psle-stage-num"><?php echo 'done' === $s2_state ? '&#10003;' : '2'; ?></div>
					<div class="psle-stage-title">
						<h3><?php esc_html_e( 'Sender data', 'parcel-selector' ); ?></h3>
						<div class="psle-stage-sub"><?php
							echo 'done' === $s2_state ? esc_html__( 'Saved', 'parcel-selector' ) : ( 'active' === $s2_state ? esc_html__( 'Step 2 of 2', 'parcel-selector' ) : esc_html__( 'Waiting for step 1', 'parcel-selector' ) );
						?></div>
					</div>
				</div>
				<div class="psle-stage-content">
					<div class="psle-stage-body">
						<p><?php esc_html_e( 'To send a parcel, we need the sender data. It will be saved as the default for all future shipments.', 'parcel-selector' ); ?></p>
						<p style="font-size:12px;color:#475569;background:#fef3c7;border-left:4px solid #f59e0b;padding:8px 12px;border-radius:6px;margin-top:8px;line-height:1.5">
							<strong><?php esc_html_e( 'ℹ Info:', 'parcel-selector' ); ?></strong> <?php echo wp_kses( __( 'The sender data will be saved <strong>natively as the default</strong> in the plugin admin panel (<em>Settings → ParcelSelector → Label tool → Sender</em>).', 'parcel-selector' ), array( 'strong' => array(), 'em' => array() ) ); ?>
							<?php echo wp_kses( __( 'In the <strong>Admin Panel</strong> you can change whether this step is shown for every new customer (after the initial sender configuration).', 'parcel-selector' ), array( 'strong' => array() ) ); ?>
						</p>
					</div>
					<div class="psle-warning">
						<strong><?php esc_html_e( 'Important note:', 'parcel-selector' ); ?></strong> <?php esc_html_e( 'if you provide false data and the customer does not collect the parcel — a refund may be impossible. For that reason we do not take responsibility for such situations.', 'parcel-selector' ); ?>
					</div>
					<form id="psle-sender-form" onsubmit="return false;">
						<div class="psle-sender-grid">
							<div class="full"><label><?php esc_html_e( 'Sender first and last name', 'parcel-selector' ); ?><span class="psle-req">*</span></label>
								<input type="text" id="psf-name" value="<?php echo esc_attr( $snd['name'] ); ?>"
								       required
								       pattern="^[\p{L}\s\-]+\s+[\p{L}\s\-]+$"
								       placeholder="<?php echo esc_attr__( 'e.g. Jan Kowalski (no digits or special characters)', 'parcel-selector' ); ?>"
								       title="<?php echo esc_attr__( 'Required: at least 2 words (first + last name), letters only, no digits', 'parcel-selector' ); ?>">
								<div id="psf-name-error" style="display:none;color:#dc2626;font-size:11px;margin-top:4px;font-weight:600">
									⚠️ <?php esc_html_e( 'The field must contain a FIRST and LAST NAME (at least 2 words, letters only — no digits or special characters)', 'parcel-selector' ); ?>
								</div>
							</div>
							<div class="full"><label><?php esc_html_e( 'Company (optional)', 'parcel-selector' ); ?></label>
								<input type="text" id="psf-company" value="<?php echo esc_attr( $snd['company'] ); ?>"></div>
							<div class="full"><label><?php esc_html_e( 'Street and number', 'parcel-selector' ); ?><span class="psle-req">*</span></label>
								<input type="text" id="psf-street" value="<?php echo esc_attr( $snd['street'] ); ?>" placeholder="<?php echo esc_attr__( 'e.g. Example St. 15/3', 'parcel-selector' ); ?>" required>
								<div id="psf-street-error" style="display:none;color:#dc2626;font-size:11px;margin-top:4px;font-weight:600"></div>
							</div>
							<div><label><?php esc_html_e( 'Postal code', 'parcel-selector' ); ?><span class="psle-req">*</span></label>
								<input type="text" id="psf-postcode" value="<?php echo esc_attr( $snd['postcode'] ); ?>" placeholder="00-000" pattern="\d{2}-\d{3}" required>
								<div id="psf-postcode-error" style="display:none;color:#dc2626;font-size:11px;margin-top:4px;font-weight:600"></div>
							</div>
							<div><label><?php esc_html_e( 'City', 'parcel-selector' ); ?><span class="psle-req">*</span></label>
								<input type="text" id="psf-city" value="<?php echo esc_attr( $snd['city'] ); ?>" placeholder="<?php echo esc_attr__( 'Warsaw (letters only)', 'parcel-selector' ); ?>" required>
								<div id="psf-city-error" style="display:none;color:#dc2626;font-size:11px;margin-top:4px;font-weight:600"></div>
							</div>
							<div><label><?php esc_html_e( 'Phone', 'parcel-selector' ); ?><span class="psle-req">*</span></label>
								<?php $_ps_phone_disp = function_exists( 'parcselect_phone_strip_pl_prefix' ) ? parcselect_phone_strip_pl_prefix( $snd['phone'] ) : $snd['phone']; ?>
								<div style="display:flex;align-items:stretch;border:1px solid #cbd5e1;border-radius:7px;overflow:hidden;background:#fff;">
									<span style="background:#f1f5f9;padding:0 12px;display:flex;align-items:center;font-weight:700;color:#475569;font-size:13px;border-right:1px solid #cbd5e1;flex-shrink:0;letter-spacing:0.3px;" aria-hidden="true">+48</span>
									<input type="tel" id="psf-phone" value="<?php echo esc_attr( $_ps_phone_disp ); ?>" placeholder="500 100 200" required maxlength="11" inputmode="numeric" autocomplete="tel-national" aria-label="<?php echo esc_attr__( 'Phone number (9 digits)', 'parcel-selector' ); ?>" style="border:0;outline:0;padding:9px 11px;flex:1;font-size:13px;background:transparent;min-width:0;">
								</div>
								<div id="psf-phone-error" style="display:none;color:#dc2626;font-size:11px;margin-top:4px;font-weight:600"></div>
							</div>
							<div><label>Email</label>
								<input type="email" id="psf-email" value="<?php echo esc_attr( $snd['email'] ); ?>" placeholder="kontakt@example.com">
								<div id="psf-email-error" style="display:none;color:#dc2626;font-size:11px;margin-top:4px;font-weight:600"></div>
							</div>
							<!-- NS-59 2026-04-30: Paczkomat nadawczy — OSOBNE POLE.
							     Opcjonalne. Gdy wybrane → tańsza etykieta (~50%). -->
							<div class="full" style="border-top:1px dashed #cbd5e1;padding-top:10px;margin-top:4px;">
								<label style="color:#0e7490;font-weight:700;">📦 <?php esc_html_e( 'Sending parcel locker', 'parcel-selector' ); ?> <span style="color:#94a3b8;font-weight:400;"><?php esc_html_e( '(optional — label ~50% cheaper)', 'parcel-selector' ); ?></span></label>
								<input type="text" id="psf-locker-id"
								       value="<?php echo esc_attr( (string) ( get_option( 'parcselect_sender_locker_id', '' ) ?: get_option( 'parcselect_label_sender_locker_id', '' ) ) ); ?>"
								       pattern="[A-Za-z]{3}[0-9]{2}[A-Za-z]?" maxlength="6"
								       placeholder="<?php echo esc_attr__( 'e.g. WAW01M, LUK01M (leave empty = courier picks up the parcel at the address)', 'parcel-selector' ); ?>"
								       style="text-transform:uppercase;font-family:monospace;background:#ecfeff;border-color:#67e8f9;">
								<div id="psf-locker-id-error" style="display:none;color:#dc2626;font-size:11px;margin-top:4px;font-weight:600"></div>
								<div id="psf-locker-id-status" style="display:none;font-size:11px;margin-top:4px;font-weight:600"></div>
								<div style="font-size:11px;color:#0e7490;margin-top:4px;line-height:1.5;">
									💡 <a href="https://map.parcelselector.com/" target="_blank" rel="noopener" style="color:#0e7490;text-decoration:underline;"><?php esc_html_e( 'Find a parcel locker at map.parcelselector.com →', 'parcel-selector' ); ?></a>
								</div>
							</div>
						</div>
						<label class="psle-checkbox">
							<input type="checkbox" id="psle-cb-sender">
							<span><?php esc_html_e( 'I confirm that the data is correct.', 'parcel-selector' ); ?></span>
						</label>
						<label class="psle-checkbox" style="margin-top:6px;">
							<input type="checkbox" id="psle-cb-save-default" checked>
							<span>📌 <strong><?php esc_html_e( 'Save the sender data as the default', 'parcel-selector' ); ?></strong> <?php esc_html_e( '(auto-fill for the next labels in the admin panel).', 'parcel-selector' ); ?></span>
						</label>
						<button type="button" id="psle-btn-sender" class="psle-btn psle-btn-primary"><?php esc_html_e( 'Save data and generate label &rarr;', 'parcel-selector' ); ?></button>
						<div class="psle-error" id="psle-sender-error"></div>
					</form>
				</div>
				<div class="psle-stage-done-msg">
					<div class="psle-done-icon">&#10003;</div>
					<div class="psle-done-text"><?php esc_html_e( 'Sender data saved', 'parcel-selector' ); ?></div>
					<div class="psle-done-sub"><?php echo wp_kses( __( 'Saved natively as the default in the admin panel<br />Edit in: <em>Settings → ParcelSelector → Label tool → Sender</em>', 'parcel-selector' ), array( 'br' => array(), 'em' => array() ) ); ?></div>
					<div class="psle-sender-summary">
						<div class="psle-sender-summary-title"><?php esc_html_e( 'Saved sender', 'parcel-selector' ); ?></div>
						<?php foreach ( array(
							__( 'Name', 'parcel-selector' )    => $snd['name'],
							__( 'Company', 'parcel-selector' ) => $snd['company'],
							__( 'Street', 'parcel-selector' )  => $snd['street'],
							__( 'City', 'parcel-selector' )    => trim( $snd['postcode'] . ' ' . $snd['city'] ),
							__( 'Phone', 'parcel-selector' )   => $snd['phone'],
							'Email'                            => $snd['email'],
						) as $lbl => $val ) :
							if ( '' === trim( (string) $val ) ) continue; ?>
						<div class="psle-sender-summary-row"><span class="psle-sender-summary-label"><?php echo esc_html( $lbl ); ?></span><span class="psle-sender-summary-value"><?php echo esc_html( $val ); ?></span></div>
						<?php endforeach; ?>
					</div>
				</div>
				<div class="psle-stage-pending-msg">
					<div class="psle-lock">&#128274;</div>
					<div class="psle-pending-text"><?php esc_html_e( 'First accept the consent on the left', 'parcel-selector' ); ?></div>
					<div class="psle-pending-sub"><?php esc_html_e( 'The form will unlock after acceptance', 'parcel-selector' ); ?></div>
				</div>
			</div>

			<?php // ─── STAGE R: Dane odbiorcy (auto-pulled from order shipping) ─── ?>
			<?php
			$_R_locker_id   = (string) $order->get_meta( '_ps_locker_id', true ) ?: (string) $order->get_meta( '_ps_locker_name', true );
			$_R_locker_city = (string) $order->get_meta( '_ps_locker_city', true );
			$_R_locker_addr = (string) $order->get_meta( '_ps_locker_address1', true ) ?: (string) $order->get_meta( '_ps_locker_address', true );
			$_R_recv_first  = $order->get_shipping_first_name() ?: $order->get_billing_first_name();
			$_R_recv_last   = $order->get_shipping_last_name()  ?: $order->get_billing_last_name();
			$_R_recv_phone  = method_exists( $order, 'get_shipping_phone' ) ? $order->get_shipping_phone() : '';
			if ( empty( $_R_recv_phone ) ) $_R_recv_phone = $order->get_billing_phone();
			$_R_recv_email  = $order->get_billing_email();
			$_R_recv_name   = trim( $_R_recv_first . ' ' . $_R_recv_last );
			$_R_carrier     = strtolower( (string) $order->get_meta( '_ps_locker_carrier', true ) ?: 'inpost' );
			// NS-58 2026-04-30: rozdziel paczkomat ID od opisu lokalu — wcześniej
			// "LUK01M (Lidl ul. Warszawska 20 A)" jako jeden ciąg było mylące i mieszało
			// identyfikator z opisową lokalizacją.
			$_R_data = array( __( 'Pickup point', 'parcel-selector' ) => $_R_locker_id );
			if ( '' !== $_R_locker_city ) {
				$_R_data[ __( 'Locker description', 'parcel-selector' ) ] = $_R_locker_city;
			}
			$_R_data[ __( 'Address', 'parcel-selector' ) ]  = $_R_locker_addr;
			$_R_data[ __( 'Recipient', 'parcel-selector' ) ] = $_R_recv_name;
			$_R_data[ __( 'Phone', 'parcel-selector' ) ]     = $_R_recv_phone;
			$_R_data['Email']                                = $_R_recv_email;
			$_R_data[ __( 'Carrier', 'parcel-selector' ) ]   = strtoupper( $_R_carrier );
			?>
			<div class="psle-progress-col sR <?php echo esc_attr( $sR_state ); ?>" id="psle-stageR" data-mini-label="<?php echo esc_attr__( 'Recipient', 'parcel-selector' ); ?>">
				<div class="psle-stage-head">
					<div class="psle-stage-num"><?php echo 'done' === $sR_state ? '&#10003;' : '3'; ?></div>
					<div class="psle-stage-title">
						<h3><?php esc_html_e( 'Recipient data', 'parcel-selector' ); ?></h3>
						<div class="psle-stage-sub"><?php
							echo 'done' === $sR_state ? esc_html__( 'Accepted', 'parcel-selector' ) : ( 'active' === $sR_state ? esc_html__( 'Step 3 of 4', 'parcel-selector' ) : esc_html__( 'Waiting for step 2', 'parcel-selector' ) );
						?></div>
					</div>
				</div>
				<div class="psle-stage-content">
					<div class="psle-stage-body">
						<p><?php esc_html_e( 'The recipient data is auto-pulled from the order. Review and accept — the label will be generated with this data.', 'parcel-selector' ); ?></p>
					</div>
					<div class="psle-sender-summary" style="background:rgba(255,255,255,.6);border-radius:8px;padding:10px 12px;margin:10px 0">
						<?php foreach ( $_R_data as $lbl => $val ) : if ( '' === trim( (string) $val ) ) continue; ?>
						<div class="psle-sender-summary-row"><span class="psle-sender-summary-label"><?php echo esc_html( $lbl ); ?></span><span class="psle-sender-summary-value"><?php echo esc_html( $val ); ?></span></div>
						<?php endforeach; ?>
					</div>
					<label class="psle-checkbox">
						<input type="checkbox" id="psle-cb-receiver">
						<span><?php esc_html_e( 'I confirm that the recipient data is correct — the label will be generated exactly with this data.', 'parcel-selector' ); ?></span>
					</label>
					<button type="button" id="psle-btn-receiver" class="psle-btn psle-btn-primary"><?php esc_html_e( 'I accept the recipient data &rarr;', 'parcel-selector' ); ?></button>
				</div>
				<div class="psle-stage-done-msg">
					<div class="psle-done-icon">&#10003;</div>
					<div class="psle-done-text"><?php esc_html_e( 'Recipient data accepted', 'parcel-selector' ); ?></div>
					<div class="psle-sender-summary">
						<?php foreach ( $_R_data as $lbl => $val ) : if ( '' === trim( (string) $val ) ) continue; ?>
						<div class="psle-sender-summary-row"><span class="psle-sender-summary-label"><?php echo esc_html( $lbl ); ?></span><span class="psle-sender-summary-value"><?php echo esc_html( $val ); ?></span></div>
						<?php endforeach; ?>
					</div>
				</div>
				<div class="psle-stage-pending-msg">
					<div class="psle-lock">&#128274;</div>
					<div class="psle-pending-text"><?php esc_html_e( 'First confirm the sender data', 'parcel-selector' ); ?></div>
					<div class="psle-pending-sub"><?php esc_html_e( 'The recipient acceptance unlocks after the sender is saved', 'parcel-selector' ); ?></div>
				</div>
			</div>

			<?php // ─── STAGE 4 (size picker — sam zmienia kolor na zielony po wyborze) + STAGE 5 (Oracle QR osobno) ─── ?>
			<?php if ( ! $show_consent ) : ?>
				<?php // Stage 4: ten sam kontener — render_native_size_picker sam wykrywa payload i renderuje state done ?>
				<?php /* BUG-R 2026-05-15: panel Gabaryt zwija sie auto (psle-minimized) po wyborze rozmiaru — jak Zgoda/Nadawca/Odbiorca. Klik rozwija (toggle w stepper.js). */ ?>
				<div class="psle-stage3-col<?php echo ( $awaiting || $paid ) && '' !== $payload_json ? ' done psle-minimized' : ''; ?>" id="psle-stage4" data-mini-label="<?php echo esc_attr__( 'Size', 'parcel-selector' ); ?>">
					<?php if ( ( $awaiting || $paid ) && '' !== $payload_json ) : ?>
						<div class="psle-stage-head"><div class="psle-stage-num" style="background:#10b981;color:#fff;border-color:#10b981">&#10003;</div></div>
					<?php endif; ?>
					<?php if ( class_exists( 'Parcselect_Label_Embed' ) ) { Parcselect_Label_Embed::render_native_size_picker( $order ); } ?>
				</div>
				<?php // Stage 5: Oracle QR osobno OBOK (tylko gdy payload obecny) ?>
				<?php if ( ( $awaiting || $paid ) && '' !== $payload_json ) : ?>
				<div class="psle-stage3-col done" id="psle-stage5" data-mini-label="<?php echo esc_attr__( 'Payment', 'parcel-selector' ); ?>">
					<?php if ( class_exists( 'Parcselect_Label_Embed' ) ) { Parcselect_Label_Embed::render_from_pscp_payload( $order, $payload_json, $paid ); } ?>
				</div>
				<?php endif; ?>
			<?php endif; ?>

		</div>

		<?php self::print_js( $order_id, $nonce ); ?>
		<?php
	}

	/**
	 * Print inline CSS (1:1 port from embed-label.ejs lines 278-442).
	 */
	private static function print_css() {
		if ( ! wp_style_is( 'parcselect-label-stepper', 'registered' ) ) {
			wp_register_style(
				'parcselect-label-stepper',
				PARCSELECT_PLUGIN_URL . 'assets/css/parcselect-label-stepper.css',
				array(),
				PARCSELECT_VERSION
			);
		}
		wp_enqueue_style( 'parcselect-label-stepper' );
	}

	/**
	 * Inline JS event handlers — click + AJAX to plugin endpoints.
	 * Transitions stage.active→done visually, reloads page to re-render next stage.
	 */
	private static function print_js( $order_id, $nonce ) {
		// Inline JS extracted to assets/js/parcselect-label-stepper.js for WP.org compliance.
		// NONCE + ORDER_ID injected via wp_add_inline_script (before the main script body).
		if ( ! wp_script_is( 'parcselect-label-stepper', 'registered' ) ) {
			wp_register_script(
				'parcselect-label-stepper',
				PARCSELECT_PLUGIN_URL . 'assets/js/parcselect-label-stepper.js',
				array(),
				PARCSELECT_VERSION,
				true
			);
		}
		wp_enqueue_script( 'parcselect-label-stepper' );
		wp_add_inline_script(
			'parcselect-label-stepper',
			'var NONCE = ' . wp_json_encode( $nonce ) . '; var ORDER_ID = ' . (int) $order_id . ';',
			'before'
		);
		self::print_confetti_js();
	}

	/**
	 * Global PSLE_Confetti.fire() — port from parcel-locker-selector.js:1719-1789.
	 * Callable from any script; fires 3-wave confetti burst from element center.
	 * NS-54 2026-04-30: visibility public so class-ps-label-embed.php Stage 4 can preload it.
	 */
	public static function print_confetti_js() {
		static $done = false;
		if ( $done ) { return; }
		$done = true;
		// Inline JS extracted to assets/js/parcselect-label-confetti.js for WP.org compliance.
		if ( ! wp_script_is( 'parcselect-label-confetti', 'registered' ) ) {
			wp_register_script(
				'parcselect-label-confetti',
				PARCSELECT_PLUGIN_URL . 'assets/js/parcselect-label-confetti.js',
				array(),
				PARCSELECT_VERSION,
				true
			);
		}
		wp_enqueue_script( 'parcselect-label-confetti' );
	}

	/**
	 * Render all 5 stages minimized (after completed) with stage 5 (el-col-pdf) expanded.
	 * All previous stages render as 42px vertical strips with data-mini-label, click-to-expand.
	 *
	 * @param WC_Order $order
	 */
	public static function render_stages_minimized( $order ) {
		$order_id = $order->get_id();
		self::print_css();

		// Collect all accepted data for display in done columns
		$c_date = (string) $order->get_meta( '_ps_label_consent_date', true );
		$c_uid  = (int)    $order->get_meta( '_ps_label_consent_user', true );
		$c_user = $c_uid && get_userdata( $c_uid ) ? get_userdata( $c_uid )->user_login : '';

		$snd = array(
			__( 'Name', 'parcel-selector' )    => (string) get_option( 'parcselect_label_sender_name', '' ),
			__( 'Company', 'parcel-selector' ) => (string) get_option( 'parcselect_label_sender_company', '' ),
			__( 'Street', 'parcel-selector' )  => (string) get_option( 'parcselect_label_sender_street', '' ),
			__( 'City', 'parcel-selector' )    => trim( (string) get_option( 'parcselect_label_sender_postcode', '' ) . ' ' . (string) get_option( 'parcselect_label_sender_city', '' ) ),
			__( 'Phone', 'parcel-selector' )   => (string) get_option( 'parcselect_label_sender_phone', '' ),
			'Email'                            => (string) get_option( 'parcselect_label_sender_email', '' ),
		);

		$size3   = (string) $order->get_meta( '_ps_label_size', true );
		$weight3 = (string) $order->get_meta( '_ps_label_weight', true );
		$price3  = (string) $order->get_meta( '_ps_label_price_pln', true );
		$dims3   = array( 'A' => '8x38x64 cm', 'B' => '19x38x64 cm', 'C' => '41x38x64 cm' );

		$txid4    = (string) $order->get_meta( '_ps_label_txid', true );
		$amt4     = (string) $order->get_meta( '_ps_label_sol_amount', true );
		$paid_at  = (string) $order->get_meta( '_ps_label_paid_at', true );
		$pln4     = (string) $order->get_meta( '_ps_label_price_pln', true );
		$rate4    = (string) $order->get_meta( '_ps_label_sol_rate', true );
		$wallet4  = (string) $order->get_meta( '_ps_label_sol_wallet', true );
		$session4 = (string) $order->get_meta( '_ps_label_session_id', true );
		$tracking4= (string) $order->get_meta( '_ps_label_tracking_number', true );
		$locker4  = (string) $order->get_meta( '_ps_locker_name', true );
		$locker_addr4 = (string) ( $order->get_meta( '_ps_locker_address1', true ) ?: $order->get_meta( '_ps_locker_address', true ) );
		$txid_short = $txid4 ? ( substr( $txid4, 0, 8 ) . '...' . substr( $txid4, -6 ) ) : '';
		$wallet_short = $wallet4 ? ( substr( $wallet4, 0, 6 ) . '...' . substr( $wallet4, -4 ) ) : '';
		?>
		<div class="psle-layout3" id="psle-stages-minimized" data-order-id="<?php echo absint( $order_id ); ?>">

			<?php // Stage 1 done — consent date + user ?>
			<div class="psle-progress-col s1 done" data-mini-label="<?php echo esc_attr__( 'Consent', 'parcel-selector' ); ?>" onclick="this.classList.toggle('psle-expanded')" style="cursor:pointer">
				<div class="psle-stage-head">
					<div class="psle-stage-num">&#10003;</div>
					<div class="psle-stage-title"><h3><?php esc_html_e( 'Data processing consent', 'parcel-selector' ); ?></h3><div class="psle-stage-sub"><?php esc_html_e( 'Accepted', 'parcel-selector' ); ?></div></div>
				</div>
				<div class="psle-stage-done-msg">
					<div class="psle-done-icon">&#10003;</div>
					<div class="psle-done-text"><?php esc_html_e( 'Data processing accepted', 'parcel-selector' ); ?></div>
					<?php if ( $c_date ) : ?><div class="psle-done-sub"><?php esc_html_e( 'Date:', 'parcel-selector' ); ?> <?php echo esc_html( $c_date ); ?></div><?php endif; ?>
					<?php if ( $c_user ) : ?><div class="psle-done-sub"><?php esc_html_e( 'By:', 'parcel-selector' ); ?> <?php echo esc_html( $c_user ); ?></div><?php endif; ?>
				</div>
			</div>

			<?php // Stage 2 done — full sender summary ?>
			<div class="psle-progress-col s2 done" data-mini-label="<?php echo esc_attr__( 'Sender', 'parcel-selector' ); ?>" onclick="this.classList.toggle('psle-expanded')" style="cursor:pointer">
				<div class="psle-stage-head">
					<div class="psle-stage-num">&#10003;</div>
					<div class="psle-stage-title"><h3><?php esc_html_e( 'Sender data', 'parcel-selector' ); ?></h3><div class="psle-stage-sub"><?php esc_html_e( 'Saved', 'parcel-selector' ); ?></div></div>
				</div>
				<div class="psle-stage-done-msg">
					<div class="psle-done-icon">&#10003;</div>
					<div class="psle-done-text"><?php esc_html_e( 'Sender data saved', 'parcel-selector' ); ?></div>
					<div class="psle-sender-summary">
						<div class="psle-sender-summary-title"><?php esc_html_e( 'Saved sender', 'parcel-selector' ); ?></div>
						<?php foreach ( $snd as $lbl => $val ) : if ( '' === trim( $val ) ) continue; ?>
						<div class="psle-sender-summary-row"><span class="psle-sender-summary-label"><?php echo esc_html( $lbl ); ?></span><span class="psle-sender-summary-value"><?php echo esc_html( $val ); ?></span></div>
						<?php endforeach; ?>
					</div>
				</div>
			</div>

			<?php // Stage 3 done — size+weight+price ?>
			<div class="psle-stage3-col done" data-mini-label="<?php echo esc_attr__( 'Size', 'parcel-selector' ); ?>" onclick="this.classList.toggle('psle-expanded')" style="cursor:pointer;background:linear-gradient(135deg,#ecfdf5 0%,#d1fae5 100%);border:2px solid #10b981;border-radius:14px;padding:14px;max-width:360px">
				<div class="psle-stage-head">
					<div class="psle-stage-num" style="background:#10b981;color:#fff;border-color:#10b981">&#10003;</div>
					<div class="psle-stage-title"><h3><?php esc_html_e( 'Parcel size', 'parcel-selector' ); ?></h3><div class="psle-stage-sub"><?php esc_html_e( 'Size', 'parcel-selector' ); ?> <?php echo esc_html( $size3 ); ?></div></div>
				</div>
				<div class="psle-sender-summary">
					<?php if ( $size3 ) : ?><div class="psle-sender-summary-row"><span class="psle-sender-summary-label"><?php esc_html_e( 'Size', 'parcel-selector' ); ?></span><span class="psle-sender-summary-value"><?php echo esc_html( $size3 ); ?><?php echo isset( $dims3[ $size3 ] ) ? ' - ' . esc_html( $dims3[ $size3 ] ) : ''; ?></span></div><?php endif; ?>
					<?php if ( $weight3 ) : ?><div class="psle-sender-summary-row"><span class="psle-sender-summary-label"><?php esc_html_e( 'Weight', 'parcel-selector' ); ?></span><span class="psle-sender-summary-value"><?php echo esc_html( $weight3 ); ?> kg</span></div><?php endif; ?>
					<?php if ( $price3 ) : ?><div class="psle-sender-summary-row"><span class="psle-sender-summary-label"><?php esc_html_e( 'Price', 'parcel-selector' ); ?></span><span class="psle-sender-summary-value"><?php echo esc_html( $price3 ); ?> PLN</span></div><?php endif; ?>
				</div>
			</div>

			<?php // Stage 4 done — full payment details (NS-51 fix 2026-04-30: pelen kontekst + spojny styl z Stage 1-3) ?>
			<div class="psle-progress-col s4 done" data-mini-label="<?php echo esc_attr__( 'Paid', 'parcel-selector' ); ?>" onclick="this.classList.toggle('psle-expanded')" style="cursor:pointer;background:linear-gradient(135deg,#ecfdf5 0%,#d1fae5 100%);border:2px solid #10b981;border-radius:14px;padding:14px;max-width:360px">
				<div class="psle-stage-head">
					<div class="psle-stage-num" style="background:#10b981;color:#fff;border-color:#10b981">&#10003;</div>
					<div class="psle-stage-title"><h3><?php esc_html_e( 'SOLANA payment', 'parcel-selector' ); ?></h3><div class="psle-stage-sub"><?php esc_html_e( 'Paid on-chain', 'parcel-selector' ); ?></div></div>
				</div>
				<div class="psle-stage-done-msg">
					<div class="psle-done-icon">&#10003;</div>
					<div class="psle-done-text"><?php esc_html_e( 'Payment confirmed', 'parcel-selector' ); ?></div>
					<div class="psle-sender-summary">
						<div class="psle-sender-summary-title"><?php esc_html_e( 'Transaction details', 'parcel-selector' ); ?></div>
						<?php if ( $pln4 ) : ?><div class="psle-sender-summary-row"><span class="psle-sender-summary-label"><?php esc_html_e( 'Value', 'parcel-selector' ); ?></span><span class="psle-sender-summary-value" style="font-weight:700;color:#065f46"><?php echo esc_html( $pln4 ); ?> PLN</span></div><?php endif; ?>
						<?php if ( $amt4 ) : ?><div class="psle-sender-summary-row"><span class="psle-sender-summary-label"><?php esc_html_e( 'SOL amount', 'parcel-selector' ); ?></span><span class="psle-sender-summary-value" style="font-family:monospace"><?php echo esc_html( $amt4 ); ?> SOL</span></div><?php endif; ?>
						<?php if ( $rate4 ) : ?><div class="psle-sender-summary-row"><span class="psle-sender-summary-label"><?php esc_html_e( 'Rate', 'parcel-selector' ); ?></span><span class="psle-sender-summary-value">1 SOL = <?php echo esc_html( $rate4 ); ?> PLN</span></div><?php endif; ?>
						<?php if ( $wallet4 ) : ?><div class="psle-sender-summary-row" onclick="event.stopPropagation()"><span class="psle-sender-summary-label"><?php esc_html_e( 'Wallet', 'parcel-selector' ); ?></span><span class="psle-sender-summary-value"><a href="<?php echo esc_url( 'https://solscan.io/account/' . rawurlencode( $wallet4 ) ); ?>" target="_blank" rel="noopener" style="color:#047857;font-family:monospace;text-decoration:underline;font-size:11px"><?php echo esc_html( $wallet_short ); ?> &#8599;</a></span></div><?php endif; ?>
						<?php if ( $txid4 ) : ?><div class="psle-sender-summary-row" onclick="event.stopPropagation()"><span class="psle-sender-summary-label">TXID</span><span class="psle-sender-summary-value"><a href="<?php echo esc_url( 'https://solscan.io/tx/' . rawurlencode( $txid4 ) ); ?>" target="_blank" rel="noopener" style="color:#047857;font-family:monospace;text-decoration:underline;font-size:11px"><?php echo esc_html( $txid_short ); ?> &#8599;</a></span></div><?php endif; ?>
						<?php if ( $session4 ) : ?><div class="psle-sender-summary-row"><span class="psle-sender-summary-label"><?php esc_html_e( 'Invoice', 'parcel-selector' ); ?></span><span class="psle-sender-summary-value" style="font-family:monospace;font-size:11px">#<?php echo esc_html( $session4 ); ?></span></div><?php endif; ?>
						<?php if ( $locker4 ) : ?><div class="psle-sender-summary-row"><span class="psle-sender-summary-label"><?php esc_html_e( 'Parcel locker', 'parcel-selector' ); ?></span><span class="psle-sender-summary-value" style="font-family:monospace"><?php echo esc_html( $locker4 ); ?></span></div><?php endif; ?>
						<?php if ( $locker_addr4 ) : ?><div class="psle-sender-summary-row"><span class="psle-sender-summary-label"><?php esc_html_e( 'Address', 'parcel-selector' ); ?></span><span class="psle-sender-summary-value" style="font-size:11px"><?php echo esc_html( $locker_addr4 ); ?></span></div><?php endif; ?>
						<?php if ( $tracking4 ) : ?><div class="psle-sender-summary-row" onclick="event.stopPropagation()"><span class="psle-sender-summary-label">Tracking</span><span class="psle-sender-summary-value"><a href="<?php echo esc_url( 'https://inpost.pl/sledzenie-przesylek?number=' . rawurlencode( $tracking4 ) ); ?>" target="_blank" rel="noopener" style="color:#047857;font-family:monospace;text-decoration:underline;font-size:11px"><?php echo esc_html( $tracking4 ); ?> &#8599;</a></span></div><?php endif; ?>
						<?php if ( $paid_at ) : ?><div class="psle-sender-summary-row"><span class="psle-sender-summary-label"><?php esc_html_e( 'Time', 'parcel-selector' ); ?></span><span class="psle-sender-summary-value" style="font-size:11px"><?php echo esc_html( $paid_at ); ?></span></div><?php endif; ?>
					</div>
				</div>
			</div>

			<?php // Stage 5 — THE prominent column: PDF embed + buttons ?>
			<div class="el-col-pdf" data-mini-label="<?php echo esc_attr__( 'Label', 'parcel-selector' ); ?>">
				<?php Parcselect_Label_Metabox::render_completed( $order ); ?>
			</div>

		</div>
		<?php
		self::print_confetti_js();
	}
}
