<?php

/**
 * Contentosapp Studio Standalone Settings — Sites Tab
 *
 * @package Contentosapp_Studio
 * @since   1.0.0
 */

defined('ABSPATH') || exit;
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals -- Included admin view; local presentation variables are scoped to this template.

$sites_repo = costudio_sites();
$sites      = $sites_repo ? $sites_repo->get_all() : array();
?>

<div class="fos-sites-list">
	<?php if (empty($sites)) : ?>
		<div class="fos-sites-empty">
			<p><?php esc_html_e('No sites configured yet.', 'contentosapp-studio'); ?></p>
			<button type="button" class="cts-btn cts-btn--sm fos-add-site-btn">+ <?php esc_html_e('Add your first site', 'contentosapp-studio'); ?></button>
		</div>
	<?php else : ?>
		<?php foreach ($sites as $key => $site) :
			$site_name = costudio_site_display_name( $site, $key );
			$status    = $site['last_connection_status'] ?? 'unknown';
			$recovery_status = $site['publication_recovery_status'] ?? 'unknown';
			$cats      = ! empty($site['categories']) && is_array($site['categories']) ? $site['categories'] : array();
			$site_colors = costudio_site_color_vars( $site );
			$is_operable = $sites_repo ? $sites_repo->is_site_operable( (string) $key ) : false;

			if ( ! $is_operable ) {
				$status_modifier = 'fos-int-status--warn';
				$status_text     = __('Inactive', 'contentosapp-studio');
			} elseif ('success' === $status) {
				$status_modifier = 'fos-int-status--ok';
				$status_text     = __('Connected', 'contentosapp-studio');
			} elseif ('error' === $status) {
				$status_modifier = 'fos-int-status--error';
				$status_text     = __('Connection error', 'contentosapp-studio');
			} else {
				$status_modifier = 'fos-int-status--warn';
				$status_text     = __('Not tested', 'contentosapp-studio');
			}
		?>
			<div class="fos-site-card" data-key="<?php echo esc_attr($key); ?>" style="<?php echo esc_attr( $site_colors['style'] ); ?>">
				<div class="fos-site-card__avatar" aria-hidden="true"><?php echo esc_html(mb_strtoupper(mb_substr($site_name, 0, 1))); ?></div>
				<div class="fos-site-card__info">
					<strong class="fos-site-card__name">
						<?php echo esc_html($site_name); ?>
						<?php if ( Costudio_WP_Publisher::LOCAL_SITE_KEY === $key || ! empty( $site['is_local'] ) ) : ?>
							<span style="font-size: 10px; font-weight: 600; color: var(--fos-primary); background: var(--fos-primary-light); padding: 2px 6px; border-radius: 4px; margin-left: 6px; vertical-align: middle; border: 1px solid rgba(108, 71, 255, 0.15);">🔌 Plug & Play</span>
						<?php endif; ?>
					</strong>
					<span class="fos-site-card__url"><?php echo esc_html($site['url']); ?></span>
					<?php if ( 'success' === $status ) : ?>
						<span class="fos-site-card__url">
							<?php
							echo esc_html(
								'ready' === $recovery_status
									? __( 'Duplicate recovery ready', 'contentosapp-studio' )
									: __( 'Duplicate recovery limited · retest with an Editor or Administrator Application Password', 'contentosapp-studio' )
							);
							?>
						</span>
					<?php endif; ?>
					<?php if (! empty($cats)) : ?>
						<div class="fos-site-card__cats">
							<?php foreach (array_slice($cats, 0, 5) as $cat) : ?>
								<span class="fos-site-card__cat-tag"><?php echo esc_html($cat); ?></span>
							<?php endforeach; ?>
							<?php if (count($cats) > 5) : ?>
								<span class="fos-site-card__cat-more">+<?php echo (int) ( count($cats) - 5 ); ?></span>
							<?php endif; ?>
						</div>
					<?php endif; ?>
				</div>
				<div class="fos-int-status <?php echo esc_attr($status_modifier); ?>">
					<span class="fos-int-status__dot"></span>
					<span class="fos-int-status__text"><?php echo esc_html($status_text); ?></span>
				</div>
				<div class="fos-site-card__actions">
					<?php if ( class_exists( 'Costudio_Brand_Voice' ) ) : 
						$bv_class  = 'fos-open-voice-btn';
						$bv_title  = __('Brand Voice', 'contentosapp-studio');
						?>
						<button type="button" class="fos-action-btn fos-action-btn--primary <?php echo esc_attr( $bv_class ); ?>" data-key="<?php echo esc_attr($key); ?>" data-name="<?php echo esc_attr($site_name); ?>" title="<?php echo esc_attr($bv_title); ?>">
							<span class="fos-action-btn__icon" aria-hidden="true">🎙️</span>
						</button>
					<?php endif; ?>

					<?php /* translators: %s: site name to be edited */ ?>
					<button type="button" class="fos-action-btn fos-action-btn--primary fos-edit-site-btn" data-key="<?php echo esc_attr($key); ?>" title="<?php esc_attr_e('Edit site', 'contentosapp-studio'); ?>" aria-label="<?php
					printf(
						/* translators: %s: destination site name. */
						esc_attr__( 'Edit site %s', 'contentosapp-studio' ),
						esc_attr( $site_name )
					);
					?>">
						<span class="fos-action-btn__icon" aria-hidden="true">✏️</span>
					</button>
					<?php /* translators: %s: site name to be deleted */ ?>
					<button type="button" class="fos-action-btn fos-action-btn--danger fos-delete-site-btn" data-key="<?php echo esc_attr($key); ?>" title="<?php esc_attr_e('Delete site', 'contentosapp-studio'); ?>" aria-label="<?php
					printf(
						/* translators: %s: destination site name. */
						esc_attr__( 'Delete site %s', 'contentosapp-studio' ),
						esc_attr( $site_name )
					);
					?>">
						<span class="fos-action-btn__icon" aria-hidden="true">🗑</span>
					</button>
				</div>
			</div>
		<?php endforeach; ?>

	<?php endif; ?>
</div><!-- /.fos-sites-list -->

<!-- Modal for Adding/Editing Site -->
<div id="fos-site-modal" class="fos-modal" style="display:none;" role="dialog" aria-modal="true" aria-labelledby="fos-modal-title">
	<div class="fos-modal__box fos-modal__box--site">

		<!-- Header -->
		<div class="fos-modal__header">
			<div class="fos-modal__title-group">
				<span class="fos-modal__title-icon" aria-hidden="true">🌐</span>
				<h2 id="fos-modal-title" class="fos-modal__title">
					<?php esc_html_e('Add New Site', 'contentosapp-studio'); ?>
				</h2>
			</div>
			<button type="button" id="fos-modal-close" class="fos-modal__close fos-modal__close--text" aria-label="<?php esc_attr_e('Close', 'contentosapp-studio'); ?>">✕</button>
		</div>

		<!-- Form -->
		<form id="fos-site-form">
			<input type="hidden" name="site_key" id="fos-site-old-key">

			<!-- Body -->
			<div class="fos-modal__body">
				
				<?php if (!isset($sites['__local__'])) : ?>
				<div class="fos-form-grid fos-form-grid--1col" style="margin-bottom: 1.5rem;" id="fos-site-local-toggle-wrap">
					<label style="display: flex; align-items: center; font-size: 13px; gap: 8px; cursor: pointer; background: rgba(108, 71, 255, 0.05); padding: 12px; border-radius: 6px; border: 1px solid rgba(108, 71, 255, 0.2); color: var(--fos-text); font-weight: 500;">
						<input type="checkbox" id="fos-site-is-local" name="is_local" value="1" style="width: 18px; height: 18px; accent-color: var(--fos-primary); cursor: pointer;">
						🔌 <?php esc_html_e('This is the current site (Plug & Play)', 'contentosapp-studio'); ?>
					</label>
				</div>
				<?php endif; ?>

				<!-- Row 1: Name + URL -->
				<div class="fos-form-grid fos-form-grid--2col">
					<div class="fos-form-field">
						<label for="fos-site-name"><?php esc_html_e('Site Name', 'contentosapp-studio'); ?> <span class="fos-field-required" aria-hidden="true">*</span></label>
						<input type="text" name="name" id="fos-site-name" class="cts-input" placeholder="<?php esc_attr_e('e.g. My Blog', 'contentosapp-studio'); ?>" required>
					</div>
					<div class="fos-form-field">
						<label for="fos-site-url"><?php esc_html_e('Site URL', 'contentosapp-studio'); ?> <span class="fos-field-required" aria-hidden="true">*</span></label>
						<input type="url" name="url" id="fos-site-url" class="cts-input" placeholder="https://mysite.com" required>
					</div>
				</div>

				<!-- Row 2: Username + Password -->
				<div class="fos-form-grid fos-form-grid--2col">
					<div class="fos-form-field">
						<label for="fos-site-user"><?php esc_html_e('WP Username', 'contentosapp-studio'); ?> <span class="fos-field-required" aria-hidden="true">*</span></label>
						<input type="text" name="user" id="fos-site-user" class="cts-input" placeholder="admin" autocomplete="off" required>
					</div>
					<div class="fos-form-field">
						<label for="fos-site-password"><?php esc_html_e('Application Password', 'contentosapp-studio'); ?> <span class="fos-field-required" aria-hidden="true">*</span></label>
						<input type="password" name="password" id="fos-site-password" class="cts-input" placeholder="xxxx xxxx xxxx xxxx" autocomplete="new-password">
						<p class="fos-form-field__hint">
							<?php esc_html_e('Generate in WordPress → Users → Profile → Application Passwords.', 'contentosapp-studio'); ?>
						</p>
					</div>
				</div>

				<!-- Row 2.5: Brand / Color -->
				<div class="fos-form-grid fos-form-grid--1col" style="margin-bottom:1.5rem;">
					<div class="fos-form-field">
						<label for="fos-site-color"><?php esc_html_e('Site Theme Color', 'contentosapp-studio'); ?></label>
						<div style="display:flex; align-items:center; gap:12px; background:#fafafa; border:1px solid #eaeaea; padding:8px 12px; border-radius:6px;">
							<input type="color" name="color" id="fos-site-color" value="#3b82f6" style="width:40px; height:40px; min-width:40px; min-height:40px; padding:2px; cursor:pointer; border-radius:4px; border:1px solid #ccc; flex-shrink:0; background:none;">
							<p class="fos-form-field__hint" style="margin:0; line-height:1.4;">
								<?php esc_html_e('Used by ContentOS Agents to colorize HTML highlight boxes and stylize generated images to match this site\'s branding (e.g., #3b82f6).', 'contentosapp-studio'); ?>
							</p>
						</div>
					</div>
				</div>

				<!-- Categories area -->
				<div class="fos-cat-area fos-sites-modal__row">
					<div class="fos-cat-area__header">
						<span class="fos-cat-area__label">🏷️ <?php esc_html_e('Available categories', 'contentosapp-studio'); ?></span>
						<button type="button" id="fos-modal-load-cats-btn" class="fos-cat-area__load-btn">
							🔄 <?php esc_html_e('Load from site', 'contentosapp-studio'); ?>
						</button>
					</div>
					<div class="fos-cat-area__body" id="fos-modal-cat-tags-wrap">
						<span class="fos-cat-area__empty"><?php esc_html_e('Click "Load from site" to fetch available categories.', 'contentosapp-studio'); ?></span>
					</div>
					<p class="fos-form-field__hint">
						🌐 <?php esc_html_e('Categories are public on WordPress — no credentials needed to load them. Authentication is only required to publish articles.', 'contentosapp-studio'); ?>
					</p>
				</div>

			</div><!-- /.fos-modal__body -->

			<!-- Footer -->
			<div class="fos-modal__footer">
				<div class="fos-modal__footer-left">
					<button type="button" id="fos-modal-test-btn" class="fos-btn-test-conn">
						🔌 <?php esc_html_e('Test Connection', 'contentosapp-studio'); ?>
					</button>
					<div id="fos-modal-conn-result" class="fos-modal__conn-result" style="display:none;" aria-live="polite"></div>
				</div>
				<div class="fos-modal__footer-right">
					<button type="button" id="fos-modal-cancel" class="cts-btn cts-btn--ghost"><?php esc_html_e('Cancel', 'contentosapp-studio'); ?></button>
					<button type="submit" id="fos-site-save-btn" class="cts-btn cts-btn--primary">💾 <?php esc_html_e('Save Site', 'contentosapp-studio'); ?></button>
				</div>
			</div><!-- /.fos-modal__footer -->

		</form>
	</div><!-- /.fos-modal__box -->
</div><!-- /#fos-site-modal -->
