<?php

declare(strict_types=1);

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

use Signocore\Multilanguage\Application\Constants;
use Signocore\Multilanguage\Infrastructure\Database\StringRepository;
use Signocore\Multilanguage\Support\FlagHelper;

/**
 * @var array<int, object> $strings
 * @var array<int, object> $languages
 * @var array<int, string> $contexts
 * @var int $totalStrings
 * @var int $perPage
 * @var string $firstLangCode
 * @var array{all: int, translated: int, needs_update: int, needs_translation: int} $statusCounts
 */

$lastScan = get_transient('sml_last_full_scan');
$allContexts = StringRepository::getContexts();
$contextCounts = [];
foreach ($allContexts as $ctx) {
	$contextCounts[$ctx] = StringRepository::countStrings($ctx);
}

$totalPages = (int) ceil($totalStrings / $perPage);
?>

<div class="wrap">
	<h1 class="sml-page-title">
		<?php echo esc_html__('String Translation', 'signocore-multilanguage'); ?>
	</h1>

	<?php if (isset($_GET['message']) && sanitize_text_field(wp_unslash($_GET['message'])) === 'strings_saved') : // phpcs:ignore WordPress.Security.NonceVerification.Recommended ?>
		<div class="notice notice-success is-dismissible">
			<p><?php echo esc_html__('Translations saved successfully.', 'signocore-multilanguage'); ?></p>
		</div>
	<?php endif; ?>

	<!-- Scan Info Bar -->
	<div class="sml-scan-bar">
		<div class="sml-scan-bar-info">
			<span class="sml-scan-sources">
				<?php foreach ($contextCounts as $ctx => $count) : ?>
					<span class="sml-scan-source-pill"><?php echo esc_html($ctx); ?> <strong><?php echo (int) $count; ?></strong></span>
				<?php endforeach; ?>
				<?php if (empty($contextCounts)) : ?>
					<span style="color: var(--sml-gray-500);"><?php echo esc_html__('No strings found.', 'signocore-multilanguage'); ?></span>
				<?php endif; ?>
			</span>
		</div>
		<div class="sml-scan-bar-actions">
			<?php if ($lastScan) : ?>
				<span class="sml-scan-timestamp">
					<?php printf(
						esc_html__('Scanned %s ago', 'signocore-multilanguage'),
						human_time_diff((int) $lastScan)
					); ?>
				</span>
			<?php endif; ?>
		</div>
	</div>

	<?php if (empty($languages)) : ?>
		<div class="sml-string-empty">
			<span class="dashicons dashicons-translation"></span>
			<?php echo esc_html__('Add at least one non-default language to start translating strings.', 'signocore-multilanguage'); ?>
		</div>
	<?php else : ?>

		<div class="sml-string-toolbar-wrap">
			<div class="sml-string-toolbar">
				<div class="sml-string-toolbar-main">
					<div class="sml-lang-pills sml-string-lang-pills">
						<?php $first = true; ?>
						<?php foreach ($languages as $lang) : ?>
							<button type="button"
									class="sml-lang-pill sml-string-lang-pill<?php echo $first ? ' active' : ''; ?>"
									data-lang="<?php echo esc_attr($lang->code); ?>">
								<?php echo FlagHelper::getFlagImg($lang->code, 16, 12, $lang->name); ?>
								<?php echo esc_html($lang->name); ?>
							</button>
							<?php $first = false; ?>
						<?php endforeach; ?>
					</div>

					<div class="sml-filter-bar">
						<label class="screen-reader-text" for="sml-context-filter"><?php echo esc_html__('Filter by context', 'signocore-multilanguage'); ?></label>
						<select id="sml-context-filter">
							<option value=""><?php echo esc_html__('All Contexts', 'signocore-multilanguage'); ?></option>
							<?php foreach ($contexts as $ctx) : ?>
								<option value="<?php echo esc_attr($ctx); ?>"><?php echo esc_html($ctx); ?></option>
							<?php endforeach; ?>
						</select>

						<label class="screen-reader-text" for="sml-search-filter"><?php echo esc_html__('Search strings', 'signocore-multilanguage'); ?></label>
						<input type="search"
							   id="sml-search-filter"
							   autocomplete="off"
							   placeholder="<?php echo esc_attr__('Search strings...', 'signocore-multilanguage'); ?>">

						<button type="button" class="button" id="sml-clear-filters">
							<?php echo esc_html__('Clear filters', 'signocore-multilanguage'); ?>
						</button>
					</div>
				</div>

				<div class="sml-string-toolbar-actions">
					<button type="button" class="button button-primary" id="sml-save-all" disabled>
						<?php echo esc_html__('Save all changes', 'signocore-multilanguage'); ?>
					</button>

					<a href="<?php echo esc_url(wp_nonce_url(add_query_arg('sml_rescan', '1'), 'sml_rescan')); ?>"
					   class="button">
						<?php echo esc_html__('Scan for strings', 'signocore-multilanguage'); ?>
					</a>
				</div>
			</div>

			<div class="sml-string-progress" id="sml-string-progress">
				<div class="sml-string-status-chips" role="group" aria-label="<?php echo esc_attr__('Filter by status', 'signocore-multilanguage'); ?>">
					<button type="button" class="sml-status-chip active" data-status="all" aria-pressed="true">
						<span class="sml-status-chip-label"><?php echo esc_html__('All', 'signocore-multilanguage'); ?></span>
						<span class="sml-status-chip-count" id="sml-status-count-all"><?php echo (int) $statusCounts['all']; ?></span>
					</button>
					<button type="button" class="sml-status-chip" data-status="needs_translation" aria-pressed="false">
						<span class="sml-status-chip-label"><?php echo esc_html__('Needs Translation', 'signocore-multilanguage'); ?></span>
						<span class="sml-status-chip-count" id="sml-status-count-needs_translation"><?php echo (int) $statusCounts['needs_translation']; ?></span>
					</button>
					<button type="button" class="sml-status-chip" data-status="needs_update" aria-pressed="false">
						<span class="sml-status-chip-label"><?php echo esc_html__('Needs Update', 'signocore-multilanguage'); ?></span>
						<span class="sml-status-chip-count" id="sml-status-count-needs_update"><?php echo (int) $statusCounts['needs_update']; ?></span>
					</button>
					<button type="button" class="sml-status-chip" data-status="translated" aria-pressed="false">
						<span class="sml-status-chip-label"><?php echo esc_html__('Translated', 'signocore-multilanguage'); ?></span>
						<span class="sml-status-chip-count" id="sml-status-count-translated"><?php echo (int) $statusCounts['translated']; ?></span>
					</button>
				</div>

				<div class="sml-string-progress-meta">
					<span class="sml-unsaved-badge" id="sml-unsaved-count" aria-live="polite">
						<?php echo esc_html__('No unsaved changes', 'signocore-multilanguage'); ?>
					</span>
					<span class="sml-last-saved" id="sml-last-saved" aria-live="polite"></span>
				</div>
			</div>

			</div>

		<div class="sml-string-feedback" id="sml-string-feedback" aria-live="polite"></div>

		<!-- String Cards List (server-rendered for initial load) -->
		<div class="sml-string-list" id="sml-string-list">
			<?php if (empty($strings)) : ?>
				<div class="sml-string-empty">
					<span class="dashicons dashicons-translation"></span>
					<?php echo esc_html__('No strings registered yet. Strings will appear here when themes or plugins register them for translation.', 'signocore-multilanguage'); ?>
				</div>
			<?php else : ?>
				<?php foreach ($strings as $string) : ?>
					<?php
					$stringId = (int) $string->id;
					$translationValue = $string->translation_value ?? '';
					$translationStatus = $string->translation_status ?? 'needs_translation';
				if (trim($translationValue) === '') {
					$translationStatus = 'needs_translation';
				}
					$isTextarea = ($string->type ?? 'line') !== 'line';
					$inputId = 'sml-string-translation-' . $stringId;
					?>
					<div class="sml-string-card" data-string-id="<?php echo esc_attr((string) $stringId); ?>" data-status="<?php echo esc_attr($translationStatus); ?>">
						<div class="sml-string-card-header">
							<span class="sml-string-original"><?php echo esc_html($string->value); ?></span>
							<span class="sml-string-context"><?php echo esc_html($string->context); ?></span>
						</div>
						<label for="<?php echo esc_attr($inputId); ?>" class="screen-reader-text">
							<?php
							printf(
								esc_html__('Translation for %s', 'signocore-multilanguage'),
								esc_html((string) $string->name)
							);
							?>
						</label>
						<?php if ($isTextarea) : ?>
							<textarea id="<?php echo esc_attr($inputId); ?>"
									  class="sml-translation-input sml-string-translation"
									  data-string-id="<?php echo esc_attr((string) $stringId); ?>"
									  data-lang-code="<?php echo esc_attr($firstLangCode); ?>"
									  data-original-value="<?php echo esc_attr($translationValue); ?>"
									  rows="3"><?php echo esc_textarea($translationValue); ?></textarea>
						<?php else : ?>
							<input type="text"
								   id="<?php echo esc_attr($inputId); ?>"
								   class="sml-translation-input sml-string-translation"
								   data-string-id="<?php echo esc_attr((string) $stringId); ?>"
								   data-lang-code="<?php echo esc_attr($firstLangCode); ?>"
								   data-original-value="<?php echo esc_attr($translationValue); ?>"
								   value="<?php echo esc_attr($translationValue); ?>">
						<?php endif; ?>
						<span class="sml-string-save-state" aria-live="polite"></span>
					</div>
				<?php endforeach; ?>
			<?php endif; ?>
		</div>

		<!-- Pagination -->
		<div class="sml-pagination" id="sml-pagination">
			<?php
			if ($totalPages > 1) {
				for ($i = 1; $i <= $totalPages; $i++) {
					if ($i === 1) {
						echo '<span class="sml-page-number current" data-page="1">1</span>';
					} elseif ($i <= 5 || $i === $totalPages) {
						echo '<a href="#" class="sml-page-number" data-page="' . $i . '">' . $i . '</a>';
					} elseif ($i === 6) {
						echo '<span class="sml-page-dots">&hellip;</span>';
					}
				}

				printf(
					'<span class="sml-pagination-info">%s</span>',
					esc_html(sprintf(
						/* translators: %s: number of items */
						_n('%s item', '%s items', $totalStrings, 'signocore-multilanguage'),
						number_format_i18n($totalStrings)
					))
				);
			} else {
				printf(
					'<span class="sml-pagination-info">%s</span>',
					esc_html(sprintf(
						/* translators: %s: number of items */
						_n('%s item', '%s items', $totalStrings, 'signocore-multilanguage'),
						number_format_i18n($totalStrings)
					))
				);
			}
			?>
		</div>

	<?php endif; ?>
</div>
