<?php

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

class Sabriel_Module_Prezzi extends Sabriel_Module {

	/* ⚠ La pagina del PRODOTTO, non la home: e' il link da cui parte chi ha
	   scaricato la gratuita e vuole vedere l'edizione a pagamento. */
	const URL_SITO             = 'https://sabrielagency.com/sabriel-ai/';
	const URL_CHECKOUT_PRO     = 'https://checkout.freemius.com/product/34648/plan/56982/licenses/1/';
	const URL_CHECKOUT_STUDIO  = 'https://checkout.freemius.com/product/34648/plan/60238/licenses/5/';
	const URL_CHECKOUT_AGENZIA = 'https://checkout.freemius.com/product/34648/plan/56983/licenses/20/';

	const PREZZI = [
		'pro'     => [ 'mensile' => '$19', 'annuale' => '$149', 'lifetime' => '$399',   'siti' => 1,  'sconto' => 35, 'ripaga' => 32 ],
		'studio'  => [ 'mensile' => '$39', 'annuale' => '$299', 'lifetime' => '$749',   'siti' => 5,  'sconto' => 36, 'ripaga' => 30 ],
		'agenzia' => [ 'mensile' => '$79', 'annuale' => '$599', 'lifetime' => '$1,490', 'siti' => 20, 'sconto' => 37, 'ripaga' => 30 ],
	];

	public function get_id() {
		return 'prezzi';
	}

	public function register_hooks() {
		add_action( 'admin_menu', [ $this, 'add_submenu' ], 40 );
	}

	public function add_submenu() {

		add_submenu_page(
			'sabriel-ai',
			__( 'Complete edition', 'sabriel-ai' ),
			'<span class="dashicons dashicons-star-filled" style="font-size:15px;width:15px;height:15px;vertical-align:-3px;color:#f0a020"></span> ' . __( 'Complete edition', 'sabriel-ai' ),
			'manage_options',
			'sabriel-ai-prezzi',
			[ $this, 'render_page' ]
		);
	}

	private static function cose_incluse() {
		return [
			[
				__( 'The AI engine, and who operates it', 'sabriel-ai' ),
				__( 'You connect your own account with Google, OpenAI or Anthropic. There is no intermediary service and no separate subscription: your site communicates directly with the provider you choose, and that provider bills you directly.', 'sabriel-ai' ),
				[
					__( 'AI assistant powered by your own key: Google Gemini, OpenAI or Anthropic Claude, interchangeable at any time', 'sabriel-ai' ),
					__( 'No additional account, licence or third-party service required', 'sabriel-ai' ),
					__( 'API keys stored encrypted and transmitted only to the provider you selected', 'sabriel-ai' ),
					__( 'Sixteen models with their cost per million tokens shown upfront; the recommended model is the least expensive, because we earn nothing on your usage', 'sabriel-ai' ),
					__( 'The assistant replies in the language the visitor writes in', 'sabriel-ai' ),
					__( 'Panel and assistant available in nine languages, configurable independently', 'sabriel-ai' ),
				],
			],
			[
				__( 'What the assistant is allowed to say', 'sabriel-ai' ),
				__( 'An assistant that improvises a price or a page you do not offer costs you the enquiry. This one answers only from the material you supply: your price list, your pages, your tone of voice.', 'sabriel-ai' ),
				[
					__( 'Your price list, one line per service: the assistant quotes from it instead of improvising', 'sabriel-ai' ),
					__( 'Links to your own pages, cited only where they are relevant to the question', 'sabriel-ai' ),
					__( 'Behaviour and tone of voice defined by you, in your own wording', 'sabriel-ai' ),
				],
			],
			[
				__( 'What visitors are able to send', 'sabriel-ai' ),
				__( 'Conversations are not limited to typed text. A customer can photograph a component, attach a document or dictate a message: speech is transcribed on their own device, so no audio is ever transmitted.', 'sabriel-ai' ),
				[
					__( 'Reads images attached by visitors, and PDF documents on the providers that support them', 'sabriel-ai' ),
					__( 'Voice messages transcribed inside the visitor\'s browser: the provider receives text only, the audio never leaves the device', 'sabriel-ai' ),
				],
			],
			[
				__( 'Escalation to a human', 'sabriel-ai' ),
				__( 'The assistant recognises the limits of what it can resolve. At that point it hands the conversation to you on WhatsApp, by email or by phone, with a summary already prepared.', 'sabriel-ai' ),
				[
					__( 'WhatsApp opens with the message pre-written: who the visitor is, what they need and what was discussed. Nothing to repeat for them, no transcript to read for you', 'sabriel-ai' ),
					__( 'A contact form that delivers the enquiry straight to your inbox', 'sabriel-ai' ),
					__( 'A conversation summary sent by email to both the visitor and you', 'sabriel-ai' ),
				],
			],
			[
				__( 'How the chat presents itself', 'sabriel-ai' ),
				__( 'The widget carries your logo, your name and your colours. A visitor returning from the same device resumes the conversation where it ended.', 'sabriel-ai' ),
				[
					__( 'Logo, assistant name and the widget\'s primary colours, with a live preview', 'sabriel-ai' ),
					__( 'Returning visitors are recognised on the same device and continue from where they left off', 'sabriel-ai' ),
				],
			],
			[
				__( 'Cost control and safeguards', 'sabriel-ai' ),
				__( 'AI usage is billed to you, so the plugin limits what a single visitor can consume. If no valid key is configured the widget stays hidden, rather than failing in front of your customers.', 'sabriel-ai' ),
				[
					__( 'Abuse protection: daily message cap per visitor, summary cap per address, disposable email addresses rejected', 'sabriel-ai' ),
					__( 'With no working key the widget does not render at all: no broken chat on your site', 'sabriel-ai' ),
				],
			],
			[
				__( 'Monitoring and support', 'sabriel-ai' ),
				__( 'Traffic figures for the widget, a diagnostic page that reports exactly what is missing, and documentation written for a first-time setup.', 'sabriel-ai' ),
				[
					__( 'Widget traffic statistics, stored entirely on your own site', 'sabriel-ai' ),
					__( 'A system status page listing what is incomplete and where to correct it', 'sabriel-ai' ),
					__( 'Complete documentation inside the panel, exportable as a standalone HTML file', 'sabriel-ai' ),
				],
			],
		];
	}

	private static function cose_in_piu() {
		return [
			[
				__( 'Client management dashboard', 'sabriel-ai' ),
				__( 'The free edition includes a dashboard with the widget\'s traffic figures. The complete edition turns it into the operational centre of the plugin: appointments to confirm, reschedule or cancel; every quote issued, with amount and current status; the results of each site audit; full analytics on conversations, qualified leads, quotes and bookings; and the consent register, retained with dates as evidence. Your data stays exportable at any time in a file that opens in Excel.', 'sabriel-ai' ),
			],
			[
				__( 'PDF quotes', 'sabriel-ai' ),
				__( 'The assistant issues a formal quotation during the conversation: priced from your own list, VAT applied as you configured it, your terms appended, and a numbered PDF carrying your logo with space for a signature. The figure is always calculated from your list, so a visitor cannot dictate a price and have it issued. Files are stored in a protected directory, outside the site\'s public media library. For businesses that quote work rather than sell from a cart.', 'sabriel-ai' ),
			],
			[
				__( 'Appointment booking', 'sabriel-ai' ),
				__( 'A booking calendar inside the chat, aware of your opening hours, the capacity of each slot and the buffer between appointments. Visitors can also book conversationally: the assistant checks the day, the available hours and existing reservations before confirming, and never reports a booking it did not complete. Rescheduling and cancellation run through a signed link sent by email, so nobody can alter another person\'s appointment. For appointment-based businesses: practices, clinics, salons, consultants and workshops.', 'sabriel-ai' ),
			],
			[
				__( 'Lead scoring and analytics', 'sabriel-ai' ),
				__( 'Every conversation is reviewed by the model and classified as hot, warm or cold, with a one-line rationale. The classification is recalculated whenever the contact writes again, so an accidentally closed chat does not leave a lead marked cold. Follow-ups then go out on their own: day three and seven for hot leads, day six and fourteen for warm ones, stopping automatically if a booking or a quote occurs in the meantime. Six per contact over their entire lifetime, never more, with one-click unsubscribe. For businesses receiving more enquiries than they can follow up by hand.', 'sabriel-ai' ),
			],
			[
				__( 'Free website audit', 'sabriel-ai' ),
				__( 'Built for businesses that sell websites: agencies, freelance designers and SEO consultants. When a visitor already has a site the usual pitch does not land, so the assistant requests the address, retrieves the page, runs up to twenty-five technical checks across security, search visibility, speed and trust, and returns a scored PDF report listing the issues found. It states the problems and not the remedies, by design: the remedies are the conversation you wanted. When a check cannot answer with certainty the report says so and names it, rather than scoring it as a failure on a document you send to a prospect. A free assessment of something they already own is the most reliable way to obtain a name and an email address.', 'sabriel-ai' ),
			],
			[
				__( 'Recoverable conversation history', 'sabriel-ai' ),
				__( 'A visitor who talks to the assistant on a phone at lunchtime and opens a laptop that evening keeps the conversation. They request it, receive a signed link by email, and the assistant resumes already knowing who they are and what was discussed. For businesses whose customers deliberate over several days before deciding.', 'sabriel-ai' ),
			],
			[
				__( 'Portfolio and products in the chat', 'sabriel-ai' ),
				__( 'Describing a piece of work is one thing, showing it is another. When a visitor asks to see examples, the assistant presents your work inside the conversation, with image and price, sourced from wherever it already lives: WooCommerce, your theme\'s own content types, a page or the blog. Nothing is uploaded twice. For photographers, makers, retailers and anyone whose work is more persuasive than a description of it.', 'sabriel-ai' ),
			],
			[
				__( 'Mailchimp synchronisation', 'sabriel-ai' ),
				__( 'Nobody joins your mailing list by accident. The visitor ticks the box in the chat and then confirms from the email: genuine double opt-in, with one-click unsubscribe. It operates alongside lead scoring, so with that disabled nothing is recorded and the box is never displayed. For businesses running a newsletter that has to stand up to scrutiny on how the list was built.', 'sabriel-ai' ),
			],
			[
				__( 'Security pack', 'sabriel-ai' ),
				__( 'The configuration a developer would apply on day one, from a single screen and without editing files: XML-RPC disabled, WordPress version hidden, user enumeration blocked including over the REST API, login attempts limited, security headers applied, the file editor disabled, readme hidden, login errors made generic, and the login page relocated to an address of your choosing. For sites operated without dedicated maintenance.', 'sabriel-ai' ),
			],
			[
				__( 'Site knowledge', 'sabriel-ai' ),
				__( 'By default the assistant knows your business details and your price list, not the content of your pages. Here you select the pages that matter and the model reads each one and writes a concise summary into its own instructions. It is bound to the save action, so an edited page is reflected within five minutes, automatically, with nothing to trigger by hand. No embeddings are involved, which means no second provider key and no second invoice: behaviour is identical on Gemini, OpenAI and Claude.', 'sabriel-ai' ),
			],
			[
				__( 'Full customization', 'sabriel-ai' ),
				__( 'The free edition covers the essentials: logo, name and primary colours. The complete edition exposes every value, more than thirty of them, from the window background to the message bubbles, the panels, the input bar and the header icons with their opacity. It adds nine embedded font families, the shape and icon of the launcher, a greeting bubble that opens on its own, and a field for custom CSS where an option does not reach. For agencies delivering a finished site to a client.', 'sabriel-ai' ),
			],
		];
	}

	/**
	 * Short rows used by the plan table: [ label, is it in the free edition? ].
	 * Single source of truth: the free column ticks or crosses each row,
	 * and the Pro column lists exactly the crossed ones. They cannot drift apart.
	 */
	private static function righe_confronto() {
		return [
			[ __( 'AI assistant available to your visitors around the clock', 'sabriel-ai' ), true ],
			[ __( 'Your own key: Gemini, OpenAI or Claude, interchangeable at any time', 'sabriel-ai' ), true ],
			[ __( 'Sixteen models, with their cost shown upfront', 'sabriel-ai' ), true ],
			[ __( 'Replies in the visitor\'s language; panel and assistant in nine languages', 'sabriel-ai' ), true ],
			[ __( 'Answers drawn from your price list and your pages, never improvised', 'sabriel-ai' ), true ],
			[ __( 'Images, PDF documents and voice messages from visitors', 'sabriel-ai' ), true ],
			[ __( 'Escalation to you on WhatsApp, by email or by phone', 'sabriel-ai' ), true ],
			[ __( 'Logo, assistant name and the widget\'s primary colours', 'sabriel-ai' ), true ],
			[ __( 'Daily message cap set by you, abuse protection included', 'sabriel-ai' ), true ],
			[ __( 'Dashboard with the widget\'s traffic statistics', 'sabriel-ai' ), true ],
			[ __( 'System status page and complete documentation', 'sabriel-ai' ), true ],
			[ __( 'No Sabriel AI credit unless you switch it on: by default the widget carries only your name', 'sabriel-ai' ), true ],
			[ __( 'Updates straight from WordPress.org, like any other plugin', 'sabriel-ai' ), true ],
			[ __( 'Client management dashboard: appointments, quotes, audits, analytics and consents', 'sabriel-ai' ), false ],
			[ __( 'Full customization: over thirty colours and nine font families', 'sabriel-ai' ), false ],
			[ __( 'Appointment booking', 'sabriel-ai' ), false ],
			[ __( 'Numbered PDF quotes with space for a signature', 'sabriel-ai' ), false ],
			[ __( 'Lead scoring and analytics', 'sabriel-ai' ), false ],
			[ __( 'Free website audit for your visitors', 'sabriel-ai' ), false ],
			[ __( 'Recoverable history and returning-customer memory', 'sabriel-ai' ), false ],
			[ __( 'Portfolio and products inside the chat', 'sabriel-ai' ), false ],
			[ __( 'Knowledge of your site\'s pages', 'sabriel-ai' ), false ],
			[ __( 'Mailchimp synchronisation with double opt-in', 'sabriel-ai' ), false ],
			[ __( 'Security pack', 'sabriel-ai' ), false ],
		];
	}

	public function render_page() {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'Access denied', 'sabriel-ai' ) );
		}
		?>
		<style>
		.sab-acc{border:1.5px solid #e6e6e6;border-radius:11px;background:#fff;margin:0 0 8px;overflow:hidden}
		.sab-acc[open]{border-color:#c9d8ea;box-shadow:0 1px 8px rgba(20,97,204,.07)}
		.sab-acc summary{cursor:pointer;list-style:none;padding:13px 16px;display:flex;align-items:center;gap:9px;font-weight:650;font-size:14px;color:#16202b}
		.sab-acc summary::-webkit-details-marker{display:none}
		.sab-acc summary:hover{background:#f7f9fc}
		.sab-acc summary:focus-visible{outline:2px solid #1461CC;outline-offset:-2px}
		.sab-acc-frec{color:#8aa0b8;font-size:12px;transition:transform .18s;flex-shrink:0}
		.sab-acc[open] .sab-acc-frec{transform:rotate(90deg)}
		.sab-acc-corpo{padding:15px 16px 15px 34px}
		.sab-acc-intro{margin:0 0 12px;font-size:13.5px;color:#5a6672;line-height:1.65}
		.sab-acc-voce{font-size:13px;color:#243024;line-height:1.6;padding:5px 0;border-top:1px solid #f1f1f1}
		.sab-acc-spunta{color:#1a7f37;font-weight:800;margin-right:8px}
		.sab-acc-free{border-color:#d6e6d8;background:#fcfefc}
		.sab-acc-free[open]{border-color:#bcd9c0}
		</style>
		<div class="wrap" style="max-width:1330px">

			<h1 style="font-size:26px;margin:0 0 24px;letter-spacing:-.01em;max-width:860px"><?php esc_html_e( 'Your edition, and what the complete edition adds', 'sabriel-ai' ); ?></h1>
			<div style="background:#f4f8f4;border:1.5px solid #cfe4d2;border-radius:14px;padding:22px 24px;margin-bottom:30px;max-width:900px">
				<div style="display:flex;align-items:center;gap:9px;margin-bottom:14px">
					<span style="color:#1a7f37;font-size:18px;font-weight:800">&#10003;</span>
					<h2 style="margin:0;font-size:16px"><?php esc_html_e( 'Included in this edition, at no cost', 'sabriel-ai' ); ?></h2>
				</div>
				<p style="margin:0 0 14px;font-size:13px;color:#41603f;line-height:1.6"><?php esc_html_e( 'Select a section to see what it covers.', 'sabriel-ai' ); ?></p>
				<?php foreach ( self::cose_incluse() as $sab_g ) : ?>
					<details class="sab-acc sab-acc-free" name="sab-gruppo-free" data-gruppo="free">
						<summary>
							<span class="sab-acc-frec" aria-hidden="true">&#9656;</span>
							<span class="sab-acc-tit"><?php echo esc_html( $sab_g[0] ); ?></span>
						</summary>
						<div class="sab-acc-corpo">
							<p class="sab-acc-intro"><?php echo esc_html( $sab_g[1] ); ?></p>
							<?php foreach ( $sab_g[2] as $sab_riga ) : ?>
								<div class="sab-acc-voce"><span class="sab-acc-spunta">&#10003;</span><?php echo esc_html( $sab_riga ); ?></div>
							<?php endforeach; ?>
						</div>
					</details>
				<?php endforeach; ?>
			</div>

			<h2 style="font-size:17px;margin:0 0 6px;max-width:860px"><?php esc_html_e( 'What the complete edition adds', 'sabriel-ai' ); ?></h2>
			<p style="color:#777;font-size:13px;margin:0 0 18px;max-width:680px">
				<?php esc_html_e( 'Eleven capabilities that are not present in this package: not disabled, not hidden behind a button. They ship in a separate build that is installed in place of this one.', 'sabriel-ai' ); ?>
			</p>

			<div style="margin-bottom:34px;max-width:900px">
				<?php foreach ( self::cose_in_piu() as $sab_v ) : ?>
					<details class="sab-acc" name="sab-gruppo-pro" data-gruppo="pro">
						<summary>
							<span class="sab-acc-frec" aria-hidden="true">&#9656;</span>
							<span class="sab-acc-tit"><?php echo esc_html( $sab_v[0] ); ?></span>
						</summary>
						<div class="sab-acc-corpo"><p class="sab-acc-intro"><?php echo esc_html( $sab_v[1] ); ?></p></div>
					</details>
				<?php endforeach; ?>
			</div>

			<?php self::render_tabella_piani( [ 'id' => 'sabprem' ] ); ?>

			<div style="margin-top:28px;padding:16px 18px;background:#fafafa;border:1px solid #ececec;border-radius:11px;max-width:780px">
				<p style="margin:0 0 8px;font-size:13px;color:#555;line-height:1.65">
					<strong><?php esc_html_e( 'How switching works.', 'sabriel-ai' ); ?></strong>
					<?php esc_html_e( 'The complete edition is a separate package, downloaded after purchase, that replaces this one. Settings, appearance and conversations are preserved: nothing is lost.', 'sabriel-ai' ); ?>
				</p>
				<p style="margin:0;font-size:12.5px;color:#888;line-height:1.6">
					<?php
					printf(
						/* translators: %s: link to the author's website */
						esc_html__( 'In both editions the AI provider bills you directly, for the engine you chose: this plugin adds no margin on top. Questions: %s', 'sabriel-ai' ),
						'<a href="' . esc_url( self::URL_SITO ) . '" target="_blank" rel="noopener">' . esc_html( str_replace( 'https://', '', self::URL_SITO ) ) . '</a>'
					);
					?>
				</p>
			</div>
		</div>
		<script>
		(function(){
			document.querySelectorAll('details.sab-acc').forEach(function(d){
				d.addEventListener('toggle', function(){
					if(!d.open) return;
					document.querySelectorAll('details.sab-acc[data-gruppo="'+d.dataset.gruppo+'"]').forEach(function(x){
						if(x !== d && x.open) x.open = false;
					});
				});
			});
			document.addEventListener('click', function(e){
				if(e.target.closest && e.target.closest('details.sab-acc')) return;
				document.querySelectorAll('details.sab-acc[open]').forEach(function(x){ x.open = false; });
			});
			document.addEventListener('keydown', function(e){
				if(e.key !== 'Escape') return;
				document.querySelectorAll('details.sab-acc[open]').forEach(function(x){ x.open = false; });
			});
		})();
		</script>
		<?php
	}

	private static function render_lista_funzioni( $righe, $id, $scuro = false ) {
		$sab_bordo    = $scuro ? 'rgba(255,255,255,.07)' : '#f5f5f5';
		$sab_restanti = array_slice( $righe, 5 );
		foreach ( array_slice( $righe, 0, 5 ) as $sab_riga ) {
			self::render_riga_funzione( $sab_riga, $sab_bordo, $scuro );
		}
		if ( ! $sab_restanti ) {
			return;
		}
		/* translators: %d: how many more features are left to show in the plan list */
		$sab_testo_piu = sprintf( __( 'Show all (+%d)', 'sabriel-ai' ), count( $sab_restanti ) );
		echo '<div id="sab-extra-' . esc_attr( $id ) . '" style="display:none">';
		foreach ( $sab_restanti as $sab_riga ) {
			self::render_riga_funzione( $sab_riga, $sab_bordo, $scuro );
		}
		echo '</div>';
		printf(
			'<div onclick="sabPrezziEspandi()" id="sab-link-%1$s" data-testo-piu="%2$s" data-testo-meno="%3$s" style="cursor:pointer;color:%4$s;font-size:12.5px;font-weight:700;padding:10px 0 2px">%2$s</div>',
			esc_attr( $id ),
			esc_attr( $sab_testo_piu ),
			esc_attr__( 'Show less', 'sabriel-ai' ),
			$scuro ? '#7fb4ff' : '#1461CC'
		);
	}

	private static function render_riga_funzione( $riga, $bordo, $scuro ) {
		list( $sab_ok, $sab_testo ) = $riga;
		$sab_pallino = $sab_ok
			? ( $scuro ? 'background:rgba(74,222,128,.16);color:#4ade80' : 'background:rgba(34,197,94,.13);color:#16a34a' )
			: 'background:#f5f5f5;color:#ccc';
		$sab_colore = $sab_ok ? ( $scuro ? '#f0f0f0' : '#333' ) : '#bbb';
		echo '<div style="display:flex;align-items:center;gap:11px;padding:10px 0;border-bottom:1px solid ' . esc_attr( $bordo ) . '">';
		echo '<span style="width:19px;height:19px;border-radius:50%;flex-shrink:0;display:flex;align-items:center;justify-content:center;font-size:10px;font-weight:800;' . esc_attr( $sab_pallino ) . '">' . ( $sab_ok ? '&#10003;' : '&#10007;' ) . '</span>';
		echo '<span style="font-size:13.5px;color:' . esc_attr( $sab_colore ) . ';line-height:1.45">' . esc_html( $sab_testo ) . '</span>';
		echo '</div>';
	}

	public static function render_tabella_piani( $opzioni = [] ) {
		$p = isset( $opzioni['id'] ) ? preg_replace( '/[^a-z0-9_-]/i', '', $opzioni['id'] ) : 'sabtp';

		$sab_ritorno = ! empty( $opzioni['pubblico'] )
			? rawurlencode( home_url( '/' ) )
			: rawurlencode( admin_url( 'admin.php?page=sabriel-ai-prezzi' ) );

		$sab_voci_pro = [ __( 'Everything in the free edition', 'sabriel-ai' ) ];
		foreach ( self::righe_confronto() as $sab_voce ) {
			if ( empty( $sab_voce[1] ) ) {
				$sab_voci_pro[] = $sab_voce[0];
			}
		}

		$sab_piani = [
			'pro' => [
				'etichetta' => __( 'Pro', 'sabriel-ai' ),
				'azione'    => __( 'Upgrade to Pro', 'sabriel-ai' ),
				'url'       => add_query_arg( [ 'billing_cycle' => 'monthly', 'cancel_url' => $sab_ritorno ], self::URL_CHECKOUT_PRO ),
				'evidenza'  => true,
				'voci'      => $sab_voci_pro,
			],
			'studio' => [
				'etichetta' => __( 'Studio', 'sabriel-ai' ),
				'azione'    => __( 'Upgrade to Studio', 'sabriel-ai' ),
				'url'       => add_query_arg( [ 'billing_cycle' => 'monthly', 'cancel_url' => $sab_ritorno ], self::URL_CHECKOUT_STUDIO ),
				'evidenza'  => false,
				'voci'      => [
					__( 'Everything in Pro', 'sabriel-ai' ),
					__( 'Activatable on 5 sites with the same license', 'sabriel-ai' ),
					__( 'Built for freelancers and small studios', 'sabriel-ai' ),
				],
			],
			'agenzia' => [
				'etichetta' => __( 'Agency', 'sabriel-ai' ),
				'azione'    => __( 'Upgrade to Agency', 'sabriel-ai' ),
				'url'       => add_query_arg( [ 'billing_cycle' => 'monthly', 'cancel_url' => $sab_ritorno ], self::URL_CHECKOUT_AGENZIA ),
				'evidenza'  => false,
				'voci'      => [
					__( 'Everything in Pro', 'sabriel-ai' ),
					__( 'Activatable on 20 sites with the same license', 'sabriel-ai' ),
					__( 'Built for agencies and freelancers', 'sabriel-ai' ),
				],
			],
		];

		$sab_sotto = [];
		$sab_verde = [];
		foreach ( self::PREZZI as $sab_k => $sab_v ) {
			$sab_n = (int) $sab_v['siti'];
			$sab_sotto[ $sab_k ] = [
				/* translators: %d: number of sites the licence covers */
				'mensile'  => sprintf( _n( 'per month, for %d site', 'per month, for %d sites', $sab_n, 'sabriel-ai' ), $sab_n ),
				/* translators: %d: number of sites the licence covers */
				'annuale'  => sprintf( _n( 'per year, for %d site', 'per year, for %d sites', $sab_n, 'sabriel-ai' ), $sab_n ),
				/* translators: %d: number of sites the licence covers */
				'lifetime' => sprintf( _n( 'one payment, forever, for %d site', 'one payment, forever, for %d sites', $sab_n, 'sabriel-ai' ), $sab_n ),
			];
			$sab_verde[ $sab_k ] = [
				'mensile'  => '',
				/* translators: %d: how much less a year costs than twelve months */
				'annuale'  => sprintf( __( 'You save %d%% compared with monthly', 'sabriel-ai' ), (int) $sab_v['sconto'] ),
				/* translators: %d: how many months before a one-off payment costs less than renewing every year */
				'lifetime' => sprintf( _n( 'It pays for itself in %d month compared with yearly', 'It pays for itself in %d months compared with yearly', (int) $sab_v['ripaga'], 'sabriel-ai' ), (int) $sab_v['ripaga'] ),
			];
		}
		?>
		<div class="sab-piani" id="<?php echo esc_attr( $p ); ?>-piani">

			<div style="display:flex;justify-content:center;margin-bottom:26px">
				<div style="display:inline-flex;background:#f0f0f0;border-radius:10px;padding:4px;gap:2px">
					<button type="button" data-<?php echo esc_attr( $p ); ?>-ciclo="mensile" style="padding:8px 18px;border-radius:7px;border:none;font-size:12.5px;font-weight:700;cursor:pointer;background:#fff;box-shadow:0 1px 3px rgba(0,0,0,.15)"><?php esc_html_e( 'Monthly', 'sabriel-ai' ); ?></button>
					<button type="button" data-<?php echo esc_attr( $p ); ?>-ciclo="annuale" style="padding:8px 18px;border-radius:7px;border:none;font-size:12.5px;font-weight:700;cursor:pointer;background:transparent"><?php esc_html_e( 'Annual', 'sabriel-ai' ); ?></button>
					<button type="button" data-<?php echo esc_attr( $p ); ?>-ciclo="lifetime" style="padding:8px 18px;border-radius:7px;border:none;font-size:12.5px;font-weight:700;cursor:pointer;background:transparent"><?php esc_html_e( 'One-time', 'sabriel-ai' ); ?></button>
				</div>
			</div>

			<div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(258px,1fr));gap:18px;align-items:stretch">

				<div style="background:#fff;border:1.5px solid #ebebeb;border-radius:18px;padding:26px 20px;display:flex;flex-direction:column">
					<div style="font-weight:800;font-size:12px;letter-spacing:.08em;text-transform:uppercase;color:#999"><?php esc_html_e( 'This version', 'sabriel-ai' ); ?></div>
					<div style="font-size:30px;font-weight:800;margin:18px 0 8px;letter-spacing:-.02em;color:#111">$0</div>
					<div style="color:#aaa;font-size:12.5px;margin-bottom:22px"><?php esc_html_e( 'forever, unlimited sites', 'sabriel-ai' ); ?></div>
					<div style="flex:1">
						<?php
						$sab_righe_free = [];
						foreach ( self::righe_confronto() as $sab_voce ) {
							$sab_righe_free[] = [ (bool) $sab_voce[1], $sab_voce[0] ];
						}
						self::render_lista_funzioni( $sab_righe_free, $p . '-free' );
						?>
					</div>
					<div style="margin-top:22px;padding:12px;text-align:center;border-radius:10px;background:#fafafa;color:#999;font-weight:700;font-size:13px;border:1.5px solid #ebebeb"><?php esc_html_e( 'Your current edition', 'sabriel-ai' ); ?></div>
				</div>

				<?php foreach ( $sab_piani as $sab_k => $sab_pi ) :
					$sab_pr = self::PREZZI[ $sab_k ];
					$sab_ev = ! empty( $sab_pi['evidenza'] );
					?>
					<div style="background:<?php echo $sab_ev ? '#0c0c0e' : '#fff'; ?>;border:1.5px solid <?php echo $sab_ev ? '#0c0c0e' : '#ebebeb'; ?>;border-radius:18px;padding:26px 20px;display:flex;flex-direction:column;position:relative<?php echo $sab_ev ? ';box-shadow:0 16px 40px rgba(12,12,14,.22)' : ''; ?>">
						<?php if ( $sab_ev ) : ?>
							<div style="position:absolute;top:-13px;left:50%;transform:translateX(-50%);white-space:nowrap;background:#1461CC;color:#fff;font-size:10.5px;font-weight:800;padding:5px 14px;border-radius:20px;letter-spacing:.05em"><?php esc_html_e( 'MOST POPULAR', 'sabriel-ai' ); ?></div>
						<?php endif; ?>
						<div style="font-weight:800;font-size:12px;letter-spacing:.08em;text-transform:uppercase;color:<?php echo $sab_ev ? '#7fb4ff' : '#999'; ?>"><?php echo esc_html( $sab_pi['etichetta'] ); ?></div>
						<div style="font-size:30px;font-weight:800;margin:18px 0 8px;letter-spacing:-.02em;color:<?php echo $sab_ev ? '#fff' : '#111'; ?>" data-<?php echo esc_attr( $p ); ?>-prezzo="<?php echo esc_attr( $sab_k ); ?>" data-mensile="<?php echo esc_attr( $sab_pr['mensile'] ); ?>" data-annuale="<?php echo esc_attr( $sab_pr['annuale'] ); ?>" data-lifetime="<?php echo esc_attr( $sab_pr['lifetime'] ); ?>"><?php echo esc_html( $sab_pr['mensile'] ); ?></div>
						<div style="color:<?php echo $sab_ev ? '#8a8a90' : '#aaa'; ?>;font-size:12.5px" data-<?php echo esc_attr( $p ); ?>-sotto="<?php echo esc_attr( $sab_k ); ?>"><?php echo esc_html( $sab_sotto[ $sab_k ]['mensile'] ); ?></div>
						<div style="color:<?php echo $sab_ev ? '#4ade80' : '#16a34a'; ?>;font-size:12.5px;font-weight:700;margin-top:6px;min-height:18px" data-<?php echo esc_attr( $p ); ?>-verde="<?php echo esc_attr( $sab_k ); ?>"><?php echo esc_html( $sab_verde[ $sab_k ]['mensile'] ); ?></div>
						<div style="margin-bottom:22px"></div>
						<div style="flex:1">
							<?php
							$sab_righe = [];
							foreach ( $sab_pi['voci'] as $sab_r ) {
								$sab_righe[] = [ true, $sab_r ];
							}
							self::render_lista_funzioni( $sab_righe, $p . '-' . $sab_k, $sab_ev );
							?>
						</div>
						<a href="<?php echo esc_url( $sab_pi['url'] ); ?>" data-sab-checkout="<?php echo esc_attr( $sab_k ); ?>" target="_blank" rel="noopener" style="margin-top:22px;padding:12px;text-align:center;border-radius:10px;background:<?php echo $sab_ev ? '#1461CC' : '#fafafa'; ?>;color:<?php echo $sab_ev ? '#fff' : '#111'; ?>;font-weight:700;font-size:13px;text-decoration:none;display:block<?php echo $sab_ev ? '' : ';border:1.5px solid #ebebeb'; ?>"><?php echo esc_html( $sab_pi['azione'] ); ?></a>
					</div>
				<?php endforeach; ?>

			</div>
			<p style="color:#999;font-size:11.5px;margin-top:22px"><?php esc_html_e( 'Payments processed securely by Freemius. Cancel at any time.', 'sabriel-ai' ); ?></p>
		</div>

		<script>
		(function(){
			var radice = document.getElementById('<?php echo esc_js( $p ); ?>-piani');
			if(!radice) return;
			var sotto = <?php echo wp_json_encode( $sab_sotto ); ?>;
			var verde = <?php echo wp_json_encode( $sab_verde ); ?>;
			var CICLO = { mensile:'monthly', annuale:'annual', lifetime:'lifetime' };
			radice.querySelectorAll('[data-<?php echo esc_js( $p ); ?>-ciclo]').forEach(function(b){
				b.addEventListener('click', function(){
					var ciclo = b.getAttribute('data-<?php echo esc_js( $p ); ?>-ciclo');
					radice.querySelectorAll('[data-<?php echo esc_js( $p ); ?>-ciclo]').forEach(function(x){
						var on = x === b;
						x.style.background = on ? '#fff' : 'transparent';
						x.style.boxShadow = on ? '0 1px 3px rgba(0,0,0,.15)' : 'none';
					});
					Object.keys(sotto).forEach(function(piano){
						var prezzo = radice.querySelector('[data-<?php echo esc_js( $p ); ?>-prezzo="'+piano+'"]');
						var sot = radice.querySelector('[data-<?php echo esc_js( $p ); ?>-sotto="'+piano+'"]');
						if(prezzo) prezzo.textContent = prezzo.getAttribute('data-'+ciclo);
						if(sot) sot.textContent = sotto[piano][ciclo];
						var vrd = radice.querySelector('[data-<?php echo esc_js( $p ); ?>-verde="'+piano+'"]');
						if(vrd) vrd.textContent = verde[piano][ciclo];
						var link = radice.querySelector('[data-sab-checkout="'+piano+'"]');
						if(link){
							var url = new URL(link.href);
							url.searchParams.set('billing_cycle', CICLO[ciclo] || 'monthly');
							link.href = url.toString();
						}
					});
				});
			});
		})();
		function sabPrezziEspandi(){
			var primo = document.querySelector('[id^="sab-extra-"]');
			var apri  = primo ? (primo.style.display === 'none') : true;
			document.querySelectorAll('[id^="sab-extra-"]').forEach(function(extra){
				extra.style.display = apri ? 'block' : 'none';
			});
			document.querySelectorAll('[id^="sab-link-"]').forEach(function(link){
				link.textContent = apri ? link.dataset.testoMeno : link.dataset.testoPiu;
			});
		}
		</script>
		<?php
	}
}
