<?php
/**
 * Link Shortener – Admin UI (modal only)
 *
 * @package LinkShortener
 * @since 1.0.0
 */

use WP_PowerSuite\Core\OptionStoreModuleSettingsRepository;

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

if ( ! function_exists( 'wp_powersuite_is_license_valid' ) || ! wp_powersuite_is_license_valid() ) {
	$license_page_url = admin_url( 'admin.php?page=powersuite-license' );
	?>
	<div class="wp-powersuite-module-settings wpps-settings-panel" data-module-id="<?php echo esc_attr( $module_id ?? 'link-shortener' ); ?>">
		<div class="notice notice-warning inline" style="margin:0;">
			<p>
				<?php esc_html_e( 'URL Shortener requires an active license. Activate your license to create short links and view click analytics.', 'wp-powersuite' ); ?>
				<a href="<?php echo esc_url( $license_page_url ); ?>"><?php esc_html_e( 'Activate license', 'wp-powersuite' ); ?></a>
			</p>
		</div>
	</div>
	<?php
	return;
}

$module_id = $module_id ?? 'link-shortener';

$settings     = OptionStoreModuleSettingsRepository::forModule( $module_id )->all( [] );
$defaults = [
	'url_prefix'                => 'link',
	'expired_redirect_home'     => true,
	'default_password'          => '',
	'default_short_code_length' => 6,
	'track_clicks'              => true,
	'track_detailed_analytics'  => true,
	'analytics_retention_days'  => 14,
	'forward_query_strings'     => false,
];
$settings = is_array( $settings ) ? array_merge( $defaults, $settings ) : $defaults;

$url_prefix = isset( $settings['url_prefix'] ) ? trim( (string) $settings['url_prefix'] ) : 'link';
$expired_redirect_home = ! empty( $settings['expired_redirect_home'] );
$default_password = isset( $settings['default_password'] ) ? $settings['default_password'] : '';
$default_short_code_length = isset( $settings['default_short_code_length'] ) ? max( 4, min( 20, (int) $settings['default_short_code_length'] ) ) : 6;
$track_clicks = ! empty( $settings['track_clicks'] );
$track_detailed_analytics = ! empty( $settings['track_detailed_analytics'] );
$analytics_retention_days = isset( $settings['analytics_retention_days'] ) ? max( 0, min( 365, (int) $settings['analytics_retention_days'] ) ) : 14;
$forward_query_strings = ! empty( $settings['forward_query_strings'] );

$module = null;
if ( class_exists( 'WP_PowerSuite\Core\ModuleManager' ) ) {
	$manager = \WP_PowerSuite\Core\ModuleManager::getInstance();
	$module  = $manager->getModule( 'link-shortener' );
}
if ( $module === null && class_exists( 'LinkShortener\Module' ) ) {
	$module = new \LinkShortener\Module();
}

$stats = [];
$links = [];
if ( $module instanceof \LinkShortener\Module ) {
	$stats = $module->getStats();
	$links = $module->getLinks( [ 'page' => 1, 'per_page' => 50 ] );
}

$url_prefix_for_base = ( $module instanceof \LinkShortener\Module ) ? trim( $module->getUrlPrefix(), '/' ) : 'link';
if ( $url_prefix_for_base === '' ) {
	$url_prefix_for_base = 'link';
}
$base_url = home_url( '/' . $url_prefix_for_base . '/' );
$ajax_url = admin_url( 'admin-ajax.php' );
$nonce    = wp_create_nonce( 'wp_powersuite_ajax' );
$export_links_url = admin_url( 'admin-ajax.php?action=wpps_link_shortener_export&nonce=' . $nonce );
$export_analytics_url = admin_url( 'admin-ajax.php?action=wpps_link_shortener_export_analytics&nonce=' . $nonce );

$date_format = get_option( 'date_format' ) . ' ' . get_option( 'time_format' );
?>
<div class="wp-powersuite-module-settings wpps-ls-modal wpps-link-shortener" data-ajax-url="<?php echo esc_attr( $ajax_url ); ?>" data-nonce="<?php echo esc_attr( $nonce ); ?>" data-base-url="<?php echo esc_attr( $base_url ); ?>">
	<p class="description wpps-ls-description">
		<?php esc_html_e( 'Create short URLs, track clicks, and set expiration or password protection.', 'wp-powersuite' ); ?>
	</p>

	<div class="wpps-ls-tabs" role="tablist" aria-label="<?php esc_attr_e( 'Link Shortener', 'wp-powersuite' ); ?>">
		<button type="button" class="wpps-ls-tab-btn" role="tab" aria-selected="false" aria-controls="wpps-ls-panel-settings" data-tab="settings" id="wpps-ls-tab-settings"><?php esc_html_e( 'Settings', 'wp-powersuite' ); ?></button>
		<button type="button" class="wpps-ls-tab-btn" role="tab" aria-selected="false" aria-controls="wpps-ls-panel-add" data-tab="add" id="wpps-ls-tab-add"><?php esc_html_e( 'Add Link', 'wp-powersuite' ); ?></button>
		<button type="button" class="wpps-ls-tab-btn is-active" role="tab" aria-selected="true" aria-controls="wpps-ls-panel-links" data-tab="links" id="wpps-ls-tab-links"><?php esc_html_e( 'View Links', 'wp-powersuite' ); ?></button>

		<div class="wpps-ls-tab-panels">
			<!-- Settings -->
			<div id="wpps-ls-panel-settings" class="wpps-ls-tab-panel" role="tabpanel" aria-labelledby="wpps-ls-tab-settings" hidden>
				<form class="wp-powersuite-module-settings-form" data-module-id="<?php echo esc_attr( $module_id ); ?>">
					<?php wp_nonce_field( 'wp_powersuite_save_module_settings_' . $module_id, 'wp_powersuite_nonce' ); ?>
					<p class="description wpps-ls-privacy-note">
						<?php esc_html_e( 'Short links redirect visitors to external URLs you configure. Only share links to destinations you trust, and review click analytics periodically.', 'wp-powersuite' ); ?>
					</p>
					<table class="form-table" role="presentation">
						<tbody>
				<tr>
					<th scope="row"><label for="wpps-ls-url_prefix"><?php esc_html_e( 'URL Prefix', 'wp-powersuite' ); ?></label></th>
					<td>
						<input type="text" id="wpps-ls-url_prefix" name="url_prefix" value="<?php echo esc_attr( $url_prefix ); ?>" class="regular-text wp-powersuite-advanced-setting" data-setting-key="url_prefix" placeholder="link" />
						<?php /* translators: %s: string value. */ ?>
						<p class="description"><?php echo esc_html( sprintf( __( 'Short links will be: yoursite.com/%s/short-code. Default: link.', 'wp-powersuite' ), $url_prefix ) ); ?></p>
					</td>
				</tr>
				<tr>
					<th scope="row"><label for="wpps-ls-expired_redirect_home"><?php esc_html_e( 'Expired / Invalid Links', 'wp-powersuite' ); ?></label></th>
					<td>
						<label>
							<input type="checkbox" id="wpps-ls-expired_redirect_home" name="expired_redirect_home" value="1" <?php checked( $expired_redirect_home ); ?> class="wp-powersuite-advanced-setting" data-setting-key="expired_redirect_home" />
							<?php esc_html_e( 'Redirect to homepage when link is expired or invalid', 'wp-powersuite' ); ?>
						</label>
					</td>
				</tr>
				<tr>
					<th scope="row"><label for="wpps-ls-default_password"><?php esc_html_e( 'Default Password', 'wp-powersuite' ); ?></label></th>
					<td>
						<input type="password" id="wpps-ls-default_password" name="default_password" value="<?php echo esc_attr( $default_password ); ?>" class="regular-text wp-powersuite-advanced-setting" data-setting-key="default_password" autocomplete="new-password" />
						<p class="description"><?php esc_html_e( 'Optional. Applied to new links when no password is set.', 'wp-powersuite' ); ?></p>
					</td>
				</tr>
				<tr>
					<th scope="row"><label for="wpps-ls-track_clicks"><?php esc_html_e( 'Click Tracking', 'wp-powersuite' ); ?></label></th>
					<td>
						<label>
							<input type="checkbox" id="wpps-ls-track_clicks" name="track_clicks" value="1" <?php checked( $track_clicks ); ?> class="wp-powersuite-advanced-setting" data-setting-key="track_clicks" />
							<?php esc_html_e( 'Track click counts on short links', 'wp-powersuite' ); ?>
						</label>
					</td>
				</tr>
				<tr>
					<th scope="row"><label for="wpps-ls-track_detailed_analytics"><?php esc_html_e( 'Detailed Analytics', 'wp-powersuite' ); ?></label></th>
					<td>
						<label>
							<input type="checkbox" id="wpps-ls-track_detailed_analytics" name="track_detailed_analytics" value="1" <?php checked( $track_detailed_analytics ); ?> class="wp-powersuite-advanced-setting" data-setting-key="track_detailed_analytics" />
							<?php esc_html_e( 'Store anonymized IP, referer, and user agent per click', 'wp-powersuite' ); ?>
						</label>
						<p class="description"><?php esc_html_e( 'IP addresses are anonymized before storage. Disable for click counts only.', 'wp-powersuite' ); ?></p>
					</td>
				</tr>
				<tr>
					<th scope="row"><label for="wpps-ls-analytics_retention_days"><?php esc_html_e( 'Analytics Retention (days)', 'wp-powersuite' ); ?></label></th>
					<td>
						<input type="number" id="wpps-ls-analytics_retention_days" name="analytics_retention_days" value="<?php echo esc_attr( (string) $analytics_retention_days ); ?>" class="small-text wp-powersuite-advanced-setting" data-setting-key="analytics_retention_days" min="0" max="365" />
						<p class="description"><?php esc_html_e( 'Detailed click logs older than this are deleted daily. Use 0 to keep all records.', 'wp-powersuite' ); ?></p>
					</td>
				</tr>
				<tr>
					<th scope="row"><label for="wpps-ls-forward_query_strings"><?php esc_html_e( 'Forward Query Strings', 'wp-powersuite' ); ?></label></th>
					<td>
						<label>
							<input type="checkbox" id="wpps-ls-forward_query_strings" name="forward_query_strings" value="1" <?php checked( $forward_query_strings ); ?> class="wp-powersuite-advanced-setting" data-setting-key="forward_query_strings" />
							<?php esc_html_e( 'Append short-link query parameters to the destination URL', 'wp-powersuite' ); ?>
						</label>
					</td>
				</tr>
				<tr>
					<th scope="row"><label for="wpps-ls-default_short_code_length"><?php esc_html_e( 'Default Short Code Length', 'wp-powersuite' ); ?></label></th>
					<td>
						<input type="number" id="wpps-ls-default_short_code_length" name="default_short_code_length" value="<?php echo esc_attr( (string) $default_short_code_length ); ?>" class="small-text wp-powersuite-advanced-setting" data-setting-key="default_short_code_length" min="4" max="20" />
						<p class="description"><?php esc_html_e( 'Length of auto-generated short codes (4–20).', 'wp-powersuite' ); ?></p>
					</td>
				</tr>
						</tbody>
					</table>
				</form>
			</div>

			<!-- Add / Edit Link -->
			<div id="wpps-ls-panel-add" class="wpps-ls-tab-panel" role="tabpanel" aria-labelledby="wpps-ls-tab-add" hidden>
				<h4 class="wpps-ls-section-title" id="wpps-ls-form-title"><?php esc_html_e( 'Add New Link', 'wp-powersuite' ); ?></h4>
				<form id="wpps-ls-form" class="wpps-ls-form">
					<input type="hidden" name="id" id="wpps-ls-id" value="" />
					<table class="form-table" role="presentation">
						<tr>
							<th><label for="wpps-ls-destination_url"><?php esc_html_e( 'Destination URL', 'wp-powersuite' ); ?></label></th>
							<td><input type="url" id="wpps-ls-destination_url" name="destination_url" class="large-text" required placeholder="https://..." /></td>
						</tr>
						<tr>
							<th><label for="wpps-ls-short_code"><?php esc_html_e( 'Short Code', 'wp-powersuite' ); ?></label></th>
							<td>
								<input type="text" id="wpps-ls-short_code" name="short_code" class="regular-text" placeholder="<?php esc_attr_e( 'e.g. summer-sale (leave blank to auto-generate)', 'wp-powersuite' ); ?>" />
								<p class="description"><?php esc_html_e( 'Letters, numbers, and hyphens only. Leave blank for auto-generated.', 'wp-powersuite' ); ?></p>
							</td>
						</tr>
						<tr>
							<th><label for="wpps-ls-redirect_type"><?php esc_html_e( 'Redirect Type', 'wp-powersuite' ); ?></label></th>
							<td>
								<select id="wpps-ls-redirect_type" name="redirect_type">
									<option value="301"><?php esc_html_e( '301 Permanent', 'wp-powersuite' ); ?></option>
									<option value="302"><?php esc_html_e( '302 Temporary', 'wp-powersuite' ); ?></option>
									<option value="307"><?php esc_html_e( '307 Temporary (preserve method)', 'wp-powersuite' ); ?></option>
									<option value="308"><?php esc_html_e( '308 Permanent (preserve method)', 'wp-powersuite' ); ?></option>
								</select>
								<p class="description"><?php esc_html_e( '301 passes SEO value; 302 does not. Use 302 for A/B tests or temporary links.', 'wp-powersuite' ); ?></p>
							</td>
						</tr>
						<tr>
							<th><label for="wpps-ls-active"><?php esc_html_e( 'Active', 'wp-powersuite' ); ?></label></th>
							<td><label><input type="checkbox" id="wpps-ls-active" name="active" value="1" checked /> <?php esc_html_e( 'Enable this link', 'wp-powersuite' ); ?></label></td>
						</tr>
						<tr>
							<th><label for="wpps-ls-expires_at"><?php esc_html_e( 'Expires', 'wp-powersuite' ); ?></label></th>
							<td><input type="datetime-local" id="wpps-ls-expires_at" name="expires_at" class="regular-text" /> <span class="description"><?php esc_html_e( 'Optional', 'wp-powersuite' ); ?></span></td>
						</tr>
						<tr>
							<th><label for="wpps-ls-expire_redirect_url"><?php esc_html_e( 'Expire Redirect', 'wp-powersuite' ); ?></label></th>
							<td><input type="url" id="wpps-ls-expire_redirect_url" name="expire_redirect_url" class="large-text" placeholder="https://..." /> <span class="description"><?php esc_html_e( 'Optional. Where to redirect when link expires.', 'wp-powersuite' ); ?></span></td>
						</tr>
						<tr>
							<th><label for="wpps-ls-password"><?php esc_html_e( 'Password', 'wp-powersuite' ); ?></label></th>
							<td>
								<input type="password" id="wpps-ls-password" name="password" class="regular-text" autocomplete="new-password" />
								<input type="hidden" name="password_unchanged" id="wpps-ls-password_unchanged" value="0" />
								<p class="description"><?php esc_html_e( 'Optional. Leave blank to keep existing or no password.', 'wp-powersuite' ); ?></p>
							</td>
						</tr>
					</table>
					<p class="wpps-ls-form-actions">
						<button type="submit" class="button button-primary"><?php esc_html_e( 'Save Link', 'wp-powersuite' ); ?></button>
						<button type="button" class="button" id="wpps-ls-form-cancel"><?php esc_html_e( 'Cancel', 'wp-powersuite' ); ?></button>
					</p>
				</form>
			</div>

			<!-- View Links -->
			<div id="wpps-ls-panel-links" class="wpps-ls-tab-panel is-active" role="tabpanel" aria-labelledby="wpps-ls-tab-links">
				<div class="wpps-ls-stats">
					<div class="wpps-ls-stat-card">
						<span class="wpps-ls-stat-value" id="wpps-ls-stat-total-links"><?php echo esc_html( number_format_i18n( $stats['total_links'] ?? 0 ) ); ?></span>
						<span class="wpps-ls-stat-label"><?php esc_html_e( 'Total Links', 'wp-powersuite' ); ?></span>
					</div>
					<div class="wpps-ls-stat-card">
						<span class="wpps-ls-stat-value" id="wpps-ls-stat-total-clicks"><?php echo esc_html( number_format_i18n( $stats['total_clicks'] ?? 0 ) ); ?></span>
						<span class="wpps-ls-stat-label"><?php esc_html_e( 'Total Clicks', 'wp-powersuite' ); ?></span>
					</div>
					<div class="wpps-ls-stat-card">
						<span class="wpps-ls-stat-value" id="wpps-ls-stat-active"><?php echo esc_html( number_format_i18n( $stats['active_links'] ?? 0 ) ); ?></span>
						<span class="wpps-ls-stat-label"><?php esc_html_e( 'Active Links', 'wp-powersuite' ); ?></span>
					</div>
				</div>

				<div class="wpps-ls-toolbar">
					<div class="wpps-ls-toolbar-left">
						<button type="button" class="button button-primary" id="wpps-ls-add-btn"><?php esc_html_e( 'Add New Link', 'wp-powersuite' ); ?></button>
						<div class="wpps-ls-bulk-actions" id="wpps-ls-bulk-actions" style="display: none;">
							<select id="wpps-ls-bulk-select">
								<option value=""><?php esc_html_e( 'Bulk actions', 'wp-powersuite' ); ?></option>
								<option value="activate"><?php esc_html_e( 'Activate', 'wp-powersuite' ); ?></option>
								<option value="deactivate"><?php esc_html_e( 'Deactivate', 'wp-powersuite' ); ?></option>
								<option value="delete"><?php esc_html_e( 'Delete', 'wp-powersuite' ); ?></option>
							</select>
							<button type="button" class="button" id="wpps-ls-bulk-apply"><?php esc_html_e( 'Apply', 'wp-powersuite' ); ?></button>
						</div>
					</div>
					<div class="wpps-ls-toolbar-right">
						<button type="button" class="button" id="wpps-ls-import-btn"><?php esc_html_e( 'Import CSV', 'wp-powersuite' ); ?></button>
						<input type="file" id="wpps-ls-import-file" accept=".csv" style="display: none;" />
						<a href="#" id="wpps-ls-export-btn" class="button" data-base-url="<?php echo esc_attr( $export_links_url ); ?>"><?php esc_html_e( 'Export Links', 'wp-powersuite' ); ?></a>
						<a href="#" id="wpps-ls-export-analytics-btn" class="button" data-base-url="<?php echo esc_attr( $export_analytics_url ); ?>"><?php esc_html_e( 'Export Analytics', 'wp-powersuite' ); ?></a>
						<label class="wpps-ls-search-wrap">
							<input type="search" id="wpps-ls-search" class="wpps-ls-search-input" placeholder="<?php esc_attr_e( 'Search short code or URL…', 'wp-powersuite' ); ?>" />
							<button type="button" class="button" id="wpps-ls-search-btn"><?php esc_html_e( 'Search', 'wp-powersuite' ); ?></button>
						</label>
					</div>
				</div>

				<div class="wpps-ls-table-wrap">
			<table class="wpps-ls-table widefat striped">
				<thead>
					<tr>
						<td class="check-column"><input type="checkbox" id="wpps-ls-select-all" aria-label="<?php esc_attr_e( 'Select all', 'wp-powersuite' ); ?>" /></td>
						<th class="column-short-code"><?php esc_html_e( 'Short Code', 'wp-powersuite' ); ?></th>
						<th class="column-destination"><?php esc_html_e( 'Destination', 'wp-powersuite' ); ?></th>
						<th class="num"><?php esc_html_e( 'Clicks', 'wp-powersuite' ); ?></th>
						<th class="column-created"><?php esc_html_e( 'Created', 'wp-powersuite' ); ?></th>
						<th class="column-last-clicked"><?php esc_html_e( 'Last Clicked', 'wp-powersuite' ); ?></th>
						<th class="column-status"><?php esc_html_e( 'Status', 'wp-powersuite' ); ?></th>
						<th class="column-actions"><?php esc_html_e( 'Actions', 'wp-powersuite' ); ?></th>
					</tr>
				</thead>
			<tbody id="wpps-ls-tbody">
				<?php
				foreach ( $links as $link ) {
					$id          = (int) ( $link['id'] ?? 0 );
					$short_code  = $link['short_code'] ?? '';
					$dest_url    = $link['destination_url'] ?? '';
					$short_url   = ( $module instanceof \LinkShortener\Module ) ? $module->getShortUrl( $short_code ) : home_url( '/' . $url_prefix . '/' . $short_code );
					$created_ts  = ! empty( $link['created_at'] ) ? strtotime( $link['created_at'] ) : false;
					$last_ts     = ! empty( $link['last_clicked_at'] ) ? strtotime( $link['last_clicked_at'] ) : false;
					$created     = $created_ts ? wp_date( $date_format, $created_ts ) : '—';
					$last        = $last_ts ? wp_date( $date_format, $last_ts ) : '—';
					$expires_ts  = ! empty( $link['expires_at'] ) ? strtotime( $link['expires_at'] ) : false;
					$expired     = $expires_ts && $expires_ts < time();
					$active      = ! empty( $link['active'] ) && ! $expired;
					$expires_at_local = \LinkShortener\Module::formatDateTimeLocal( $link['expires_at'] ?? null );
					$expire_redirect_url = $link['expire_redirect_url'] ?? '';
					$redirect_type = isset( $link['redirect_type'] ) ? (string) (int) $link['redirect_type'] : '301';
					$dest_display = \LinkShortener\Module::truncateUrl( $dest_url, 50 );
					$status_label = $expired ? __( 'Expired', 'wp-powersuite' ) : ( $active ? __( 'Active', 'wp-powersuite' ) : __( 'Inactive', 'wp-powersuite' ) );
					$status_class = $expired ? 'expired' : ( $active ? 'active' : 'inactive' );
					?>
					<tr data-id="<?php echo esc_attr( (string) $id ); ?>" data-destination-url="<?php echo esc_attr( $dest_url ); ?>" data-short-code="<?php echo esc_attr( $short_code ); ?>" data-expires-at="<?php echo esc_attr( $expires_at_local ); ?>" data-expire-redirect-url="<?php echo esc_attr( $expire_redirect_url ); ?>" data-redirect-type="<?php echo esc_attr( $redirect_type ); ?>" data-active="<?php echo $active ? '1' : '0'; ?>">
						<th class="check-column"><input type="checkbox" class="wpps-ls-row-cb" value="<?php echo esc_attr( (string) $id ); ?>" /></th>
						<td class="column-short-code"><code><?php echo esc_html( $short_code ); ?></code></td>
						<td class="column-destination"><a href="<?php echo esc_url( $dest_url ); ?>" target="_blank" rel="noopener"><?php echo esc_html( $dest_display ); ?></a></td>
						<td class="num"><?php echo esc_html( (string) ( $link['click_count'] ?? 0 ) ); ?></td>
						<td class="column-created"><?php echo esc_html( $created ); ?></td>
						<td class="column-last-clicked"><?php echo esc_html( $last ); ?></td>
						<td class="column-status">
							<span class="wpps-ls-status-badge wpps-ls-status-<?php echo esc_attr( $status_class ); ?>"><?php echo esc_html( $status_label ); ?></span>
						</td>
						<td class="column-actions">
							<span class="wpps-ls-row-actions">
								<button type="button" class="button-link wpps-ls-analytics wpps-ls-action-btn" data-id="<?php echo esc_attr( (string) $id ); ?>" data-short-code="<?php echo esc_attr( $short_code ); ?>" title="<?php esc_attr_e( 'View analytics', 'wp-powersuite' ); ?>" aria-label="<?php esc_attr_e( 'View analytics', 'wp-powersuite' ); ?>"><span class="dashicons dashicons-chart-bar" aria-hidden="true"></span></button>
								<button type="button" class="button-link wpps-ls-copy wpps-ls-action-btn" data-url="<?php echo esc_attr( $short_url ); ?>" title="<?php esc_attr_e( 'Copy link', 'wp-powersuite' ); ?>" aria-label="<?php esc_attr_e( 'Copy link', 'wp-powersuite' ); ?>"><span class="dashicons dashicons-admin-links" aria-hidden="true"></span></button>
								<button type="button" class="button-link wpps-ls-duplicate wpps-ls-action-btn" data-id="<?php echo esc_attr( (string) $id ); ?>" title="<?php esc_attr_e( 'Duplicate', 'wp-powersuite' ); ?>" aria-label="<?php esc_attr_e( 'Duplicate', 'wp-powersuite' ); ?>"><span class="dashicons dashicons-admin-page" aria-hidden="true"></span></button>
								<button type="button" class="button-link wpps-ls-edit wpps-ls-action-btn" data-id="<?php echo esc_attr( (string) $id ); ?>" title="<?php esc_attr_e( 'Edit', 'wp-powersuite' ); ?>" aria-label="<?php esc_attr_e( 'Edit', 'wp-powersuite' ); ?>"><span class="dashicons dashicons-edit" aria-hidden="true"></span></button>
								<button type="button" class="button-link wpps-ls-toggle-active wpps-ls-action-btn" data-id="<?php echo esc_attr( (string) $id ); ?>" title="<?php echo $active ? esc_attr__( 'Deactivate', 'wp-powersuite' ) : esc_attr__( 'Activate', 'wp-powersuite' ); ?>" aria-label="<?php echo $active ? esc_attr__( 'Deactivate', 'wp-powersuite' ) : esc_attr__( 'Activate', 'wp-powersuite' ); ?>"><span class="dashicons <?php echo $active ? 'dashicons-visibility' : 'dashicons-hidden'; ?>" aria-hidden="true"></span></button>
								<button type="button" class="button-link wpps-ls-delete wpps-ls-action-btn" data-id="<?php echo esc_attr( (string) $id ); ?>" title="<?php esc_attr_e( 'Delete', 'wp-powersuite' ); ?>" aria-label="<?php esc_attr_e( 'Delete', 'wp-powersuite' ); ?>"><span class="dashicons dashicons-trash" aria-hidden="true"></span></button>
							</span>
						</td>
					</tr>
				<?php } ?>
				<?php if ( empty( $links ) ) : ?>
					<tr><td colspan="8"><?php esc_html_e( 'No short links yet. Open the Add Link tab to create one.', 'wp-powersuite' ); ?></td></tr>
				<?php endif; ?>
			</tbody>
		</table>
		</div>
				<div class="wpps-ls-pagination" id="wpps-ls-pagination" style="display: none;">
					<button type="button" class="button" id="wpps-ls-prev-page"><?php esc_html_e( 'Previous', 'wp-powersuite' ); ?></button>
					<span id="wpps-ls-page-info"></span>
					<button type="button" class="button" id="wpps-ls-next-page"><?php esc_html_e( 'Next', 'wp-powersuite' ); ?></button>
				</div>
			</div>
		</div>
	</div>
</div>

<!-- Analytics modal -->
<div id="wpps-ls-analytics-modal" class="wpps-ls-analytics-modal" style="display: none;" role="dialog" aria-labelledby="wpps-ls-analytics-title" aria-modal="true">
	<div class="wpps-ls-analytics-modal-backdrop"></div>
	<div class="wpps-ls-analytics-modal-content">
		<div class="wpps-ls-analytics-modal-header">
			<h3 id="wpps-ls-analytics-title" class="wpps-ls-analytics-modal-title"><?php esc_html_e( 'Click Analytics', 'wp-powersuite' ); ?></h3>
			<button type="button" class="wpps-ls-analytics-modal-close" aria-label="<?php esc_attr_e( 'Close', 'wp-powersuite' ); ?>">&times;</button>
		</div>
		<div class="wpps-ls-analytics-modal-body">
			<div id="wpps-ls-analytics-loading" class="wpps-ls-analytics-loading"><?php esc_html_e( 'Loading…', 'wp-powersuite' ); ?></div>
			<div id="wpps-ls-analytics-content" class="wpps-ls-analytics-content" style="display: none;">
				<p class="wpps-ls-analytics-summary">
					<strong id="wpps-ls-analytics-short-url"></strong> — <span id="wpps-ls-analytics-total"></span>
					<a href="#" id="wpps-ls-analytics-export-btn" class="button button-small" data-base-url="<?php echo esc_attr( $export_analytics_url ); ?>" style="margin-left: 8px; vertical-align: middle;"><?php esc_html_e( 'Export CSV', 'wp-powersuite' ); ?></a>
				</p>
				<div class="wpps-ls-analytics-table-wrap">
					<table class="wpps-ls-analytics-table widefat striped">
						<thead>
							<tr>
								<th><?php esc_html_e( 'Date / Time', 'wp-powersuite' ); ?></th>
								<th><?php esc_html_e( 'IP Address', 'wp-powersuite' ); ?></th>
								<th><?php esc_html_e( 'Referer', 'wp-powersuite' ); ?></th>
								<th><?php esc_html_e( 'User Agent', 'wp-powersuite' ); ?></th>
							</tr>
						</thead>
						<tbody id="wpps-ls-analytics-tbody"></tbody>
					</table>
				</div>
				<p id="wpps-ls-analytics-empty" class="wpps-ls-analytics-empty" style="display: none;"><?php esc_html_e( 'No click data recorded yet.', 'wp-powersuite' ); ?></p>
				<div class="wpps-ls-analytics-pagination" id="wpps-ls-analytics-pagination" style="display: none;">
					<button type="button" class="button" id="wpps-ls-analytics-prev"><?php esc_html_e( 'Previous', 'wp-powersuite' ); ?></button>
					<span id="wpps-ls-analytics-page-info"></span>
					<button type="button" class="button" id="wpps-ls-analytics-next"><?php esc_html_e( 'Next', 'wp-powersuite' ); ?></button>
				</div>
			</div>
		</div>
	</div>
</div>

<style>
.wpps-ls-modal .wpps-ls-description { margin: 0 0 12px; }
.wpps-ls-modal .wpps-ls-tabs { display: flex; flex-wrap: wrap; gap: 8px; margin-bottom: 16px; align-items: flex-start; }
.wpps-ls-modal .wpps-ls-tab-panels { flex: 1 1 100%; order: 10; width: 100%; }
.wpps-ls-modal .wpps-ls-tab-btn { padding: 8px 16px; border: 1px solid #c3c4c7; background: #f6f7f7; border-radius: 4px; cursor: pointer; font-size: 13px; transition: background .15s, color .15s, border-color .15s; }
.wpps-ls-modal .wpps-ls-tab-btn:hover { background: #fff; }
.wpps-ls-modal .wpps-ls-tab-btn.is-active { background: #fff; border-color: #2271b1; color: #2271b1; font-weight: 600; }
.wpps-ls-modal .wpps-ls-tab-panel { display: none; padding: 4px 0 0; }
.wpps-ls-modal .wpps-ls-tab-panel.is-active { display: block; }
.wpps-ls-modal .wpps-ls-tab-panel .form-table { margin-top: 0; }
.wpps-ls-modal .wpps-ls-stats { display: flex; gap: 12px; flex-wrap: wrap; margin: 0 0 16px; }
.wpps-ls-modal .wpps-ls-stat-card { background: #f0f6fc; border: 1px solid #c3c4c7; border-radius: 4px; padding: 10px 16px; min-width: 100px; }
.wpps-ls-modal .wpps-ls-stat-value { display: block; font-size: 22px; font-weight: 600; color: #1d2327; }
.wpps-ls-modal .wpps-ls-stat-label { font-size: 12px; color: #646970; }
.wpps-ls-modal .wpps-ls-section-title { margin: 0 0 12px; font-size: 14px; font-weight: 600; }
.wpps-ls-modal .wpps-ls-toolbar { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 12px; margin: 0 0 16px; }
.wpps-ls-modal .wpps-ls-toolbar-left { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; }
.wpps-ls-modal .wpps-ls-toolbar-right .wpps-ls-search-wrap { display: inline-flex; align-items: center; gap: 6px; }
.wpps-ls-modal .wpps-ls-search-input { width: 200px; }
.wpps-ls-modal .wpps-ls-form-actions { margin: 12px 0 0; }
.wpps-ls-modal .wpps-ls-table-wrap { margin-bottom: 20px; }
.wpps-ls-modal .wpps-ls-table { margin-top: 0; margin-bottom: 12px; font-size: 12px; }
.wpps-ls-modal .wpps-ls-table code { font-size: 11px; word-break: break-all; }
.wpps-ls-modal .wpps-ls-table .num { width: 60px; text-align: right; }
.wpps-ls-modal .wpps-ls-status-badge { display: inline-block; padding: 2px 8px; border-radius: 3px; font-size: 11px; }
.wpps-ls-modal .wpps-ls-status-active { background: #d4edda; color: #155724; }
.wpps-ls-modal .wpps-ls-status-inactive { background: #f8d7da; color: #721c24; }
.wpps-ls-modal .wpps-ls-status-expired { background: #fff3cd; color: #856404; }
.wpps-ls-modal .wpps-ls-pagination, .wpps-ls-analytics-pagination { display: flex; align-items: center; gap: 10px; margin-top: 12px; }
.wpps-ls-modal .wpps-ls-row-actions { white-space: nowrap; display: inline-flex; align-items: center; gap: 4px; }
.wpps-ls-modal .wpps-ls-action-btn { padding: 2px; margin: 0; border: none; background: none; cursor: pointer; color: #2271b1; display: inline-flex; align-items: center; justify-content: center; }
.wpps-ls-modal .wpps-ls-action-btn:hover { color: #135e96; }
.wpps-ls-modal .wpps-ls-action-btn .dashicons { font-size: 18px; width: 18px; height: 18px; }
.wpps-ls-modal .wpps-ls-action-btn.wpps-ls-delete:hover { color: #b32d2e; }
.wpps-ls-modal .wpps-ls-empty-msg { color: #646970; font-style: italic; padding: 12px !important; }
.wpps-ls-analytics-modal { position: fixed; inset: 0; z-index: 100100; display: flex; align-items: center; justify-content: center; padding: 20px; }
.wpps-ls-analytics-modal-backdrop { position: absolute; inset: 0; background: rgba(0,0,0,.5); }
.wpps-ls-analytics-modal-content { position: relative; background: #fff; border-radius: 4px; box-shadow: 0 4px 20px rgba(0,0,0,.2); max-width: 900px; width: 100%; max-height: 80vh; display: flex; flex-direction: column; }
.wpps-ls-analytics-modal-header { display: flex; align-items: center; justify-content: space-between; padding: 16px 20px; border-bottom: 1px solid #c3c4c7; }
.wpps-ls-analytics-modal-title { margin: 0; font-size: 16px; }
.wpps-ls-analytics-modal-close { background: none; border: none; font-size: 24px; line-height: 1; cursor: pointer; color: #646970; padding: 0 4px; }
.wpps-ls-analytics-modal-close:hover { color: #1d2327; }
.wpps-ls-analytics-modal-body { padding: 20px; overflow-y: auto; flex: 1; }
.wpps-ls-analytics-loading { color: #646970; }
.wpps-ls-analytics-summary { margin: 0 0 16px; font-size: 13px; display: flex; flex-wrap: wrap; align-items: center; gap: 8px; }
.wpps-ls-analytics-table-wrap { overflow-x: auto; max-height: 400px; overflow-y: auto; }
.wpps-ls-analytics-table { font-size: 12px; margin: 0; }
.wpps-ls-analytics-table th, .wpps-ls-analytics-table td { padding: 8px 12px; }
.wpps-ls-analytics-table .user-agent-cell { max-width: 280px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.wpps-ls-analytics-empty { color: #646970; margin: 12px 0 0; }
</style>

<script>
(function() {
	function escapeHtml(s) {
		if (s == null) return '';
		var div = document.createElement('div');
		div.textContent = s;
		return div.innerHTML;
	}
	function initLinkShortener() {
		var wrap = document.querySelector('.wpps-link-shortener');
		if (!wrap || wrap.getAttribute('data-wpps-ls-inited')) return;
		wrap.setAttribute('data-wpps-ls-inited', '1');
		var ajaxUrl = wrap.dataset.ajaxUrl || '';
		var nonce = wrap.dataset.nonce || '';
		var baseUrl = (wrap.dataset.baseUrl || '').replace(/\/?$/, '/');
		var currentPage = 1;
		var analyticsPage = 1;
		var analyticsLinkId = 0;
		var expiredLabel = '<?php echo esc_js( __( 'Expired', 'wp-powersuite' ) ); ?>';
		var activeLabel = '<?php echo esc_js( __( 'Active', 'wp-powersuite' ) ); ?>';
		var inactiveLabel = '<?php echo esc_js( __( 'Inactive', 'wp-powersuite' ) ); ?>';
		var bulkDeleteConfirm = '<?php echo esc_js( __( 'Delete selected short links?', 'wp-powersuite' ) ); ?>';

		function normalizeRedirectType(value) {
			var allowed = ['301', '302', '307', '308'];
			var normalized = String(parseInt(value, 10) || 301);
			return allowed.indexOf(normalized) !== -1 ? normalized : '301';
		}

		function switchTab(tabName) {
			wrap.querySelectorAll('.wpps-ls-tab-btn').forEach(function(btn) {
				var active = btn.getAttribute('data-tab') === tabName;
				btn.classList.toggle('is-active', active);
				btn.setAttribute('aria-selected', active ? 'true' : 'false');
			});
			wrap.querySelectorAll('.wpps-ls-tab-panel').forEach(function(panel) {
				var isTarget = panel.id === 'wpps-ls-panel-' + tabName;
				panel.classList.toggle('is-active', isTarget);
				if (isTarget) {
					panel.removeAttribute('hidden');
				} else {
					panel.setAttribute('hidden', '');
				}
			});
		}

		function resetAddForm() {
			document.getElementById('wpps-ls-form-title').textContent = '<?php echo esc_js( __( 'Add New Link', 'wp-powersuite' ) ); ?>';
			document.getElementById('wpps-ls-form').reset();
			document.getElementById('wpps-ls-id').value = '';
			document.getElementById('wpps-ls-active').checked = true;
			document.getElementById('wpps-ls-password_unchanged').value = '0';
			var rtEl = document.getElementById('wpps-ls-redirect_type');
			if (rtEl) rtEl.value = '301';
		}

		wrap.querySelectorAll('.wpps-ls-tab-btn').forEach(function(btn) {
			btn.addEventListener('click', function() {
				var tab = btn.getAttribute('data-tab');
				if (!tab) return;
				switchTab(tab);
			});
		});

		function request(action, data) {
			data = data || {};
			data.action = action;
			data.nonce = nonce;
			var body = new FormData();
			Object.keys(data).forEach(function(k) { body.append(k, data[k]); });
			return fetch(ajaxUrl, { method: 'POST', body: body }).then(function(r) { return r.json(); });
		}

		function refreshList(page) {
			currentPage = page || currentPage || 1;
			var searchEl = document.getElementById('wpps-ls-search');
			var search = searchEl ? searchEl.value : '';
			request('wpps_link_shortener_list', { search: search, page: currentPage, per_page: 50 }).then(function(res) {
				if (!res.success || !res.data) return;
				var stats = res.data.stats || {};
				var pagination = res.data.pagination || {};
				var statTotal = document.getElementById('wpps-ls-stat-total-links');
				var statClicks = document.getElementById('wpps-ls-stat-total-clicks');
				var statActive = document.getElementById('wpps-ls-stat-active');
				if (statTotal) statTotal.textContent = stats.total_links ?? 0;
				if (statClicks) statClicks.textContent = stats.total_clicks ?? 0;
				if (statActive) statActive.textContent = stats.active_links ?? 0;
				var paginationEl = document.getElementById('wpps-ls-pagination');
				var pageInfo = document.getElementById('wpps-ls-page-info');
				if (paginationEl && pageInfo) {
					var totalPages = pagination.total_pages || 1;
					pageInfo.textContent = (pagination.page || 1) + ' / ' + totalPages + ' (' + (pagination.total || 0) + ')';
					paginationEl.style.display = totalPages > 1 ? 'flex' : 'none';
					document.getElementById('wpps-ls-prev-page').disabled = (pagination.page || 1) <= 1;
					document.getElementById('wpps-ls-next-page').disabled = (pagination.page || 1) >= totalPages;
				}
				var tbody = document.getElementById('wpps-ls-tbody');
				if (!tbody) return;
				var links = res.data.links || [];
				function fmtDate(s) {
					if (!s) return '—';
					var d = new Date(s);
					return isNaN(d.getTime()) ? String(s) : d.toLocaleString();
				}
				function expAttr(link) {
					if (!link.expires_at) return '';
					return String(link.expires_at).replace(' ', 'T').substring(0, 16);
				}
				var rows = links.map(function(link) {
					var id = link.id || '';
					var shortCode = link.short_code || '';
					var dest = link.destination_url || '';
					var shortUrl = baseUrl + escapeHtml(shortCode);
					var created = fmtDate(link.created_at);
					var last = fmtDate(link.last_clicked_at);
					var expired = link.expires_at && new Date(link.expires_at).getTime() < Date.now();
					var active = (Number(link.active) === 1 || link.active === true) && !expired;
					var statusClass = expired ? 'expired' : (active ? 'active' : 'inactive');
					var statusLabel = expired ? expiredLabel : (active ? activeLabel : inactiveLabel);
					var destDisplay = dest.length > 50 ? dest.substring(0, 47) + '...' : dest;
					var expireRedirect = link.expire_redirect_url || '';
					var redirectType = normalizeRedirectType(link.redirect_type);
					return '<tr data-id="' + escapeHtml(String(id)) + '" data-destination-url="' + escapeHtml(dest) + '" data-short-code="' + escapeHtml(shortCode) + '" data-expires-at="' + escapeHtml(expAttr(link)) + '" data-expire-redirect-url="' + escapeHtml(expireRedirect) + '" data-redirect-type="' + escapeHtml(redirectType) + '" data-active="' + (active ? '1' : '0') + '">' +
						'<th class="check-column"><input type="checkbox" class="wpps-ls-row-cb" value="' + escapeHtml(String(id)) + '" /></th>' +
						'<td class="column-short-code"><code>' + escapeHtml(shortCode) + '</code></td>' +
						'<td class="column-destination"><a href="' + escapeHtml(dest) + '" target="_blank" rel="noopener">' + escapeHtml(destDisplay) + '</a></td>' +
						'<td class="num">' + (link.click_count || 0) + '</td>' +
						'<td class="column-created">' + escapeHtml(created) + '</td>' +
						'<td class="column-last-clicked">' + escapeHtml(last) + '</td>' +
						'<td class="column-status"><span class="wpps-ls-status-badge wpps-ls-status-' + statusClass + '">' + escapeHtml(statusLabel) + '</span></td>' +
						'<td class="column-actions"><span class="wpps-ls-row-actions"><button type="button" class="button-link wpps-ls-analytics wpps-ls-action-btn" data-id="' + escapeHtml(String(id)) + '" data-short-code="' + escapeHtml(shortCode) + '" title="<?php echo esc_js( __( 'View analytics', 'wp-powersuite' ) ); ?>" aria-label="<?php echo esc_js( __( 'View analytics', 'wp-powersuite' ) ); ?>"><span class="dashicons dashicons-chart-bar" aria-hidden="true"></span></button><button type="button" class="button-link wpps-ls-copy wpps-ls-action-btn" data-url="' + escapeHtml(shortUrl) + '" title="<?php echo esc_js( __( 'Copy link', 'wp-powersuite' ) ); ?>" aria-label="<?php echo esc_js( __( 'Copy link', 'wp-powersuite' ) ); ?>"><span class="dashicons dashicons-admin-links" aria-hidden="true"></span></button><button type="button" class="button-link wpps-ls-duplicate wpps-ls-action-btn" data-id="' + escapeHtml(String(id)) + '" title="<?php echo esc_js( __( 'Duplicate', 'wp-powersuite' ) ); ?>" aria-label="<?php echo esc_js( __( 'Duplicate', 'wp-powersuite' ) ); ?>"><span class="dashicons dashicons-admin-page" aria-hidden="true"></span></button><button type="button" class="button-link wpps-ls-edit wpps-ls-action-btn" data-id="' + escapeHtml(String(id)) + '" title="<?php echo esc_js( __( 'Edit', 'wp-powersuite' ) ); ?>" aria-label="<?php echo esc_js( __( 'Edit', 'wp-powersuite' ) ); ?>"><span class="dashicons dashicons-edit" aria-hidden="true"></span></button><button type="button" class="button-link wpps-ls-toggle-active wpps-ls-action-btn" data-id="' + escapeHtml(String(id)) + '" title="' + (active ? '<?php echo esc_js( __( 'Deactivate', 'wp-powersuite' ) ); ?>' : '<?php echo esc_js( __( 'Activate', 'wp-powersuite' ) ); ?>') + '" aria-label="' + (active ? '<?php echo esc_js( __( 'Deactivate', 'wp-powersuite' ) ); ?>' : '<?php echo esc_js( __( 'Activate', 'wp-powersuite' ) ); ?>') + '"><span class="dashicons ' + (active ? 'dashicons-visibility' : 'dashicons-hidden') + '" aria-hidden="true"></span></button><button type="button" class="button-link wpps-ls-delete wpps-ls-action-btn" data-id="' + escapeHtml(String(id)) + '" title="<?php echo esc_js( __( 'Delete', 'wp-powersuite' ) ); ?>" aria-label="<?php echo esc_js( __( 'Delete', 'wp-powersuite' ) ); ?>"><span class="dashicons dashicons-trash" aria-hidden="true"></span></button></span></td>' +
						'</tr>';
				});
				if (rows.length === 0) rows = ['<tr><td colspan="8" class="wpps-ls-empty-msg"><?php echo esc_js( __( 'No short links yet. Open the Add Link tab to create one.', 'wp-powersuite' ) ); ?></td></tr>'];
				tbody.innerHTML = rows.join('');
				bindRowEvents();
			});
		}

		function loadAnalytics(id, page) {
			analyticsLinkId = id;
			analyticsPage = page || 1;
			var modal = document.getElementById('wpps-ls-analytics-modal');
			var loading = document.getElementById('wpps-ls-analytics-loading');
			var content = document.getElementById('wpps-ls-analytics-content');
			var tbody = document.getElementById('wpps-ls-analytics-tbody');
			var empty = document.getElementById('wpps-ls-analytics-empty');
			modal.style.display = 'flex';
			loading.style.display = 'block';
			content.style.display = 'none';
			request('wpps_link_shortener_analytics', { id: id, page: analyticsPage, per_page: 50 }).then(function(res) {
				loading.style.display = 'none';
				content.style.display = 'block';
				if (!res.success || !res.data) {
					empty.style.display = 'block';
					empty.textContent = res.data && res.data.message ? res.data.message : '<?php echo esc_js( __( 'Failed to load analytics.', 'wp-powersuite' ) ); ?>';
					return;
				}
				var shortUrl = res.data.short_url || '';
				var analytics = res.data.analytics || [];
				var pagination = res.data.pagination || {};
				document.getElementById('wpps-ls-analytics-short-url').textContent = shortUrl;
				document.getElementById('wpps-ls-analytics-total').textContent = (pagination.total || analytics.length) + ' <?php echo esc_js( __( 'clicks', 'wp-powersuite' ) ); ?>';
				var exportAnalyticsBtn = document.getElementById('wpps-ls-analytics-export-btn');
				if (exportAnalyticsBtn) {
					exportAnalyticsBtn.style.display = (pagination.total || analytics.length) ? 'inline-block' : 'none';
				}
				empty.style.display = (pagination.total || analytics.length) ? 'none' : 'block';
				tbody.innerHTML = '';
				analytics.forEach(function(row) {
					var d = row.clicked_at ? new Date(row.clicked_at) : null;
					var dateStr = d && !isNaN(d.getTime()) ? d.toLocaleString() : (row.clicked_at || '—');
					var tr = document.createElement('tr');
					tr.innerHTML = '<td>' + escapeHtml(dateStr) + '</td><td>' + escapeHtml(row.ip_address || '—') + '</td><td>' + escapeHtml(row.referer ? (row.referer.length > 60 ? row.referer.substring(0, 57) + '...' : row.referer) : '—') + '</td><td class="user-agent-cell" title="' + escapeHtml(row.user_agent || '') + '">' + escapeHtml(row.user_agent ? (row.user_agent.length > 80 ? row.user_agent.substring(0, 77) + '...' : row.user_agent) : '—') + '</td>';
					tbody.appendChild(tr);
				});
				var paginationEl = document.getElementById('wpps-ls-analytics-pagination');
				var pageInfo = document.getElementById('wpps-ls-analytics-page-info');
				if (paginationEl && pageInfo) {
					var totalPages = pagination.total_pages || 1;
					pageInfo.textContent = (pagination.page || 1) + ' / ' + totalPages;
					paginationEl.style.display = totalPages > 1 ? 'flex' : 'none';
					document.getElementById('wpps-ls-analytics-prev').disabled = (pagination.page || 1) <= 1;
					document.getElementById('wpps-ls-analytics-next').disabled = (pagination.page || 1) >= totalPages;
				}
			});
		}

		function bindRowEvents() {
			var tbody = document.getElementById('wpps-ls-tbody');
			if (!tbody) return;
			tbody.querySelectorAll('.wpps-ls-analytics').forEach(function(btn) {
				btn.onclick = function() {
					var id = btn.getAttribute('data-id') || '';
					if (!id) return;
					loadAnalytics(id, 1);
				};
			});
			tbody.querySelectorAll('.wpps-ls-copy').forEach(function(btn) {
				btn.onclick = function() {
					var url = btn.getAttribute('data-url') || '';
					if (navigator.clipboard && navigator.clipboard.writeText) {
						navigator.clipboard.writeText(url).then(function() { alert('<?php echo esc_js( __( 'Link copied to clipboard.', 'wp-powersuite' ) ); ?>'); });
					} else {
						var inp = document.createElement('input');
						inp.value = url;
						document.body.appendChild(inp);
						inp.select();
						document.execCommand('copy');
						document.body.removeChild(inp);
						alert('<?php echo esc_js( __( 'Link copied to clipboard.', 'wp-powersuite' ) ); ?>');
					}
				};
			});
			tbody.querySelectorAll('.wpps-ls-edit').forEach(function(btn) {
				btn.onclick = function() {
					var id = btn.getAttribute('data-id') || '';
					var row = tbody.querySelector('tr[data-id="' + id.replace(/"/g, '\\"') + '"]');
					if (!row) return;
					document.getElementById('wpps-ls-form-title').textContent = '<?php echo esc_js( __( 'Edit Link', 'wp-powersuite' ) ); ?>';
					document.getElementById('wpps-ls-id').value = id;
					document.getElementById('wpps-ls-destination_url').value = row.getAttribute('data-destination-url') || '';
					document.getElementById('wpps-ls-short_code').value = row.getAttribute('data-short-code') || '';
					var rtEl = document.getElementById('wpps-ls-redirect_type');
					if (rtEl) rtEl.value = row.getAttribute('data-redirect-type') || '301';
					document.getElementById('wpps-ls-active').checked = row.getAttribute('data-active') === '1';
					document.getElementById('wpps-ls-expires_at').value = row.getAttribute('data-expires-at') || '';
					document.getElementById('wpps-ls-expire_redirect_url').value = row.getAttribute('data-expire-redirect-url') || '';
					document.getElementById('wpps-ls-password').value = '';
					document.getElementById('wpps-ls-password_unchanged').value = '1';
					switchTab('add');
				};
			});
			tbody.querySelectorAll('.wpps-ls-delete').forEach(function(btn) {
				btn.onclick = function() {
					if (!confirm('<?php echo esc_js( __( 'Delete this short link?', 'wp-powersuite' ) ); ?>')) return;
					var id = btn.getAttribute('data-id') || '';
					request('wpps_link_shortener_delete', { id: id }).then(function(res) {
						if (res.success) refreshList();
						else alert((res.data && res.data.message) || '<?php echo esc_js( __( 'Error.', 'wp-powersuite' ) ); ?>');
					});
				};
			});
			tbody.querySelectorAll('.wpps-ls-toggle-active').forEach(function(btn) {
				btn.onclick = function() {
					var id = btn.getAttribute('data-id') || '';
					if (!id) return;
					request('wpps_link_shortener_toggle', { id: id }).then(function(res) {
						if (res.success) refreshList();
						else alert((res.data && res.data.message) || '<?php echo esc_js( __( 'Failed to update.', 'wp-powersuite' ) ); ?>');
					});
				};
			});
			tbody.querySelectorAll('.wpps-ls-duplicate').forEach(function(btn) {
				btn.onclick = function() {
					var id = btn.getAttribute('data-id') || '';
					if (!id) return;
					request('wpps_link_shortener_duplicate', { id: id }).then(function(res) {
						if (res.success) refreshList();
						else alert((res.data && res.data.message) || '<?php echo esc_js( __( 'Failed to duplicate.', 'wp-powersuite' ) ); ?>');
					});
				};
			});
			updateBulkVisibility();
		}

		function updateBulkVisibility() {
			var checked = wrap.querySelectorAll('.wpps-ls-row-cb:checked');
			var bulkEl = document.getElementById('wpps-ls-bulk-actions');
			if (bulkEl) bulkEl.style.display = checked.length ? 'inline-block' : 'none';
		}

		document.getElementById('wpps-ls-add-btn').onclick = function() {
			resetAddForm();
			switchTab('add');
		};
		document.getElementById('wpps-ls-form-cancel').onclick = function() {
			resetAddForm();
			switchTab('links');
		};
		document.getElementById('wpps-ls-form').onsubmit = function(e) {
			e.preventDefault();
			var fd = new FormData(this);
			fd.set('nonce', nonce);
			fd.set('action', 'wpps_link_shortener_save');
			fd.set('active', document.getElementById('wpps-ls-active').checked ? '1' : '0');
			fd.set('password_unchanged', document.getElementById('wpps-ls-password_unchanged').value);
			var expires = document.getElementById('wpps-ls-expires_at').value;
			if (expires) fd.set('expires_at', expires);
			var expireRedirect = document.getElementById('wpps-ls-expire_redirect_url').value;
			if (expireRedirect) fd.set('expire_redirect_url', expireRedirect);
			fetch(ajaxUrl, { method: 'POST', body: fd }).then(function(r) { return r.json(); }).then(function(res) {
				if (res.success) {
					resetAddForm();
					switchTab('links');
					refreshList(1);
				} else {
					alert((res.data && res.data.message) || '<?php echo esc_js( __( 'Save failed.', 'wp-powersuite' ) ); ?>');
				}
			});
		};
		var selectAll = document.getElementById('wpps-ls-select-all');
		if (selectAll) selectAll.onchange = function() {
			wrap.querySelectorAll('.wpps-ls-row-cb').forEach(function(cb) { cb.checked = selectAll.checked; });
			updateBulkVisibility();
		};
		wrap.addEventListener('change', function(ev) {
			if (ev.target && ev.target.classList && ev.target.classList.contains('wpps-ls-row-cb')) updateBulkVisibility();
		});
		document.getElementById('wpps-ls-bulk-apply').onclick = function() {
			var action = document.getElementById('wpps-ls-bulk-select').value;
			if (!action) return;
			var ids = [];
			wrap.querySelectorAll('.wpps-ls-row-cb:checked').forEach(function(cb) { ids.push(cb.value); });
			if (!ids.length) return;
			if (action === 'delete' && !confirm(bulkDeleteConfirm)) return;
			var body = new FormData();
			body.append('action', 'wpps_link_shortener_bulk');
			body.append('nonce', nonce);
			body.append('bulk_action', action);
			ids.forEach(function(id) { body.append('ids[]', id); });
			fetch(ajaxUrl, { method: 'POST', body: body }).then(function(r) { return r.json(); }).then(function(res) {
				if (res.success) { refreshList(); if (selectAll) selectAll.checked = false; }
				else alert((res.data && res.data.message) || '<?php echo esc_js( __( 'Bulk action failed.', 'wp-powersuite' ) ); ?>');
			});
		};
		var searchBtn = document.getElementById('wpps-ls-search-btn');
		if (searchBtn) searchBtn.onclick = function() { currentPage = 1; refreshList(1); };
		var searchInput = document.getElementById('wpps-ls-search');
		if (searchInput) searchInput.onkeypress = function(e) { if (e.key === 'Enter') { e.preventDefault(); currentPage = 1; refreshList(1); } };
		var prevPageBtn = document.getElementById('wpps-ls-prev-page');
		var nextPageBtn = document.getElementById('wpps-ls-next-page');
		if (prevPageBtn) prevPageBtn.onclick = function() { if (currentPage > 1) refreshList(currentPage - 1); };
		if (nextPageBtn) nextPageBtn.onclick = function() { refreshList(currentPage + 1); };
		var analyticsPrev = document.getElementById('wpps-ls-analytics-prev');
		var analyticsNext = document.getElementById('wpps-ls-analytics-next');
		if (analyticsPrev) analyticsPrev.onclick = function() { if (analyticsPage > 1 && analyticsLinkId) loadAnalytics(analyticsLinkId, analyticsPage - 1); };
		if (analyticsNext) analyticsNext.onclick = function() { if (analyticsLinkId) loadAnalytics(analyticsLinkId, analyticsPage + 1); };
		var analyticsModal = document.getElementById('wpps-ls-analytics-modal');
		if (analyticsModal) analyticsModal.addEventListener('click', function(e) {
			if (e.target.classList.contains('wpps-ls-analytics-modal-backdrop') || e.target.closest('.wpps-ls-analytics-modal-close')) {
				analyticsModal.style.display = 'none';
			}
		});
		var exportBtn = document.getElementById('wpps-ls-export-btn');
		if (exportBtn) exportBtn.onclick = function(e) {
			e.preventDefault();
			var url = exportBtn.getAttribute('data-base-url') || '';
			var search = searchInput ? searchInput.value : '';
			if (search) url += '&search=' + encodeURIComponent(search);
			window.open(url, '_blank');
		};
		var exportAnalyticsBtn = document.getElementById('wpps-ls-export-analytics-btn');
		if (exportAnalyticsBtn) exportAnalyticsBtn.onclick = function(e) {
			e.preventDefault();
			window.open(exportAnalyticsBtn.getAttribute('data-base-url') || '', '_blank');
		};
		var analyticsExportBtn = document.getElementById('wpps-ls-analytics-export-btn');
		if (analyticsExportBtn) analyticsExportBtn.onclick = function(e) {
			e.preventDefault();
			if (!analyticsLinkId) return;
			var url = (analyticsExportBtn.getAttribute('data-base-url') || '') + '&id=' + encodeURIComponent(String(analyticsLinkId));
			window.open(url, '_blank');
		};
		var importBtn = document.getElementById('wpps-ls-import-btn');
		var importFile = document.getElementById('wpps-ls-import-file');
		if (importBtn && importFile) {
			importBtn.onclick = function() { importFile.click(); };
			importFile.onchange = function() {
				var file = importFile.files[0];
				if (!file) return;
				var reader = new FileReader();
				reader.onload = function(e) {
					var csv = e.target && e.target.result ? e.target.result : '';
					if (!csv) {
						alert('<?php echo esc_js( __( 'Could not read file.', 'wp-powersuite' ) ); ?>');
						return;
					}
					var body = new FormData();
					body.append('action', 'wpps_link_shortener_import');
					body.append('nonce', nonce);
					body.append('csv', csv);
					fetch(ajaxUrl, { method: 'POST', body: body }).then(function(r) { return r.json(); }).then(function(res) {
						importFile.value = '';
						if (res.success) {
							refreshList();
							var msg = (res.data && res.data.message) || '<?php echo esc_js( __( 'Import complete.', 'wp-powersuite' ) ); ?>';
							if (res.data && res.data.errors && res.data.errors.length) {
								msg += '\n' + res.data.errors.join('\n');
							}
							alert(msg);
						} else {
							alert((res.data && res.data.message) || '<?php echo esc_js( __( 'Import failed.', 'wp-powersuite' ) ); ?>');
						}
					});
				};
				reader.readAsText(file, 'UTF-8');
			};
		}

		bindRowEvents();
		switchTab('links');
	}

	document.addEventListener('wp-powersuite-modal-loaded', function(ev) {
		if (ev.detail && ev.detail.moduleId === 'link-shortener') initLinkShortener();
	});
	if (document.querySelector('.wpps-link-shortener') && document.getElementById('wp-powersuite-modal') && document.getElementById('wp-powersuite-modal').style.display !== 'none') {
		setTimeout(initLinkShortener, 100);
	}
})();
</script>

