<?php
/**
 * Subscription template file
 *
 * This file handles the subscription plans display and management for the Postomatic plugin.
 *
 * @package Postomatic
 */

?>
<!DOCTYPE html>
<html 
<?php
language_attributes();
?>
>
<head>
	<meta charset="<?php bloginfo( 'charset' ); ?>">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<?php wp_head(); ?>
	<style>
		@keyframes pulse {
			0% { transform: scale(1); }
			50% { transform: scale(1.05); }
			100% { transform: scale(1); }
		}

		@keyframes fadeInDown {
			from {
				opacity: 0;
				transform: translateY(-20px);
			}
			to {
				opacity: 1;
				transform: translateY(0);
			}
		}
	</style>
</head>
<body <?php body_class(); ?>>

<div id="app" class="wrap">

	<!-- Current Plan Box -->

	<div v-if="hasDiscount('pro-ultimate')" class="limited-time-offer"
		style="margin: 20px 20px 40px 0; background: linear-gradient(125deg, #ff6b00 0%, #ff9500 100%); color: #fff; border-radius: 12px; padding: 15px 25px; box-shadow: 0 10px 20px rgba(255,107,0,0.3); font-family: inherit; text-align: center; animation: pulse 2s infinite;">
		<div style="display: flex; align-items: center; justify-content: center; gap: 15px; flex-wrap: wrap;">
			<div style="display: flex; align-items: center; gap: 10px;">
				<span style="font-size: 1.5em;">🔥</span>
				<h3 style="margin: 0; font-size: 1.3em; font-weight: 700;">Special Offer: {{ getDiscountPercentage('pro-ultimate') }}% OFF Pro Ultimate
					Plan</h3>
			</div>
			<div style="background: rgba(255,255,255,0.2); padding: 8px 15px; border-radius: 8px; font-weight: 700; letter-spacing: 1px;">
				Limited Availability! <span id="countdown">Act Now</span>
			</div>
			<a href="#pro-ultimate-plan"
				style="background: white; color: #ff6b00; padding: 8px 20px; border-radius: 30px; text-decoration: none; font-weight: 700; transition: all 0.3s ease; white-space: nowrap;">
				Claim Discount Now
			</a>
		</div>
	</div>

	<div v-if="showNotice" class="notice notice-info is-dismissible postomatic-notice"
		style="margin: 20px 20px 40px 0; background: linear-gradient(125deg, #4f46e5 0%, #7c3aed 50%, #06b6d4 100%); color: #fff; border-radius: 12px; padding: 20px 25px; box-shadow: 0 10px 20px rgba(124,58,237,0.2); font-family: inherit;">
		<button type="button" class="notice-dismiss" style="color: rgba(255,255,255,0.8);" @click="showNotice = false">
			<span class="screen-reader-text">Dismiss this notice.</span>
		</button>
		<div class="notice-content" style="display: flex; align-items: center; justify-content: space-between;">
			<div class="notice-text" style="flex: 1;">
				<h2 style="margin: 0 0 8px; color: #fff; font-size: 1.4em;">{{ noticeTitle }}</h2>
				<p style="margin: 0; font-size: 1.1em; opacity: 0.9;">{{ noticeText }}</p>
			</div>
			<a :href="noticeBtnLink" class="button button-primary"
				style="background: rgba(255,255,255,0.15); border: 2px solid rgba(255,255,255,0.3); color: #fff; padding: 8px 20px; border-radius: 30px; text-decoration: none; font-weight: 600; margin-left: 20px; transition: all 0.2s ease; white-space: nowrap;">
				{{ noticeBtnText }}
			</a>
		</div>
	</div>

	<!-- VIP and Basic Overlays -->
	<div
			v-if="plan === 'starter'"
			v-show="showVipOverlay"
			id="vip-overlay"
			class="vip-overlay"
	>
		<button
				class="vip-close"
				aria-label="Close Starter banner"
				@click="hideVip"
		></button>

		<div class="vip-icon-container">
			<div class="vip-icon">🚀</div>
		</div>

		<h3 class="vip-title">Starter Member</h3>
		<div class="vip-subtitle">Limited Access</div>
		<p class="vip-message">
			Welcome to the Starter plan. You can use our core features and get help whenever you need it.
		</p>

		<div class="vip-features">
			<div>
				<span class="vip-feature-icon">🔑</span>
				<span>Core Features</span>
			</div>
			<div>
				<span class="vip-feature-icon">📧</span>
				<span>Email Support</span>
			</div>
			<div>
				<span class="vip-feature-icon">⭐</span>
				<span>Starter Badge</span>
			</div>
		</div>
		<div class="vip-badge">Starter Status Active</div>
	</div>


	<div v-if="currentPlanState.has_active_subscription" v-show="plan === 'pro-ultimate' && showVipOverlay"
		id="vip-overlay" class="vip-overlay">
		<button class="vip-close" aria-label="Close VIP banner" @click="hideVip"></button>
		<div class="vip-crown-container">
			<div class="vip-crown">👑</div>
		</div>
		<h3 class="vip-title">Pro Ultimate Member</h3>
		<div class="vip-subtitle">Premium Access Unlocked</div>
		<p class="vip-message">Welcome to the highest tier of membership. You have exclusive access to our complete
			suite of premium features and priority support.</p>
		<div class="vip-features">
			<div><span class="vip-feature-icon">⭐</span><span>Full Access</span></div>
			<div><span class="vip-feature-icon">🏆</span><span>Priority Support</span></div>
			<div><span class="vip-feature-icon">💎</span><span>Premium Features</span></div>
		</div>
		<div class="vip-badge">Ultimate Status Active</div>
	</div>

	<div v-if="currentPlanState.has_active_subscription" v-show="plan === 'basic' && showBasicOverlay"
		id="basic-overlay" class="vip-overlay">
		<button class="vip-close" aria-label="Close VIP banner" @click="hideBasic"></button>
		<div class="vip-crown-container" style="background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%);">
			<div class="vip-crown">⭐</div>
		</div>
		<h3 class="vip-title">Basic Member</h3>
		<div class="vip-subtitle">Basic Access Enabled</div>
		<p class="vip-message">You've unlocked professional features. Upgrade to Ultimate tier to access our complete
			suite of premium features and priority support.</p>
		<div class="vip-features">
			<div><span class="vip-feature-icon">✓</span><span>Advanced Features</span></div>
			<div><span class="vip-feature-icon">✓</span><span>Professional Support</span></div>
			<div><span class="vip-feature-icon">↑</span><span>Upgrade Available</span></div>
		</div>
		<div class="vip-badge" style="background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%);">Basic Status
			Active
		</div>
	</div>

	<!-- Loading Overlay -->
	<div id="loading-overlay" v-show="loading" class="loading-active">
		<div class="loading-content">
			<div class="loading-spinner"></div>
		</div>
	</div>

	<!-- Main Content -->
	<div class="postomatic-logo"
		style="text-align: center; padding: 4rem 0; background: linear-gradient(125deg, #4f46e5 0%, #7c3aed 50%, #06b6d4 100%); margin: -20px -20px 30px -20px; border-radius: 60px; box-shadow: 0 20px 40px rgba(124,58,237,0.3); position: relative; overflow: hidden;">
		<!-- Subscription Info Section -->
		<div v-if="true"
			class="subscription-info-section">
			<div class="subscription-info-details">
				<h3>Your Subscription</h3>
				<div style="display: flex; flex-wrap: wrap; gap: 20px;">
					<div style="min-width: 200px;">
						<p>Active Plan:
							<span>
								{{(currentInitialData.plan_slug === 'free' ? 'Free' : currentInitialData.plan ) }}
							</span>
						</p>
						<p>Subscription Ends: <span>{{  (currentInitialData.plan_slug === 'free' || !currentInitialData.has_active_subscription) ? 'N/A': currentInitialData.ends_date}}</span>
						</p>
						<p v-if="currentInitialData.auto_renew === false" class="warning-text">
							After subscription expire date you will not be charged and your plan will deactivate
						</p>
						<p v-else-if="currentInitialData.auto_renew === true" class="success-text">
							Renew is activated and you do not need to do anything
						</p>
					</div>
					<div style="min-width: 200px;">
						<p>Days Remaining: <span>{{ currentInitialData.plan_slug === 'free' ? 'N/A' : remainingDays }}</span>
						</p>
						<p>Status: <span>{{ currentPlanState.status || (plan === 'starter' ? 'Active' : 'Inactive') }}</span></p>
					</div>
					<div style="min-width: 200px;">
						<p>Available Credits: <span>{{ currentInitialData.credit || 0 }}</span>
						</p>
					</div>
				</div>
			</div>
			<div class="subscription-actions" v-if="currentInitialData.manage_subscription_url !== null">
				<a href="#" @click.prevent="manageSubscription" class="manage-subscription-btn">
					<span>{{ currentInitialData.auto_renew === false ? 'Reactivate Plan' : 'Manage Subscription' }}</span>
					<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
						stroke-linecap="round" stroke-linejoin="round">
						<path d="M9 18l6-6-6-6"></path>
					</svg>
				</a>
				<a href="#" @click.prevent="cancelSubscription"
					v-if="currentInitialData.auto_renew !== false"
					class="cancel-subscription-btn">
					Cancel Subscription
				</a>
			</div>
		</div>

		<div class="wp-header-wrapper">
			<div class="wp-plugin-name"
				style="font-size: 1.2em; color: #fff; margin-bottom: 1rem; letter-spacing: 2px; font-weight: 600; text-transform: uppercase; background: rgba(255,255,255,0.1); display: inline-block; padding: 0.5rem 1.5rem; border-radius: 30px;">
				Postomatic
			</div>
			<h1 class="wp-heading-inline" style="color: #fff;">Subscription Plans</h1>
			<p class="wp-subtitle" style="color: rgba(255,255,255,0.9);">Join thousands of creators with flexible
				subscription access to AI-powered content automation</p>
		</div>
		<div class="subscription-container">
			<div v-for="key in ['starter','basic','pro-ultimate']" :key="key" :class="['plan-card', key + '-plan']"
				:id="key === 'pro-ultimate' ? 'pro-ultimate-plan' : ''"
				:style="key==='pro-ultimate'?{'transform':'scale(1.05)','boxShadow':'0 0 40px rgba(255,107,0,0.4)','border':'2px solid #ff6b00','position':'relative','zIndex':'2','background':'linear-gradient(to bottom, #ffffff, #fff8f2)'}:{}">
				<div v-if="key==='pro-ultimate' && hasDiscount(key)" class="best-value-badge"
					style="background: linear-gradient(135deg, #ff6b00 0%, #ff9500 100%); padding: 8px 20px; font-size: 1.1em; font-weight: 700; text-shadow: 0 1px 2px rgba(0,0,0,0.2); animation: pulse 1.5s infinite;">
					⭐ BEST VALUE OFFER ⭐
				</div>
				<h2 :id="key + '-plan-title'">{{ plans[key] && plans[key].title || '***' }}</h2>
				<div :class="['lifetime-badge', key==='pro-ultimate'? '':'']">
					{{ plans[key] && plans[key].slug === 'starter' ? 'Starter Plan' : key === 'basic' ? 'Basic Subscription' : 'Premium Subscription Plan'}}
				</div>
				<div class="price" :id="key + '-plan-price'">
					<span v-if="hasDiscount(key)" class="amount">
						<span style="text-decoration: line-through; color: #999; margin-right: 5px;">{{ getOriginalPrice(key) }}</span>
						<span class="discount-price"
								style="color: #ff6b00; font-weight: bold;">{{ getDiscountedPrice(key) }}</span>
						<small class="per-month">/Month</small>
						<span v-if="getDiscountPercentage(key)" 
								style="background-color: #ff6b00; color: white; padding: 2px 6px; border-radius: 4px; font-size: 0.8em; margin-left: 5px;">
							-{{ getDiscountPercentage(key) }}%
						</span>
					</span>
					<span v-else
							class="amount">{{ plans[key] && plans[key].price ? `$${plans[key].price}` : '$' }}<small class="per-month">/Month</small></span>
					<div v-if="hasDiscount(key)" style="font-size: 0.60em; color: #ff6b00; margin-top: 5px; padding: 3px 6px; background-color: #fff0e6; border-radius: 4px; font-weight: 500; display: inline-block; border-left: 2px solid #ff6b00; animation: pulse 2s infinite;">You'll be charged the discounted rate each month until you cancel</div>
				</div>

				<ul>
						<span :class="plans[key] && plans[key].slug==='pro-ultimate'?'feature-plus':'feature-plus'">+</span>
						<span :id="(plans[key] && plans[key].slug || key) + '_plan_initial_credit'">{{ plans[key] && plans[key].initial_credit || 0 }} Credits Will Reset Monthly to Your Balance</span>
					</li>
					<li v-if="plans[key] && plans[key].features"
						v-for="feat in plans[key] && plans[key].features ? plans[key].features : []" :key="feat"><span
								class="feature-check">✓</span> {{ feat }}
					</li>
					<li v-if="plans[key] && plans[key].bonus_percent"><span class="feature-check">✓</span> <span
								class="percent-badge"><span
									:id="(plans[key] && plans[key].slug || key) + '_plan_bonus_percent'">{{ plans[key] && plans[key].bonus_percent || 0 }}</span>%</span><span
								class="bonus-text">Bonus Credit on Every Credit Purchase</span></li>
				</ul>
				<a v-if="shouldShowSubscribeBtn(key) && plans[key] && plans[key].url"
					:href="plans[key].url"
					:id="key + '-plan-link'"
					:target="shouldDisableSubscribeBtn(key) ? '_self' : (key!=='starter'?'_blank':'_self')"
					:class="['select-plan-button', {'disabled': shouldDisableSubscribeBtn(key)}]"
					:title="shouldDisableSubscribeBtn(key) ? 'Please use the Manage Subscription option to manage your current subscription' : ''"
					:style="[
					key==='pro-ultimate'?{'background':'linear-gradient(135deg, #ff6b00 0%, #ff9500 100%)','transform':'scale(1.1)','boxShadow':'0 10px 20px rgba(255,107,0,0.4)','animation':'pulse 1.5s infinite','fontSize':'1.2em','fontWeight':'700','padding':'22px 32px','letterSpacing':'0.5px'}:{},
					shouldDisableSubscribeBtn(key) ? {'opacity':'0.6','cursor':'not-allowed','pointer-events':'none'} : {}
					]">
					<span class="button-text">{{ key === 'starter' ? 'Get Started Now' : key === 'basic' ? 'Upgrade to Basic' : 'Get Ultimate Access' }}</span>
					<span class="button-icon">{{ key === 'starter' ? '→' : '⚡' }}</span>
				</a>

				<p v-if="key==='starter'" class="plan-footnote"
					style="color: #1e40af; font-size: 0.85em; margin-top: 15px; font-weight: 500; text-align: center; text-transform: uppercase; letter-spacing: 0.5px; background: linear-gradient(to right, #f0f9ff, #dbeafe); padding: 10px 20px; border-radius: 6px; boxShadow: 0 1px 2px rgba(0,0,0,0.05);">
					Monthly Subscription • Cancel Anytime • No Hidden Fees</p>
				<p v-if="key==='basic'" class="plan-footnote"
					style="color: #1e40af; font-size: 0.85em; margin-top: 15px; font-weight: 500; text-align: center; text-transform: uppercase; letter-spacing: 0.5px; background: linear-gradient(to right, #f0f9ff, #dbeafe); padding: 10px 20px; border-radius: 6px; boxShadow: 0 1px 2px rgba(0,0,0,0.05);">
					Monthly Subscription • Cancel Anytime • No Hidden Fees</p>
				<p v-if="key==='pro-ultimate'" class="plan-footnote"
					style="color: #1e40af; font-size: 0.85em; margin-top: 15px; font-weight: 500; text-align: center; text-transform: uppercase; letter-spacing: 0.5px; background: linear-gradient(to right, #fff0e6, #ffe0cc); padding: 10px 20px; border-radius: 6px; boxShadow: 0 1px 2px rgba(0,0,0,0.05);">
					Monthly Subscription • Cancel Anytime • No Hidden Fees</p>
				<p v-if="key==='pro-ultimate' && hasDiscount(key)"
					style="color: #ff6b00; font-size: 0.9em; margin-top: 10px; font-weight: 700; text-align: center; animation: pulse 2s infinite;">
					🔥 Limited Time Offer - Save {{ getDiscountPercentage(key) }}% Today! 🔥</p>
			</div>
		</div>

		<section class="trust-section">
			<h2 style="text-align: center; color: #fff; font-size: 2em; margin-bottom: 30px; text-shadow: 0 2px 4px rgba(0,0,0,0.1);">
				Why Choose Postomatic?</h2>
			<div class="trust-grid"
				style="display: grid; grid-template-columns: repeat(4, 1fr); gap: 20px; max-width: 1200px; margin: 40px auto 20px; padding: 0 20px;">
				<div v-for="item in trustItems" :key="item.title" class="trust-item"
					style="background: rgba(255,255,255,0.15); padding: 30px; border-radius: 16px; text-align: center; transition: all 0.3s ease; box-shadow: 0 4px 20px rgba(0,0,0,0.1); backdrop-filter: blur(5px);">
					<div class="trust-icon" style="margin-bottom: 20px; transform: scale(1.2);"
						v-html="item.icon"></div>
					<div class="trust-content" style="color: #fff;">
						<h4 style="font-size: 1.3em; margin: 0 0 10px; font-weight: 700;">{{ item.title }}</h4>
						<p style="opacity: 0.9; margin: 0 0 15px; font-size: 1.05em;">{{ item.text }}</p>
						<p v-if="item.link && item.link.url" class="trust-link"><a :href="item.link.url" target="_blank" rel="noopener"
																	style="color: #fff; font-size: 0.95em; text-decoration: none; opacity: 0.9; font-weight: 600; display: inline-flex; align-items: center; gap: 5px;">{{ item.link.text
								}}
								<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor"
									stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
									<path d="M5 12h14M12 5l7 7-7 7"/>
								</svg>
							</a></p>
					</div>
				</div>
			</div>
			<div style="text-align: center; margin-top: 40px;">
				<p style="color: #fff; font-size: 1.2em; max-width: 800px; margin: 0 auto; opacity: 0.9;">Join thousands
					of content creators who trust Postomatic for their AI-powered content needs.</p>
			</div>
		</section>

	</div>

</div>

<script>
	const {createApp} = Vue;
	createApp({
		data() {
			return {
				postomatic_api: {
					plan_active: "<?php echo esc_url( admin_url( 'admin-ajax.php' ) ); ?>",
					pricing_plans: "<?php echo esc_url( admin_url( 'admin-ajax.php' ) ); ?>",
					credit_url: "<?php echo esc_url( admin_url( 'admin-ajax.php' ) ); ?>",
					api_key: "<?php echo esc_attr( Postomatic\Utils::get_api_service_key() ); ?>",
					site_url: "<?php echo esc_js( get_site_url() ); ?>",
					admin_nonce: "<?php echo esc_js( wp_create_nonce( 'postomatic_admin_nonce' ) ); ?>",
				},
				remainingDays: 0,
				currentPlanState: {},
				currentInitialData: {},
				plans: {},
				plan: 'starter',
				noticeTitle: '',
				noticeText: '',
				noticeBtnText: '',
				noticeBtnLink: '#',
				showNotice: false,
				loading: true,
				showVipOverlay: true,
				showBasicOverlay: true,
				trustItems: [
					{
						icon: `<svg width="48" height="48" viewBox="0 0 24 24" fill="none"><path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0 1.1.9-2 2-2z" fill="#6772E5"/><path d="M12 15V9m-3 3h6" stroke="#fff" stroke-width="2" stroke-linecap="round"/></svg>`,
						title: '<?php echo esc_html__( 'Secure Payments', 'postomatic' ); ?>',
						text: '<?php echo esc_html__( "Powered by Stripe's trusted platform", 'postomatic' ); ?>',
						link: {
							url: 'https://stripe.com/customers',
							text: '<?php echo esc_html__( 'Learn more about our secure payment system', 'postomatic' ); ?>'
						}
					},
					{
						icon: `<svg width="48" height="48" viewBox="0 0 24 24" fill="none"><path d="M12 2L4 6v6c0 5.52 3.44 10.73 8 12.6 4.56-1.87 8-7.08 8-12.6V6l-8-4z" fill="#24B47E"/><path d="M16 9l-5.5 5.5L8 12" stroke="#fff" stroke-width="2" stroke-linecap="round"/></svg>`,
						title: '<?php echo esc_html__( 'Enterprise-Grade Security', 'postomatic' ); ?>',
						text: '<?php echo esc_html__( 'Your data is protected with 256-bit SSL encryption', 'postomatic' ); ?>'
					},
					{
						icon: `<svg width="48" height="48" viewBox="0 0 24 24" fill="none"><path d="M13 2L3 14h9l-1 8L21 10h-9l1-8z" fill="#F5BE58"/></svg>`,
						title: '<?php echo esc_html__( 'Instant Access', 'postomatic' ); ?>',
						text: '<?php echo esc_html__( 'Start creating content immediately after subscribing', 'postomatic' ); ?>'
					},
					{
						icon: `<svg width="48" height="48" viewBox="0 0 24 24" fill="none"><path d="M12 2c5.52 0 10 4.48 10 10s-4.48 10-10 10S2 17.52 2 12 6.48 2 12 2z" fill="#FF6B00"/><path d="M8 14s1.5 2 4 2 4-2 4-2" stroke="#fff" stroke-width="2" stroke-linecap="round"/><circle cx="16" cy="9" r="1" fill="#fff"/><circle cx="8" cy="9" r="1" fill="#fff"/></svg>`,
						title: '<?php echo esc_html__( 'Trusted by Thousands', 'postomatic' ); ?>',
						text: '<?php echo esc_html__( 'Join over 10,000+ satisfied content creators', 'postomatic' ); ?>'
					}
				]
			}
		},
		methods: {
			showNotification(message, type = 'info') {
				// Map notification type to SweetAlert icon
				const iconMap = {
					'info': 'info',
					'success': 'success',
					'error': 'error',
					'warning': 'warning'
				};

				// Configure SweetAlert based on notification type
				Swal.fire({
					icon: iconMap[type] || 'info',
					title: type.charAt(0).toUpperCase() + type.slice(1),
					text: message,
					confirmButtonText: 'OK',
					customClass: {
						popup: 'shadow-lg rounded-lg border border-gray-300',
						title: 'text-lg font-medium text-gray-800',
						htmlContainer: 'text-gray-700'
					}
				});
			},
			hideVip() {
				this.showVipOverlay = false;
				; /* keep */
			},
			hideBasic() {
				this.showBasicOverlay = false; /* keep */
			},
			hasDiscount(key) {
				if (!this.currentInitialData.plans_discounts || !this.plans[key]) {
					return false;
				}

				const planSlug = this.plans[key].slug;
				return this.currentInitialData.plans_discounts.some(discount => discount.slug === planSlug);
			},
			getDiscountPercentage(key) {
				if (!this.hasDiscount(key)) {
					return null;
				}

				const planSlug = this.plans[key].slug;
				const discount = this.currentInitialData.plans_discounts.find(d => d.slug === planSlug);
				return discount ? discount.discount : null;
			},
			getOriginalPrice(key) {
				if (!this.hasDiscount(key)) {
					return this.plans[key] && this.plans[key].price ? `$${this.plans[key].price}` : '$';
				}

				const planSlug = this.plans[key].slug;
				const discount = this.currentInitialData.plans_discounts.find(d => d.slug === planSlug);
				return discount ? `$${discount.original_price}` : (this.plans[key].price ? `$${this.plans[key].price}` : '$');
			},
			getDiscountedPrice(key) {
				if (!this.hasDiscount(key)) {
					return this.plans[key] && this.plans[key].price ? `$${this.plans[key].price}` : '$';
				}

				const planSlug = this.plans[key].slug;
				const discount = this.currentInitialData.plans_discounts.find(d => d.slug === planSlug);
				return discount ? `$${discount.discounted_price}` : (this.plans[key].price ? `$${this.plans[key].price}` : '$');
			},
			shouldDisableSubscribeBtn(key) {
				// If user has never had an active plan, all buttons are enabled
				if (!this.currentInitialData.has_any_active_plan_ever) {
					return false;
				}

				// only disable when the user still has days left
				if (this.remainingDays > 0) {
					if (this.plan === 'pro-ultimate' && (key === 'starter' || key === 'basic' || key === 'pro-ultimate')) {
						return true;
					}

					if (this.plan === 'basic' && (key === 'starter' || key === 'basic')) {
						return true;
					}

					if (this.plan === 'starter' && (key === 'starter')) {
						return true;
					}
				}
				return false;
			},
			shouldShowSubscribeBtn(key) {
				// Always show buttons, they'll be disabled when needed
				return true;
			},
			manageSubscription() {
				window.open(
					this.currentInitialData.manage_subscription_url,
					'subscription'
				);            },
			cancelSubscription() {
				// For now, just show a confirmation dialog
				if (confirm('Are you sure you want to cancel your subscription?')) {
					window.open(
						this.currentInitialData.manage_subscription_url,
						'subscription'
					);                }
			}
		},
		async mounted() {

			// Fetch current plan
			try {
				const formData = new FormData();
				formData.append('action', 'postomatic_get_active_plan');
				formData.append('nonce', this.postomatic_api.admin_nonce);

				const res = await fetch(this.postomatic_api.plan_active, {
					method: 'POST',
					body: formData
				});

				if (!res.ok) {
					if (res.status === 401) {
						// Redirect to key-renew.php with refresh parameter
						window.location.href = `?page=postomatic&key=refresh&_wpnonce=${this.postomatic_api.admin_nonce}`;
						return;
					}
					throw new Error('Network response was not ok');
				}

				const response = await res.json();

				if (response.success) {
					const data = response.data;
					this.plan = data.slug;
					this.currentPlanState = {...data};
				} else {
					console.error('Error in API response:', response.data);
				}
			} catch (error) {
				console.error('Error fetching plan data:', error);
			}

			// Fetch notice / credit data
			try {
				const formData = new FormData();
				formData.append('action', 'postomatic_get_credits');
				formData.append('nonce', this.postomatic_api.admin_nonce);

				const cred = await fetch(this.postomatic_api.credit_url, {
					method: 'POST',
					body: formData
				});

				if (!cred.ok) {
					if (cred.status === 401) {
						// Redirect to key-renew.php with refresh parameter
						window.location.href = `?page=postomatic&key=refresh&_wpnonce=${this.postomatic_api.admin_nonce}`;
						return;
					}
					throw new Error('Network response was not ok');
				}

				const response = await cred.json();

				if (response.success) {
					const userCreditData = response.data;
					this.currentInitialData = userCreditData;
					this.remainingDays = userCreditData.remaining_days;
					this.noticeTitle = userCreditData.important_notice_title;
					this.noticeText = userCreditData.important_notice_text;
					this.noticeBtnText = userCreditData.important_notice_btn_text;
					this.noticeBtnLink = userCreditData.important_notice_btn_link;
					this.showNotice = userCreditData.important_notice_btn_visible;
				} else {
					console.error('Error in API response:', response.data);
				}
			} catch (error) {
				console.error('Error fetching credit data:', error);
			}

			// Fetch pricing plans
			try {
				const formData = new FormData();
				formData.append('action', 'postomatic_get_pricing_plans');
				formData.append('nonce', this.postomatic_api.admin_nonce);

				const resp = await fetch(this.postomatic_api.pricing_plans, {
					method: 'POST',
					body: formData
				});

				if (!resp.ok) {
					if (resp.status === 401) {
						// Redirect to key-renew.php with refresh parameter
						window.location.href = `?page=postomatic&key=refresh&_wpnonce=${this.postomatic_api.admin_nonce}`;
						return;
					}
					throw new Error('Network response was not ok');
				}

				const response = await resp.json();

				if (response.success) {
					const plansData = response.data;
					Object.keys(plansData).forEach(key => {
						let plan = plansData[key];
						if (plan.url) {
							let url = plan.url;

							const fullUrl = window.location.href;

							url = url.replace('%blog_url%', btoa(this.postomatic_api.site_url));
							url = url.replace('%plan_id%', plan.slug);
							plan.url = url + "?refer=" + fullUrl;
						}
					});
					this.plans = plansData;
				} else {
					console.error('Error in API response:', response.data);
				}
			} catch (error) {
				console.error('Error fetching pricing plans:', error);
			}

			// Calculate subscription end date after all data is fetched
			if (this.remainingDays > 0) {
				const endDate = new Date();
				endDate.setDate(endDate.getDate() + this.remainingDays);
				const formattedEndDate = endDate.toLocaleDateString('en-US', {
					year: 'numeric',
					month: 'long',
					day: 'numeric',
					hour: '2-digit',
					minute: '2-digit'
				});

				this.currentPlanState = {
					...this.currentPlanState,
					end_date: formattedEndDate,
					status: 'Active'
				};
			}

			this.loading = false;

			// Handle URL result param
			const params = new URLSearchParams(window.location.search);
			if (params.get('result') === 'success') {
				setTimeout(() => this.showNotification('Your subscription plan has been successfully activated.', 'success'), 600);
			} else if (params.get('result') === 'failed') {
				setTimeout(() => this.showNotification('There is an issue with the Payment system. Please try again later.', 'error'), 600);
			}

			// No countdown timer needed anymore - we're using a static message
			// Add a subtle animation to the "Act Now" text to draw attention
			function pulseActNow() {
				const countdownEl = document.getElementById('countdown');
				if (!countdownEl) return;

				// Add a subtle pulse animation to the text
				countdownEl.style.animation = 'pulse 2s infinite';
			}

			// Initialize the pulse animation when the page loads
			setTimeout(pulseActNow, 1000);
		}
	}).mount('#app');
</script>

<?php wp_footer(); ?>
</body>
</html>
