<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
$avi_lang = 'en';
if ( function_exists( 'avi_get_current_lang' ) ) { $avi_lang = avi_get_current_lang(); }
if ( $avi_lang === 'en' && isset( $_SERVER['REQUEST_URI'] ) ) {
    $req = $_SERVER['REQUEST_URI'];
    if ( strpos( $req, '/fr/' ) === 0 ) { $avi_lang = 'fr'; }
    elseif ( strpos( $req, '/es/' ) === 0 ) { $avi_lang = 'es'; }
}
if ( $avi_lang !== 'en' ) { set_query_var( 'avi_lang', $avi_lang ); }
$is_fr = ( $avi_lang === 'fr' );
$is_es = ( $avi_lang === 'es' );

$avi_meta_title = 'FAQ — Avision';
$avi_meta_desc  = 'Answers to the most common questions about Avision — for local businesses and agencies.';
$avi_schema_json = array(
	'@context' => 'https://schema.org',
	'@type'    => 'FAQPage',
	'name'     => 'FAQ — Avision',
	'url'      => 'https://avision.org/faq/',
);

if ( ! class_exists( 'Avision_Page_Template' ) ) {
	require_once AVISION_PLUGIN_DIR . 'includes/class-avision-page-template.php';
}

if ( ! function_exists( 'avi_faq_parse_corpus_answer' ) ) {
	/**
	 * @param string $content Corpus content field (question + answer).
	 */
	function avi_faq_parse_corpus_answer( string $content ): string {
		$pos = strpos( $content, '? ' );
		if ( false !== $pos ) {
			return trim( (string) substr( $content, $pos + 2 ) );
		}
		return trim( $content );
	}
}

if ( ! function_exists( 'avi_faq_load_corpus_answers' ) ) {
	/**
	 * @param array<int, string> $files Basenames under avision-backend/scripts/.
	 * @return array<int, string>
	 */
	function avi_faq_load_corpus_answers( array $files ): array {
		$answers = array();
		$root    = trailingslashit( ABSPATH ) . 'avision-backend/scripts/';
		foreach ( $files as $file ) {
			$path = $root . $file;
			if ( ! is_readable( $path ) ) {
				continue;
			}
			$raw  = file_get_contents( $path );
			$rows = json_decode( $raw, true );
			if ( ! is_array( $rows ) ) {
				continue;
			}
			foreach ( $rows as $row ) {
				if ( empty( $row['content'] ) ) {
					continue;
				}
				$answers[] = avi_faq_parse_corpus_answer( (string) $row['content'] );
			}
		}
		return $answers;
	}
}

if ( ! function_exists( 'avi_faq_render_accordions' ) ) {
	/**
	 * @param array<int, string> $questions Summary labels.
	 * @param array<int, string> $answers   Answer bodies.
	 */
	function avi_faq_render_accordions( array $questions, array $answers ): void {
		foreach ( $questions as $idx => $question ) {
			$answer = isset( $answers[ $idx ] ) ? $answers[ $idx ] : '';
			?>
			<details class="avi-faq-page__item">
				<summary class="avi-faq-page__summary"><?php echo esc_html( $question ); ?></summary>
				<div class="avi-faq-page__answer">
					<p><?php echo esc_html( $answer ); ?></p>
				</div>
			</details>
			<?php
		}
	}
}

$b2c_questions = array(
	'How do I connect my Google Business Profile?',
	'Why is my visibility score low?',
	'How does Guardian Mode work?',
	'My photos are not appearing on Google — what should I do?',
	'How do I cancel or modify my plan?',
	'What is Growth Radar?',
	'I redeemed my AppSumo code but my dashboard is empty',
	'How do I share my dashboard report?',
	'Why is my next step locked — how do timers work?',
	'I paid but Guardian or Growth Radar still shows inactive',
	'How do I upgrade from AVI Access to Guardian or a monthly pack?',
	'I connected the wrong Google Business Profile — how do I switch?',
	'My Google connection shows an error — how do I reconnect?',
);

$b2b_questions = array(
	'How do I import my client locations?',
	'How do I activate Guardian on multiple locations at once?',
	'How do I access a specific client\'s dashboard?',
	'How does wholesale pricing work?',
	'How do I generate a client report link?',
	'How do I upgrade my agency tier?',
	'My Google tokens expired — how do I reconnect?',
	'How does billing work per client location?',
	'What is the difference between Agency Access and monthly billing?',
	'How do I add a new client location after initial import?',
	'What is the difference between Radar Hebdo and Radar Elite?',
	'Bulk activation ran but some locations are still inactive',
	'How do I enable grey-label branding on client reports?',
);

$b2c_answers = avi_faq_load_corpus_answers(
	array(
		'corpus_support_faq_b2c_en.json',
		'corpus_support_faq_b2c_extra_en.json',
	)
);

$b2b_answers = avi_faq_load_corpus_answers(
	array(
		'corpus_support_faq_b2b_en.json',
		'corpus_support_faq_b2b_extra_en.json',
	)
);

// Réponses corrigées (alignement produit) — index = position dans $b2c_questions / $b2b_questions.
$b2c_answer_overrides = array(
	1  => 'Your visibility score reflects the current optimization state of your Google Business Profile across multiple key signals including NAP consistency, review response rate, photo freshness, post activity, keyword positions, and profile completeness. A low score is normal at the start — it means there is significant room to improve. AVI will guide you step by step through the actions that will raise your score the fastest.',
	4  => 'AVI Access is a one-time payment with no recurring charge — there is nothing to cancel. Guardian Mode and Growth Radar are monthly subscriptions. To cancel, contact us at contact@avision.org with your account email — cancellation is processed within 24 hours and takes effect at the end of your current billing period.',
	7  => 'The read-only report link is managed by your agency if you are on an agency plan. Your agency configures which sections are visible and sends you the link — it shows your visibility score, Guardian activity, and keyword positions in real time. If you purchased AVI Access directly, contact contact@avision.org to request a shareable report link for your account.',
	11 => 'If you selected the wrong location during onboarding, go to your dashboard and click the Google connection indicator to reauthorize via OAuth — you will be able to select the correct Business Profile location. If the issue persists, contact contact@avision.org with your account email and the correct business name. Your AVI Access and any paid products are not affected.',
	12 => 'In most cases, Avision refreshes your Google connection automatically in the background — you will not notice anything. If your authorization was revoked (for example, if you removed Avision from your Google account permissions), the reconnection modal will appear automatically when you open your dashboard. Follow the authorization flow — and make sure to check all permission boxes, including the ones allowing Avision to view, edit, and manage your Business Profile. If you leave any box unchecked, AVI will not be able to monitor or update your profile automatically. If the modal does not appear, go to myaccount.google.com/permissions, remove Avision from authorized apps, then return to your dashboard — the modal will launch automatically. Your score, progression, Guardian status, and all your data are fully preserved during reconnection — only the Google token is renewed.',
);
$b2b_answer_overrides = array(
	0  => 'From your Agency Fleet Dashboard, click Connect Google and authorize your agency account via OAuth. Avision will fetch all Google Business Profile locations associated with your account. Use Import more listings to add locations not included in the initial import. You can then assign Guardian Mode and Growth Radar to individual locations or in bulk. The import process takes under 5 minutes for most agency portfolios.',
	4  => 'From your Agency Fleet Dashboard, open the settings icon (⚙️) on the client profile card. Configure which dashboard sections are visible to your client using the visibility toggles. Once configured, use the View Dashboard link or copy the report URL — formatted as avision.org/report/your-agency/client-id/. Send this link directly to your client. The report updates in real time and is strictly read-only.',
	6  => 'Avision refreshes Google OAuth tokens automatically before each scan — in most cases you will not need to take any action. If a token was revoked by a client (they removed Avision from their Google account permissions), reconnect by clicking Connect Google in your Agency Fleet Dashboard and re-authorizing the relevant Google account via OAuth. Important: during the authorization screen, all permission boxes must be checked — including view, edit, and manage access. If any box is left unchecked, AVI cannot monitor or act on that client\'s profile. If the modal does not appear automatically, go to myaccount.google.com/permissions, remove Avision from authorized apps, then return to the dashboard. All client data, Guardian history, and configurations are fully preserved — only the API token is renewed.',
	12 => 'Grey label is included in all Agency Access tiers. To configure your branding, go to your Agency Fleet Dashboard under My Account → My Agency Identity. Upload your logo and enable grey label. Your agency logo will appear on all client-facing report links, formatted as avision.org/report/your-agency-slug/client-id/. Changes apply immediately to all existing and future client reports.',
);
foreach ( $b2c_answer_overrides as $idx => $text ) {
	if ( isset( $b2c_answers[ $idx ] ) ) {
		$b2c_answers[ $idx ] = $text;
	}
}
foreach ( $b2b_answer_overrides as $idx => $text ) {
	if ( isset( $b2b_answers[ $idx ] ) ) {
		$b2b_answers[ $idx ] = $text;
	}
}

$hero = array();

Avision_Page_Template::render(
	'faq',
	$hero,
	static function () use ( $avi_schema_json, $b2c_questions, $b2c_answers, $b2b_questions, $b2b_answers ) {
		$contact_url = home_url( '/contact/' );
		?>
		<div class="avi-faq-page">
			<style>
				.avi-faq-page { background: #0A1628; color: #ffffff; font-family: inherit; line-height: 1.65; }
				.avi-faq-page * { box-sizing: border-box; }
				.avi-faq-page__inner { max-width: 900px; margin: 0 auto; padding: 0 24px; }
				.avi-faq-page__hero { background: #0A1628; padding: 80px 0 40px; text-align: center; }
				.avi-faq-page__hero h1 { margin: 0 0 16px; font-size: 2.5rem; line-height: 1.15; font-weight: 800; color: #ffffff; }
				.avi-faq-page__hero p { margin: 0; max-width: 560px; margin-left: auto; margin-right: auto; font-size: 1.1rem; color: #94a3b8; }
				.avi-faq-page__tabs-section { background: #0A1628; padding: 0 0 64px; }
				.avi-faq-page__tab-input { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0, 0, 0, 0); white-space: nowrap; border: 0; }
				.avi-faq-page__tabs { display: flex; flex-wrap: wrap; gap: 12px; margin-bottom: 28px; }
				.avi-faq-page__tabs label { display: inline-block; padding: 12px 20px; border-radius: 8px; background: #0f1e35; color: #ffffff; font-weight: 600; font-size: 0.98rem; cursor: pointer; transition: background 0.2s ease; }
				#tab-b2c:checked ~ .avi-faq-page__tabs label[for="tab-b2c"],
				#tab-b2b:checked ~ .avi-faq-page__tabs label[for="tab-b2b"] { background: #6C3FC5; }
				.avi-faq-page__panels { display: block; }
				#tab-b2c:checked ~ .avi-faq-page__panels #panel-b2b,
				#tab-b2b:checked ~ .avi-faq-page__panels #panel-b2c { display: none; }
				.avi-faq-page__list { display: flex; flex-direction: column; gap: 8px; }
				.avi-faq-page__item { background: #0f1e35; border-left: 3px solid #6C3FC5; border-radius: 8px; overflow: hidden; }
				.avi-faq-page__summary { list-style: none; display: flex; align-items: center; justify-content: space-between; gap: 16px; padding: 20px 24px; color: #ffffff; font-weight: 600; cursor: pointer; }
				.avi-faq-page__summary::-webkit-details-marker { display: none; }
				.avi-faq-page__summary::after {
					content: "";
					flex-shrink: 0;
					width: 12px;
					height: 12px;
					background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 12 12' fill='none'%3E%3Cpath d='M4 2L8 6L4 10' stroke='%236C3FC5' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E");
					background-repeat: no-repeat;
					background-position: center;
					background-size: contain;
					transition: transform 0.2s ease;
				}
				.avi-faq-page__item[open] .avi-faq-page__summary { color: #F59E0B; }
				.avi-faq-page__item[open] .avi-faq-page__summary::after { transform: rotate(90deg); }
				.avi-faq-page__answer { color: #cbd5e1; padding: 0 24px 20px; line-height: 1.7; }
				.avi-faq-page__answer p { margin: 0; }
				.avi-faq-page__cta-wrap { background: #0A1628; padding: 0 0 80px; }
				.avi-faq-page__cta {
					max-width: 600px;
					margin: 0 auto;
					background: #0f1e35;
					border-radius: 16px;
					padding: 48px 32px;
					text-align: center;
				}
				.avi-faq-page__cta h2 { margin: 0 0 16px; font-size: 1.65rem; font-weight: 800; color: #ffffff; }
				.avi-faq-page__cta > p { margin: 0 0 24px; color: #94a3b8; font-size: 1rem; line-height: 1.65; }
				.avi-faq-page__cta-link {
					display: inline-block;
					background: #6C3FC5;
					color: #ffffff;
					text-decoration: none;
					border-radius: 8px;
					padding: 14px 28px;
					font-weight: 700;
					font-size: 1rem;
				}
				.avi-faq-page__cta-link:hover { color: #ffffff; opacity: 0.92; }
				.avi-faq-page__cta-note { margin: 16px 0 0; font-size: 13px; color: #94a3b8; }
				@media (max-width: 1024px) {
					.avi-faq-page__hero h1 { font-size: 2.15rem; }
				}
				@media (max-width: 768px) {
					.avi-faq-page__hero { padding: 56px 0 32px; }
					.avi-faq-page__hero h1 { font-size: 1.85rem; }
					.avi-faq-page__tabs { flex-direction: column; }
					.avi-faq-page__tabs label { text-align: center; }
					.avi-faq-page__tabs-section { padding-bottom: 48px; }
					.avi-faq-page__cta { padding: 36px 24px; }
				}
				@media (max-width: 480px) {
					.avi-faq-page__inner { padding: 0 16px; }
					.avi-faq-page__hero h1 { font-size: 1.55rem; }
					.avi-faq-page__summary { padding: 16px 18px; font-size: 0.95rem; }
					.avi-faq-page__answer { padding: 0 18px 16px; font-size: 0.95rem; }
				}
			</style>

			<section class="avi-faq-page__hero" aria-labelledby="avi-faq-hero-title">
				<div class="avi-faq-page__inner">
					<h1 id="avi-faq-hero-title">Frequently Asked Questions</h1>
					<p>Everything you need to know — before and after you get started.</p>
				</div>
			</section>

			<section class="avi-faq-page__tabs-section" aria-label="FAQ categories">
				<div class="avi-faq-page__inner avi-faq-page__tabs-root">
					<input class="avi-faq-page__tab-input" type="radio" name="faq-tab" id="tab-b2c" checked="checked" />
					<input class="avi-faq-page__tab-input" type="radio" name="faq-tab" id="tab-b2b" />
					<div class="avi-faq-page__tabs">
						<label for="tab-b2c">🏪 For Local Businesses</label>
						<label for="tab-b2b">🏢 For Agencies</label>
					</div>
					<div class="avi-faq-page__panels">
						<div class="avi-faq-page__panel" id="panel-b2c">
							<div class="avi-faq-page__list" role="list">
								<?php avi_faq_render_accordions( $b2c_questions, $b2c_answers ); ?>
							</div>
						</div>
						<div class="avi-faq-page__panel" id="panel-b2b">
							<div class="avi-faq-page__list" role="list">
								<?php avi_faq_render_accordions( $b2b_questions, $b2b_answers ); ?>
							</div>
						</div>
					</div>
				</div>
			</section>

			<section class="avi-faq-page__cta-wrap" aria-labelledby="avi-faq-cta-title">
				<div class="avi-faq-page__inner">
					<div class="avi-faq-page__cta">
						<h2 id="avi-faq-cta-title">Still have a question?</h2>
						<p>AVI answers most product questions instantly from your dashboard. For anything else — billing, account issues, technical problems — reach the founder directly.</p>
						<a class="avi-faq-page__cta-link" href="<?php echo esc_url( $contact_url ); ?>">Contact support →</a>
						<p class="avi-faq-page__cta-note">Response within 72 business hours · Handled by the founder</p>
					</div>
				</div>
			</section>
		</div>
		<script type="application/ld+json"><?php echo wp_json_encode( $avi_schema_json, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE ); ?></script>
		<?php
	}
);
