<?php
/**
 * LabelPicker
 *
 * Stateful label rotation used by the RSS handler.
 * Shuffles the label pool once per post and cycles through it in order,
 * so the same label never repeats back-to-back within a single feed item.
 *
 * For stateless random picks (inline/end-content themes) use
 * LabelProvider::random_inline() / random_end_content() directly.
 *
 * @package Relatedly\Labels
 * @since   2.0.0
 */

namespace Relatedly\Labels;

defined( 'ABSPATH' ) || exit;

/**
 * Rotates labels without immediate repetition for one feed item.
 *
 * @since 2.0.0
 */
class LabelPicker {

	/**
	 * Shuffled label pool for the current post.
	 *
	 * @since 2.0.0
	 * @var string[]
	 */
	private array $pool = [];

	/**
	 * Current position in the pool.
	 *
	 * @since 2.0.0
	 * @var int
	 */
	private int $index = 0;

	/**
	 * Seed the picker with a fresh shuffled pool.
	 * Call once per RSS feed item (post).
	 *
	 * @param string[] $labels Full label array from LabelProvider.
	 */
	public function seed( array $labels ): void {
		$this->pool  = $labels;
		$this->index = 0;
		shuffle( $this->pool );
	}

	/**
	 * Get the next label, cycling back to the start when exhausted.
	 *
	 * @return string
	 */
	public function next(): string {
		if ( empty( $this->pool ) ) {
			return 'Related:';
		}
		$label = $this->pool[ $this->index % count( $this->pool ) ];
		++$this->index;
		return $label;
	}

	/**
	 * Reset the picker between posts.
	 *
	 * @return void
	 */
	public function reset(): void {
		$this->pool  = [];
		$this->index = 0;
	}
}
