<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class CCGAL_Gallery_Renderer {

	const SHORTCODE_PRIMARY = 'ccgal_gallery';

	private static $enqueued_galleries = array();

	public static function init() {
		add_shortcode( self::SHORTCODE_PRIMARY, array( __CLASS__, 'render' ) );
		add_action( 'wp_enqueue_scripts', array( __CLASS__, 'register_assets' ) );
	}

	public static function register_assets() {
		wp_register_style(
			'ccgal-gallery',
			CCGAL_URL . 'assets/css/gallery.css',
			array(),
			CCGAL_VERSION
		);
		wp_register_script(
			'ccgal-zip-writer',
			CCGAL_URL . 'assets/js/zip-writer.js',
			array(),
			CCGAL_VERSION,
			true
		);
		wp_register_script(
			'ccgal-bulk-download',
			CCGAL_URL . 'assets/js/bulk-download.js',
			array( 'ccgal-zip-writer' ),
			CCGAL_VERSION,
			true
		);
		wp_register_script(
			'ccgal-gallery',
			CCGAL_URL . 'assets/js/gallery.js',
			array( 'ccgal-bulk-download' ),
			CCGAL_VERSION,
			true
		);
		wp_set_script_translations( 'ccgal-gallery', 'customer-cloud-gallery', CCGAL_DIR . 'languages' );
	}

	public static function render( $atts ) {
		$atts = shortcode_atts(
			array(
				'id'       => 0,
				'per_page' => 0,
				'load'     => '',
				'size'     => '',
			),
			$atts,
			self::SHORTCODE_PRIMARY
		);

		$gallery = CCGAL_CPT::get_gallery_config( (int) $atts['id'] );
		if ( ! $gallery ) {
			if ( current_user_can( 'edit_posts' ) ) {
				return '<p><em>' . esc_html__( 'Customer Cloud Gallery: Invalid gallery ID.', 'customer-cloud-gallery' ) . '</em></p>';
			}
			return '';
		}

		if ( (int) $atts['per_page'] > 0 ) {
			$gallery['per_page'] = (int) $atts['per_page'];
		}
		if ( in_array( $atts['load'], array( 'scroll', 'button' ), true ) ) {
			$gallery['load_mode'] = $atts['load'];
		}
		if ( in_array( $atts['size'], array( 'small', 'medium', 'large', 'xlarge' ), true ) ) {
			$gallery['image_size'] = $atts['size'];
		}

		if ( empty( $gallery['folder_id'] ) ) {
			if ( current_user_can( 'edit_posts' ) ) {
				return '<p><em>' . esc_html__( 'Customer Cloud Gallery: No storage folder configured. Please edit the gallery and add a Drive or Dropbox folder.', 'customer-cloud-gallery' ) . '</em></p>';
			}
			return '';
		}

		if ( ! CCGAL_Storage::adapter_for_gallery( $gallery )->is_connected() ) {
			$provider = $gallery['provider'] ?? 'google_drive';
			$label    = 'dropbox' === $provider ? 'Dropbox' : 'Google Drive';
			if ( current_user_can( 'manage_options' ) ) {
				return '<p><em>' . sprintf(
					/* translators: %s: provider name */
					esc_html__( 'Customer Cloud Gallery: %s is not connected. Please connect it in the settings.', 'customer-cloud-gallery' ),
					esc_html( $label )
				) . '</em></p>';
			}
			return '<p>' . esc_html__( 'This gallery is currently unavailable.', 'customer-cloud-gallery' ) . '</p>';
		}

		wp_enqueue_style( 'ccgal-gallery' );
		wp_enqueue_script( 'ccgal-gallery' );

		/**
		 * Fires after the gallery's frontend assets are enqueued. Allows
		 * extension modules (e.g. the Pro statistics module) to enqueue their
		 * own dependent scripts at the right moment — `wp_enqueue_scripts` runs
		 * before any shortcode is rendered, so a Pro module that wants to depend
		 * on `ccgal-gallery` cannot enqueue from there.
		 */
		do_action( 'ccgal_after_enqueue_frontend_assets' );

		$accent = CCGAL_Admin::get_accent_color();
		$hover  = CCGAL_Admin::get_hover_color();
		$border = CCGAL_Admin::get_border_color();
		$vars   = array();
		if ( $accent ) {
			$vars[] = '--ccgal-accent-override:' . $accent;
		}
		if ( $hover ) {
			$vars[] = '--ccgal-hover-override:' . $hover;
		}
		if ( $border ) {
			$vars[] = '--ccgal-border-override:' . $border;
		}
		if ( $vars ) {
			wp_add_inline_style(
				'ccgal-gallery',
				sprintf( '.ccgal-gallery{%s;}', implode( ';', $vars ) )
			);
		}

		if ( ! isset( self::$enqueued_galleries[ $gallery['id'] ] ) ) {
			self::$enqueued_galleries[ $gallery['id'] ] = true;

			// Effektive Favoriten-Erlaubnis: Cookies-Master muss an UND allow_favorites muss gesetzt sein.
			$effective_favorites = $gallery['allow_favorites'] && $gallery['cookies_enabled'];
			$pro_active          = ccgal_is_pro();

			$config = array(
				'gallery_id'      => $gallery['id'],
				'rest_url'        => esc_url_raw( rest_url( CCGAL_REST_API::NAMESPACE_V1 . '/gallery/' . $gallery['id'] ) ),
				'rest_nonce'      => wp_create_nonce( 'wp_rest' ),
				'gallery_nonce'   => wp_create_nonce( 'ccgal_gallery_' . $gallery['id'] ),
				'download_nonce'  => wp_create_nonce( 'ccgal_download_' . $gallery['id'] ),
				'download_url'    => admin_url( 'admin-ajax.php' ),
				// Cache-Buster, damit ein neuer Plugin-Build den SW im Browser auch wirklich
				// austauscht; ohne ?ver hält der Browser den alten SW bis zu 24h.
				'sw_zip_url'      => esc_url_raw( add_query_arg( 'ver', CCGAL_VERSION, CCGAL_URL . 'assets/js/sw-zip.js' ) ),
				'sw_zip_scope'    => esc_url_raw( CCGAL_URL . 'assets/js/' ),
				'per_page'        => (int) $gallery['per_page'],
				'load_mode'       => $gallery['load_mode'],
				'image_size'      => $gallery['image_size'],
				'allow_downloads' => (bool) $gallery['allow_downloads'],
				'allow_favorites' => $effective_favorites,
				'allow_print'     => (bool) $gallery['allow_print'] && $pro_active,
				'allow_zip_selection' => (bool) $gallery['allow_downloads'],
				'stats_enabled'   => (bool) $gallery['stats_enabled'],
				'cookies_enabled' => (bool) $gallery['cookies_enabled'],
				// stats_enabled is resolved by the Pro statistics module via the `ccgal_gallery_stats_enabled` filter — Free reports false.
				'print_page_url'  => $pro_active && (int) get_option( 'ccgal_print_page_id' ) ? esc_url_raw( get_permalink( (int) get_option( 'ccgal_print_page_id' ) ) ) : '',
				'strings'         => array(
					'loading'           => __( 'Loading images…', 'customer-cloud-gallery' ),
					'load_more'         => __( 'Load more', 'customer-cloud-gallery' ),
					'end_of_gallery'    => __( 'All images loaded', 'customer-cloud-gallery' ),
					'favorite_add'      => __( 'Add to favorites', 'customer-cloud-gallery' ),
					'favorite_remove'   => __( 'Remove from favorites', 'customer-cloud-gallery' ),
					'download_single'   => __( 'Download this image', 'customer-cloud-gallery' ),
					'download_all'      => __( 'Download all (ZIP)', 'customer-cloud-gallery' ),
					'download_selected' => __( 'Download selection (ZIP)', 'customer-cloud-gallery' ),
					'selection_label'   => __( 'Add to selection', 'customer-cloud-gallery' ),
					/* translators: %d: number of selected images */
					'selection_counter' => __( '%d selected', 'customer-cloud-gallery' ),
					'clear_selection'   => __( 'Clear selection', 'customer-cloud-gallery' ),
					'only_favorites_on' => __( 'Show only favorites', 'customer-cloud-gallery' ),
					'only_favorites_off'=> __( 'Show all', 'customer-cloud-gallery' ),
					'loading_all'       => __( 'Loading all images…', 'customer-cloud-gallery' ),
					'select_favorites'  => __( 'Select favorites', 'customer-cloud-gallery' ),
					'no_favorites'      => __( 'No favorites marked yet.', 'customer-cloud-gallery' ),
					'play_video'        => __( 'Play video', 'customer-cloud-gallery' ),
					'error_generic'     => __( 'An error occurred. Please reload the page.', 'customer-cloud-gallery' ),
					'lb_select_add'     => __( 'Add to selection', 'customer-cloud-gallery' ),
					'lb_select_remove'  => __( 'Remove from selection', 'customer-cloud-gallery' ),
					'close'             => __( 'Close', 'customer-cloud-gallery' ),
					'previous'          => __( 'Previous image', 'customer-cloud-gallery' ),
					'next'              => __( 'Next image', 'customer-cloud-gallery' ),
					'bulk_preparing'    => __( 'Preparing download…', 'customer-cloud-gallery' ),
					'bulk_downloading'  => __( 'Downloading images…', 'customer-cloud-gallery' ),
					'bulk_packing'      => __( 'Packaging ZIP…', 'customer-cloud-gallery' ),
					'bulk_cancel'       => __( 'Cancel', 'customer-cloud-gallery' ),
					'bulk_cancelling'   => __( 'Cancelling…', 'customer-cloud-gallery' ),
					'bulk_some_errors'  => __( 'Some files could not be downloaded:', 'customer-cloud-gallery' ),
					'bulk_failed'       => __( 'Bulk download failed. Falling back to ZIP.', 'customer-cloud-gallery' ),
					'bulk_empty'        => __( 'This gallery has no downloadable files.', 'customer-cloud-gallery' ),
					/* translators: {files}=files done, {total_files}=total files, {done}=size done, {total_size}=total size. The {…} tokens are replaced by the frontend at runtime. */
					'bulk_progress_template' => __( '{files} of {total_files} · {done} of {total_size}', 'customer-cloud-gallery' ),
				),
			);

			wp_add_inline_script(
				'ccgal-gallery',
				'window.CCGAL_CONFIG = window.CCGAL_CONFIG || {}; window.CCGAL_CONFIG[' . (int) $gallery['id'] . '] = ' . wp_json_encode( $config ) . ';',
				'before'
			);
		}

		ob_start();
		$is_pro          = ccgal_is_pro();
		$allow_downloads = $gallery['allow_downloads'];
		$allow_favorites = $gallery['allow_favorites'] && $gallery['cookies_enabled'];
		$allow_print     = $gallery['allow_print'] && $is_pro;
		$allow_zip_selection = $allow_downloads;
		$load_mode       = $gallery['load_mode'];
		$img_px          = CCGAL_CPT::image_size_to_px( $gallery['image_size'] );
		?>
		<div class="ccgal-gallery"
		     data-gallery-id="<?php echo esc_attr( $gallery['id'] ); ?>"
		     data-load-mode="<?php echo esc_attr( $load_mode ); ?>"
		     data-toolbar-align="<?php echo esc_attr( $gallery['toolbar_align'] ); ?>"
		     style="--ccgal-img-size: <?php echo esc_attr( $img_px ); ?>px;">

			<?php if ( $allow_downloads || $allow_favorites || $allow_print ) : ?>
			<div class="ccgal-toolbar">
				<?php if ( $allow_downloads ) : ?>
				<button type="button" class="ccgal-btn ccgal-btn-primary ccgal-download-all">
					<?php esc_html_e( 'Download all images', 'customer-cloud-gallery' ); ?>
				</button>
				<?php endif; ?>
				<?php if ( $allow_favorites ) : ?>
				<button type="button" class="ccgal-btn ccgal-btn-ghost ccgal-toggle-favorites" aria-pressed="false">
					<?php esc_html_e( 'Show only favorites', 'customer-cloud-gallery' ); ?>
				</button>
				<?php if ( $allow_zip_selection ) : ?>
				<button type="button" class="ccgal-btn ccgal-download-favorites" data-template="<?php
					/* translators: %d: number of favorited images */
					esc_attr_e( 'Download favorites (%d)', 'customer-cloud-gallery' ); ?>" hidden>
					<?php esc_html_e( 'Download favorites', 'customer-cloud-gallery' ); ?>
				</button>
				<?php endif; ?>
				<?php endif; ?>
				<?php if ( $allow_print ) : ?>
				<button type="button" class="ccgal-btn ccgal-btn-primary ccgal-print-selected" disabled>
					<?php esc_html_e( 'Order prints from selection', 'customer-cloud-gallery' ); ?>
				</button>
				<?php endif; ?>
				<?php if ( $allow_zip_selection ) : ?>
				<div class="ccgal-selection-controls" hidden>
					<span class="ccgal-selection-count" data-template="<?php
						/* translators: %d: number of selected images */
						esc_attr_e( '%d selected', 'customer-cloud-gallery' ); ?>"></span>
					<button type="button" class="ccgal-btn ccgal-download-selected">
						<?php esc_html_e( 'Download selection', 'customer-cloud-gallery' ); ?>
					</button>
					<button type="button" class="ccgal-btn ccgal-btn-ghost ccgal-clear-selection">
						<?php esc_html_e( 'Clear selection', 'customer-cloud-gallery' ); ?>
					</button>
				</div>
				<?php endif; ?>
			</div>
			<?php endif; ?>

			<div class="ccgal-grid" role="list"></div>

			<div class="ccgal-status" aria-live="polite">
				<span class="ccgal-loading" hidden><?php esc_html_e( 'Loading images…', 'customer-cloud-gallery' ); ?></span>
				<span class="ccgal-end" hidden><?php esc_html_e( 'All images loaded', 'customer-cloud-gallery' ); ?></span>
				<span class="ccgal-empty-favs" hidden><?php esc_html_e( 'No favorites marked yet.', 'customer-cloud-gallery' ); ?></span>
				<span class="ccgal-error" hidden></span>
			</div>

			<?php if ( 'button' === $load_mode ) : ?>
			<div class="ccgal-load-more-wrap">
				<button type="button" class="ccgal-btn ccgal-load-more"><?php esc_html_e( 'Load more', 'customer-cloud-gallery' ); ?></button>
			</div>
			<?php endif; ?>

			<?php if ( ! $gallery['cookies_enabled'] ) : ?>
			<p class="ccgal-cookie-hint" style="margin-top:18px;font-size:0.85em;color:#7a756c;text-align:center;">
				<?php esc_html_e( 'This gallery runs without cookies. Favorites are disabled.', 'customer-cloud-gallery' ); ?>
			</p>
			<?php endif; ?>

			<div class="ccgal-lightbox" hidden role="dialog" aria-modal="true">
				<button type="button" class="ccgal-lb-close" aria-label="<?php esc_attr_e( 'Close', 'customer-cloud-gallery' ); ?>">&times;</button>
				<button type="button" class="ccgal-lb-prev" aria-label="<?php esc_attr_e( 'Previous image', 'customer-cloud-gallery' ); ?>">&lsaquo;</button>
				<button type="button" class="ccgal-lb-next" aria-label="<?php esc_attr_e( 'Next image', 'customer-cloud-gallery' ); ?>">&rsaquo;</button>
				<div class="ccgal-lb-stage"></div>
				<div class="ccgal-lb-controls">
					<?php if ( $allow_favorites ) : ?>
					<button type="button" class="ccgal-lb-btn ccgal-lb-favorite" aria-pressed="false" aria-label="<?php esc_attr_e( 'Favorite', 'customer-cloud-gallery' ); ?>"></button>
					<?php endif; ?>
					<?php if ( $allow_zip_selection ) : ?>
					<button type="button" class="ccgal-lb-btn ccgal-lb-select" aria-pressed="false" aria-label="<?php esc_attr_e( 'Add to selection', 'customer-cloud-gallery' ); ?>"></button>
					<?php endif; ?>
					<?php if ( $allow_downloads ) : ?>
					<button type="button" class="ccgal-lb-btn ccgal-lb-download" aria-label="<?php esc_attr_e( 'Download', 'customer-cloud-gallery' ); ?>"></button>
					<?php endif; ?>
				</div>
			</div>
		</div>
		<?php
		return ob_get_clean();
	}
}
