<?php
/**
 * Template: Legal Wizard (native, full parity — 11-step guided wizard)
 *
 * Multi-step wizard mirroring the Cloud Legal Wizard: Business → Jurisdiction →
 * Identity → Local → Marketplace (conditional) → Compliance → Contract
 * (conditional) → Tech → Social → AVV (conditional) → Documents. Company data is
 * persisted via save-legal-entity (only VALID LegalEntity columns are sent — the
 * Cloud view erroneously sends AVV-only fields that are not columns; we don't).
 * Documents are generated via generate-document using input keys that
 * legal-service.js::prismaTypeMap maps to valid enum values (AVV, not avv_dpa).
 *
 * @var array $data get-legal-wizard-data response: { legalEntity:{...}|null, jurisdictions:[{code,name,region,consentModel,framework}], documents:[{type,version}] }
 * @package Biscotti_CMP
 */

defined( 'ABSPATH' ) || exit;

// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Template is included inside Biscotti_Admin::render_dynamic_page(); these are function-scoped locals, not globals.

$page_title = __( 'Legal Wizard', 'biscotti-cmp' );
include __DIR__ . '/partials/page-header.php';

if ( null === $data ) :
	include __DIR__ . '/partials/loading-state.php';
	return;
endif;

$e             = ( isset( $data['legalEntity'] ) && is_array( $data['legalEntity'] ) ) ? $data['legalEntity'] : array();
$jurisdictions = ( isset( $data['jurisdictions'] ) && is_array( $data['jurisdictions'] ) ) ? $data['jurisdictions'] : array();
$documents     = ( isset( $data['documents'] ) && is_array( $data['documents'] ) ) ? $data['documents'] : array();

// --- helpers ---------------------------------------------------------------
$ev = function ( $key, $default = '' ) use ( $e ) {
	return isset( $e[ $key ] ) && null !== $e[ $key ] ? $e[ $key ] : $default;
};
$ec = function ( $key ) use ( $e ) {
	return ! empty( $e[ $key ] );
};

$business_category = (string) $ev( 'businessCategory', '' );
$is_marketplace    = ( 'marketplace' === $business_category );
$is_blog           = ( 'blog' === $business_category );

// Representative (first entry of representatives JSON array).
$reps     = ( isset( $e['representatives'] ) && is_array( $e['representatives'] ) ) ? $e['representatives'] : array();
$rep_name = ( ! empty( $reps ) && isset( $reps[0]['name'] ) ) ? (string) $reps[0]['name'] : '';

$social_profiles = ( isset( $e['socialMediaProfiles'] ) && is_array( $e['socialMediaProfiles'] ) ) ? $e['socialMediaProfiles'] : array();
$payment_methods = ( isset( $e['payment_methods'] ) && is_array( $e['payment_methods'] ) ) ? $e['payment_methods'] : array();
$has_agb_data    = ( isset( $e['agbData'] ) && is_array( $e['agbData'] ) && ! empty( $e['agbData'] ) );

// --- option data -----------------------------------------------------------
$business_categories = array(
	'ecommerce'   => __( 'E-Commerce / Online Store', 'biscotti-cmp' ),
	'saas'        => __( 'SaaS / Software', 'biscotti-cmp' ),
	'blog'        => __( 'Blog / Publishing', 'biscotti-cmp' ),
	'hospitality' => __( 'Hospitality / Tourism', 'biscotti-cmp' ),
	'healthcare'  => __( 'Healthcare', 'biscotti-cmp' ),
	'finance'     => __( 'Financial Services', 'biscotti-cmp' ),
	'education'   => __( 'Education / E-Learning', 'biscotti-cmp' ),
	'consulting'  => __( 'Consulting / Services', 'biscotti-cmp' ),
	'realestate'  => __( 'Real Estate', 'biscotti-cmp' ),
	'nonprofit'   => __( 'Non-Profit / Association', 'biscotti-cmp' ),
	'media'       => __( 'Media / Entertainment', 'biscotti-cmp' ),
	'marketplace' => __( 'Marketplace / Platform', 'biscotti-cmp' ),
	'other'       => __( 'Other', 'biscotti-cmp' ),
);

$social_platforms = array(
	'facebook'  => array( '📘', 'Facebook' ),
	'instagram' => array( '📷', 'Instagram' ),
	'linkedin'  => array( '💼', 'LinkedIn' ),
	'twitter'   => array( '🐦', 'X (Twitter)' ),
	'youtube'   => array( '▶️', 'YouTube' ),
	'tiktok'    => array( '🎵', 'TikTok' ),
	'pinterest' => array( '📌', 'Pinterest' ),
	'xing'      => array( '🔗', 'XING' ),
	'threads'   => array( '🧵', 'Threads' ),
	'mastodon'  => array( '🐘', 'Mastodon' ),
);

$region_labels = array(
	'europe'        => __( 'Europe & UK', 'biscotti-cmp' ),
	'north_america' => __( 'North America', 'biscotti-cmp' ),
	'south_america' => __( 'Latin America', 'biscotti-cmp' ),
	'asia'          => __( 'Asia-Pacific', 'biscotti-cmp' ),
	'africa'        => __( 'Africa', 'biscotti-cmp' ),
	'middle_east'   => __( 'Middle East', 'biscotti-cmp' ),
	'oceania'       => __( 'Oceania', 'biscotti-cmp' ),
	'eurasia'       => __( 'Eurasia', 'biscotti-cmp' ),
	'other'         => __( 'Other', 'biscotti-cmp' ),
);
$region_order = array( 'europe', 'north_america', 'south_america', 'asia', 'africa', 'middle_east', 'oceania', 'eurasia', 'other' );

// Documents to generate in the final step: value => label. Values map cleanly via prismaTypeMap.
$gen_doc_types = array(
	'IMPRESSUM'      => __( 'Legal Notice (Impressum)', 'biscotti-cmp' ),
	'PRIVACY_POLICY' => __( 'Privacy Policy', 'biscotti-cmp' ),
	'COOKIE_POLICY'  => __( 'Cookie Policy', 'biscotti-cmp' ),
	'TERMS'          => __( 'Terms & Conditions (AGB)', 'biscotti-cmp' ),
	'WIDERRUF'       => __( 'Cancellation Policy (Widerruf)', 'biscotti-cmp' ),
	'AVV'            => __( 'Data Processing Agreement (AVV)', 'biscotti-cmp' ),
	'DSA_INFO'       => __( 'DSA Information', 'biscotti-cmp' ),
);

// Build doc version lookup (stored types are UPPERCASE enum).
$doc_versions = array();
foreach ( $documents as $d ) {
	if ( isset( $d['type'] ) ) {
		$doc_versions[ strtoupper( (string) $d['type'] ) ] = isset( $d['version'] ) ? absint( $d['version'] ) : 1;
	}
}

// --- build active steps ----------------------------------------------------
$all_steps = array(
	array( 'id' => 'business',     'icon' => '🏢', 'label' => __( 'Business Context', 'biscotti-cmp' ), 'show' => true ),
	array( 'id' => 'jurisdiction', 'icon' => '🌍', 'label' => __( 'Jurisdiction', 'biscotti-cmp' ), 'show' => true ),
	array( 'id' => 'identity',     'icon' => '🪪', 'label' => __( 'Identity', 'biscotti-cmp' ), 'show' => true ),
	array( 'id' => 'local',        'icon' => '📍', 'label' => __( 'Local Requirements', 'biscotti-cmp' ), 'show' => true ),
	array( 'id' => 'marketplace',  'icon' => '🏪', 'label' => __( 'Marketplace', 'biscotti-cmp' ), 'show' => $is_marketplace ),
	array( 'id' => 'compliance',   'icon' => '✅', 'label' => __( 'Compliance', 'biscotti-cmp' ), 'show' => true ),
	array( 'id' => 'contract',     'icon' => '💳', 'label' => __( 'Contract Details', 'biscotti-cmp' ), 'show' => ! $is_blog ),
	array( 'id' => 'tech',         'icon' => '⚙️', 'label' => __( 'Tech Stack', 'biscotti-cmp' ), 'show' => true ),
	array( 'id' => 'social',       'icon' => '📱', 'label' => __( 'Social Media', 'biscotti-cmp' ), 'show' => true ),
	array( 'id' => 'avv',          'icon' => '📋', 'label' => __( 'AVV / DPA', 'biscotti-cmp' ), 'show' => ! $is_blog ),
	array( 'id' => 'documents',    'icon' => '📄', 'label' => __( 'Documents', 'biscotti-cmp' ), 'show' => true ),
);
$steps = array();
foreach ( $all_steps as $s ) {
	if ( $s['show'] ) {
		$steps[] = $s;
	}
}

// JSON data for the wizard script (jurisdiction lookup + step order).
$jur_lookup = array();
foreach ( $jurisdictions as $j ) {
	if ( isset( $j['code'] ) ) {
		$jur_lookup[ $j['code'] ] = array(
			'name'      => isset( $j['name'] ) ? $j['name'] : $j['code'],
			'model'     => isset( $j['consentModel'] ) ? $j['consentModel'] : 'NOTICE',
			'framework' => isset( $j['framework'] ) ? $j['framework'] : '',
		);
	}
}
$wizard_data = array(
	'stepIds'      => wp_list_pluck( $steps, 'id' ),
	'totalSteps'   => count( $steps ),
	'jurisdiction' => (string) $ev( 'jurisdiction', '' ),
	'jurLookup'    => $jur_lookup,
);

// Group jurisdictions by region for the dropdown.
$grouped = array();
foreach ( $jurisdictions as $j ) {
	$r = isset( $j['region'] ) ? $j['region'] : 'other';
	$grouped[ $r ][] = $j;
}
$cur_jur = (string) $ev( 'jurisdiction', '' );

// --- single-source jurisdiction schema (from get-legal-wizard-data .schema) -----
// Renders the Identity step's legal forms, tax-ID/registration fields and the
// state/province dropdown for the SELECTED jurisdiction — identical to the App.
$lw_schema    = ( isset( $data['schema'] ) && is_array( $data['schema'] ) ) ? $data['schema'] : array();
$lw_sj        = ( isset( $lw_schema['jurisdiction'] ) && is_array( $lw_schema['jurisdiction'] ) ) ? $lw_schema['jurisdiction'] : array();
$lw_countries = ( isset( $lw_schema['countries'] ) && is_array( $lw_schema['countries'] ) ) ? $lw_schema['countries'] : array();
$lw_fmap      = ( isset( $lw_schema['fieldColumnMap'] ) && is_array( $lw_schema['fieldColumnMap'] ) ) ? $lw_schema['fieldColumnMap'] : array();
$lw_jid       = isset( $lw_schema['jurisdictionId'] ) ? (string) $lw_schema['jurisdictionId'] : '';
$lw_ja        = ( isset( $e['jurisdictionAnswers'] ) && is_array( $e['jurisdictionAnswers'] ) ) ? $e['jurisdictionAnswers'] : array();
// Derive the country code from the selected jurisdiction (no redundant free-text field).
$lw_country_code = (string) $ev( 'country', '' );
if ( '' === $lw_country_code ) {
	foreach ( $lw_countries as $c ) {
		if ( isset( $c['jurisdictionId'], $c['code'] ) && $c['jurisdictionId'] === $lw_jid ) {
			$lw_country_code = (string) $c['code'];
			break;
		}
	}
	if ( '' === $lw_country_code ) {
		$lw_country_code = 'DE';
	}
}
$lw_company_types    = ( isset( $lw_sj['companyTypes'] ) && is_array( $lw_sj['companyTypes'] ) ) ? $lw_sj['companyTypes'] : array();
$lw_reg_fields       = ( isset( $lw_sj['registrationFields'] ) && is_array( $lw_sj['registrationFields'] ) ) ? $lw_sj['registrationFields'] : array();
$lw_states           = ( isset( $lw_sj['states'] ) && is_array( $lw_sj['states'] ) ) ? $lw_sj['states'] : array();
$lw_state_label      = ( isset( $lw_sj['addressFormat']['stateLabel'] ) && $lw_sj['addressFormat']['stateLabel'] ) ? (string) $lw_sj['addressFormat']['stateLabel'] : __( 'State / Province', 'biscotti-cmp' );
$lw_cur_company_type = (string) $ev( 'companyTypeId', '' );
$lw_cur_state        = (string) $ev( 'state', '' );
$lw_icon_enum        = array( 'User' => 'PRIVATE', 'Building2' => 'COMPANY', 'Users' => 'PARTNERSHIP', 'Shield' => 'ASSOCIATION' );
// Localized country names (code -> localized string) for the jurisdiction dropdown (Req 4.4).
$lw_cname = array();
foreach ( $lw_countries as $c ) {
	if ( isset( $c['code'] ) ) {
		$lw_cname[ $c['code'] ] = isset( $c['name'] ) ? (string) $c['name'] : (string) $c['code'];
	}
}
// Resolve the stored value for a jurisdiction-specific registration field id:
// canonical column first (via field map), then the jurisdictionAnswers JSON.
$lw_reg_value = function ( $fid ) use ( $e, $lw_fmap, $lw_ja ) {
	$col = isset( $lw_fmap[ $fid ] ) ? $lw_fmap[ $fid ] : $fid;
	if ( isset( $e[ $col ] ) && '' !== $e[ $col ] && null !== $e[ $col ] ) {
		return (string) $e[ $col ];
	}
	return isset( $lw_ja[ $fid ] ) ? (string) $lw_ja[ $fid ] : '';
};
?>

<div class="biscotti-page biscotti-page-legal-wizard" id="biscotti-lw">

	<p class="description"><?php esc_html_e( 'Step-by-step guide to set up your legal documents. AI-generated documents are not legal advice — have them reviewed by a qualified lawyer before publishing.', 'biscotti-cmp' ); ?></p>

	<!-- Progress bar -->
	<div class="biscotti-lw-progress">
		<?php foreach ( $steps as $i => $s ) : ?>
			<button type="button" class="biscotti-lw-step<?php echo 0 === $i ? ' active' : ''; ?>" data-step="<?php echo esc_attr( $i + 1 ); ?>" data-id="<?php echo esc_attr( $s['id'] ); ?>">
				<span class="biscotti-lw-step-num"><?php echo esc_html( $i + 1 ); ?></span>
				<span class="biscotti-lw-step-label"><?php echo esc_html( $s['icon'] . ' ' . $s['label'] ); ?></span>
			</button>
		<?php endforeach; ?>
	</div>

	<!-- STEP: Business -->
	<div class="biscotti-lw-panel active" data-id="business">
		<div class="biscotti-card">
			<h3>🏢 <?php esc_html_e( 'Business Context', 'biscotti-cmp' ); ?></h3>
			<div class="biscotti-lw-grid-2">
				<p class="biscotti-form-row"><label><?php esc_html_e( 'Industry', 'biscotti-cmp' ); ?> *</label>
					<select id="lw-businessCategory" class="biscotti-svc-input">
						<option value="">— <?php esc_html_e( 'Select', 'biscotti-cmp' ); ?> —</option>
						<?php foreach ( $business_categories as $k => $label ) : ?>
							<option value="<?php echo esc_attr( $k ); ?>" <?php selected( $business_category, $k ); ?>><?php echo esc_html( $label ); ?></option>
						<?php endforeach; ?>
					</select>
				</p>
				<p class="biscotti-form-row"><label><?php esc_html_e( 'Sub-Industry', 'biscotti-cmp' ); ?></label>
					<input type="text" id="lw-businessSubcategory" class="biscotti-svc-input" value="<?php echo esc_attr( $ev( 'businessSubcategory' ) ); ?>" />
				</p>
			</div>
			<p class="biscotti-form-row"><label><?php esc_html_e( 'Business Description', 'biscotti-cmp' ); ?></label>
				<textarea id="lw-businessDescription" class="biscotti-svc-input" rows="3"><?php echo esc_textarea( $ev( 'businessDescription' ) ); ?></textarea>
			</p>
			<div class="biscotti-lw-grid-3">
				<p class="biscotti-form-row"><label class="lw-cb"><input type="checkbox" id="lw-hasEcommerce" <?php checked( $ec( 'hasEcommerce' ) ); ?> /> <?php esc_html_e( 'Online sales (products/services)', 'biscotti-cmp' ); ?></label></p>
				<p class="biscotti-form-row"><label class="lw-cb"><input type="checkbox" id="lw-hasNewsletter" <?php checked( $ec( 'hasNewsletter' ) ); ?> /> <?php esc_html_e( 'Newsletter / email marketing', 'biscotti-cmp' ); ?></label></p>
				<p class="biscotti-form-row"><label><?php esc_html_e( 'Employee Count', 'biscotti-cmp' ); ?></label><input type="number" id="lw-employeeCount" class="biscotti-svc-input" min="0" value="<?php echo esc_attr( $ev( 'employeeCount' ) ); ?>" /></p>
			</div>
		</div>
	</div>

	<!-- STEP: Jurisdiction -->
	<div class="biscotti-lw-panel" data-id="jurisdiction">
		<div class="biscotti-card">
			<h3>🌍 <?php esc_html_e( 'Jurisdiction', 'biscotti-cmp' ); ?></h3>
			<p class="biscotti-form-row"><label><?php esc_html_e( 'Primary Jurisdiction', 'biscotti-cmp' ); ?> *</label>
				<select id="lw-jurisdiction" class="biscotti-svc-input">
					<option value="">— <?php esc_html_e( 'Select', 'biscotti-cmp' ); ?> —</option>
					<?php
					foreach ( $region_order as $rk ) :
						if ( empty( $grouped[ $rk ] ) ) {
							continue;
						}
						$label = isset( $region_labels[ $rk ] ) ? $region_labels[ $rk ] : $rk;
						?>
						<optgroup label="<?php echo esc_attr( $label . ' (' . count( $grouped[ $rk ] ) . ')' ); ?>">
							<?php foreach ( $grouped[ $rk ] as $j ) :
								$suffix = ! empty( $j['framework'] ) ? ' (' . $j['framework'] . ')' : '';
								$j_name = isset( $lw_cname[ $j['code'] ] ) ? $lw_cname[ $j['code'] ] : $j['name'];
								?>
								<option value="<?php echo esc_attr( $j['code'] ); ?>" <?php selected( $cur_jur, $j['code'] ); ?>><?php echo esc_html( $j_name . $suffix ); ?></option>
							<?php endforeach; ?>
						</optgroup>
					<?php endforeach; ?>
				</select>
				<span class="description"><?php echo esc_html( sprintf( /* translators: %d count */ __( '%d jurisdictions available', 'biscotti-cmp' ), count( $jurisdictions ) ) ); ?></span>
			</p>
			<p class="biscotti-form-row"><label><?php esc_html_e( 'Target Audience', 'biscotti-cmp' ); ?></label></p>
			<?php $ta = (string) $ev( 'targetAudience', 'B2C' ); ?>
			<div class="biscotti-lw-radio-row">
				<label class="lw-radio"><input type="radio" name="lw-targetAudience" value="B2C" <?php checked( $ta, 'B2C' ); ?> /> <?php esc_html_e( 'B2C (Consumers)', 'biscotti-cmp' ); ?></label>
				<label class="lw-radio"><input type="radio" name="lw-targetAudience" value="B2B" <?php checked( $ta, 'B2B' ); ?> /> <?php esc_html_e( 'B2B (Businesses)', 'biscotti-cmp' ); ?></label>
				<label class="lw-radio"><input type="radio" name="lw-targetAudience" value="B2B2C" <?php checked( $ta, 'B2B2C' ); ?> /> <?php esc_html_e( 'B2B + B2C', 'biscotti-cmp' ); ?></label>
			</div>
		</div>
	</div>

	<!-- STEP: Identity -->
	<div class="biscotti-lw-panel" data-id="identity">
		<div class="biscotti-card">
			<h3>🪪 <?php esc_html_e( 'Identity', 'biscotti-cmp' ); ?></h3>
			<div class="biscotti-lw-grid-2">
				<p class="biscotti-form-row" id="lw-companyType-wrap"><label><?php esc_html_e( 'Legal Form', 'biscotti-cmp' ); ?></label>
					<select id="lw-companyTypeId" class="biscotti-svc-input">
						<option value="">— <?php esc_html_e( 'Select', 'biscotti-cmp' ); ?> —</option>
						<?php foreach ( $lw_company_types as $ct ) :
							$ct_id   = isset( $ct['id'] ) ? (string) $ct['id'] : '';
							$ct_lbl  = isset( $ct['label'] ) ? (string) $ct['label'] : $ct_id;
							$ct_icon = isset( $ct['icon'] ) ? (string) $ct['icon'] : 'Building2';
							$ct_enum = isset( $lw_icon_enum[ $ct_icon ] ) ? $lw_icon_enum[ $ct_icon ] : 'COMPANY';
							?>
							<option value="<?php echo esc_attr( $ct_id ); ?>" data-entity-type="<?php echo esc_attr( $ct_enum ); ?>" <?php selected( $lw_cur_company_type, $ct_id ); ?>><?php echo esc_html( $ct_lbl ); ?></option>
						<?php endforeach; ?>
					</select>
				</p>
				<p class="biscotti-form-row"><label><?php esc_html_e( 'Company Name', 'biscotti-cmp' ); ?> *</label><input type="text" id="lw-companyName" class="biscotti-svc-input" value="<?php echo esc_attr( $ev( 'companyName' ) ); ?>" /></p>
			</div>
			<div class="biscotti-lw-grid-3">
				<p class="biscotti-form-row"><label><?php esc_html_e( 'Street & No.', 'biscotti-cmp' ); ?></label><input type="text" id="lw-street" class="biscotti-svc-input" value="<?php echo esc_attr( $ev( 'street' ) ); ?>" /></p>
				<p class="biscotti-form-row"><label><?php esc_html_e( 'Postal Code', 'biscotti-cmp' ); ?></label><input type="text" id="lw-zip" class="biscotti-svc-input" value="<?php echo esc_attr( $ev( 'zip' ) ); ?>" /></p>
				<p class="biscotti-form-row"><label><?php esc_html_e( 'City', 'biscotti-cmp' ); ?></label><input type="text" id="lw-city" class="biscotti-svc-input" value="<?php echo esc_attr( $ev( 'city' ) ); ?>" /></p>
			</div>
			<div class="biscotti-lw-grid-2">
				<span id="lw-state-wrap">
					<?php if ( ! empty( $lw_states ) ) : ?>
						<p class="biscotti-form-row"><label><?php echo esc_html( $lw_state_label ); ?></label>
							<select id="lw-state" class="biscotti-svc-input">
								<option value="">— <?php esc_html_e( 'Select', 'biscotti-cmp' ); ?> —</option>
								<?php foreach ( $lw_states as $st ) :
									$st_id  = isset( $st['id'] ) ? (string) $st['id'] : '';
									$st_nm  = isset( $st['name'] ) ? (string) $st['name'] : $st_id;
									?>
									<option value="<?php echo esc_attr( $st_id ); ?>" <?php selected( $lw_cur_state, $st_id ); ?>><?php echo esc_html( $st_nm ); ?></option>
								<?php endforeach; ?>
							</select>
						</p>
					<?php else : ?>
						<input type="hidden" id="lw-state" value="<?php echo esc_attr( $lw_cur_state ); ?>" />
					<?php endif; ?>
				</span>
				<p class="biscotti-form-row"><label><?php esc_html_e( 'Email', 'biscotti-cmp' ); ?> *</label><input type="email" id="lw-email" class="biscotti-svc-input" value="<?php echo esc_attr( $ev( 'email' ) ); ?>" /></p>
			</div>
			<div class="biscotti-lw-grid-2">
				<p class="biscotti-form-row"><label><?php esc_html_e( 'Phone', 'biscotti-cmp' ); ?></label><input type="text" id="lw-phone" class="biscotti-svc-input" value="<?php echo esc_attr( $ev( 'phone' ) ); ?>" /></p>
				<p class="biscotti-form-row"><label><?php esc_html_e( 'Authorized Representative', 'biscotti-cmp' ); ?></label><input type="text" id="lw-representative" class="biscotti-svc-input" value="<?php echo esc_attr( $rep_name ); ?>" /></p>
			</div>
			<?php // Jurisdiction-specific registration / tax-ID fields (CUIT for AR, USt-IdNr. for DE, SIRET for FR, …) — schema-driven. ?>
			<div class="biscotti-lw-grid-2" id="lw-registration-fields">
				<?php foreach ( $lw_reg_fields as $fid => $cfg ) :
					$rf_label = isset( $cfg['label'] ) ? (string) $cfg['label'] : $fid;
					$rf_ph    = isset( $cfg['placeholder'] ) ? (string) $cfg['placeholder'] : '';
					$rf_req   = ! empty( $cfg['required'] );
					?>
					<p class="biscotti-form-row"><label><?php echo esc_html( $rf_label ); ?><?php echo $rf_req ? ' *' : ''; ?></label><input type="text" id="lw-rf-<?php echo esc_attr( $fid ); ?>" data-lw-rf="<?php echo esc_attr( $fid ); ?>" class="biscotti-svc-input" value="<?php echo esc_attr( $lw_reg_value( $fid ) ); ?>" placeholder="<?php echo esc_attr( $rf_ph ); ?>" /></p>
				<?php endforeach; ?>
			</div>
			<div class="biscotti-lw-grid-2">
				<p class="biscotti-form-row"><label><?php esc_html_e( 'Data Protection Officer', 'biscotti-cmp' ); ?></label><input type="text" id="lw-dpoName" class="biscotti-svc-input" value="<?php echo esc_attr( $ev( 'dpoName' ) ); ?>" /></p>
				<p class="biscotti-form-row"><label><?php esc_html_e( 'DPO Email', 'biscotti-cmp' ); ?></label><input type="email" id="lw-dpoEmail" class="biscotti-svc-input" value="<?php echo esc_attr( $ev( 'dpoEmail' ) ); ?>" /></p>
			</div>
			<?php // Country is derived from the selected jurisdiction (no contradictory free-text field). ?>
			<input type="hidden" id="lw-country" value="<?php echo esc_attr( $lw_country_code ); ?>" />
			<input type="hidden" id="lw-entityType" value="<?php echo esc_attr( $ev( 'entityType', 'COMPANY' ) ); ?>" />
		</div>
	</div>

	<!-- STEP: Local -->
	<div class="biscotti-lw-panel" data-id="local">
		<div class="biscotti-card">
			<h3>📍 <?php esc_html_e( 'Local Requirements', 'biscotti-cmp' ); ?></h3>
			<p class="description"><?php esc_html_e( 'Jurisdiction-specific questions needed for legally compliant documents in your selected country (e.g. the responsible person under § 18 MStV for journalistic content in Germany).', 'biscotti-cmp' ); ?></p>
			<div id="lw-local-questions"
				data-empty="<?php echo esc_attr_x( 'No additional country-specific questions for the selected jurisdiction.', 'legal wizard', 'biscotti-cmp' ); ?>"
				data-condition-label="<?php echo esc_attr__( 'Condition', 'biscotti-cmp' ); ?>"
				data-ph-name="<?php echo esc_attr__( 'First and last name of the responsible person', 'biscotti-cmp' ); ?>"
				data-ph-street="<?php echo esc_attr__( 'Street & Number', 'biscotti-cmp' ); ?>"
				data-ph-zip="<?php echo esc_attr__( 'Postal Code', 'biscotti-cmp' ); ?>"
				data-ph-city="<?php echo esc_attr__( 'City', 'biscotti-cmp' ); ?>"
				data-ph-email="<?php echo esc_attr__( 'Email', 'biscotti-cmp' ); ?>"
				data-ph-text="<?php echo esc_attr__( 'Your answer…', 'biscotti-cmp' ); ?>">
				<p class="biscotti-empty-state"><?php esc_html_e( 'Select a jurisdiction to see country-specific requirements.', 'biscotti-cmp' ); ?></p>
			</div>
		</div>
	</div>

	<?php if ( $is_marketplace ) : ?>
	<!-- STEP: Marketplace -->
	<div class="biscotti-lw-panel" data-id="marketplace">
		<div class="biscotti-card">
			<h3>🏪 <?php esc_html_e( 'Marketplace', 'biscotti-cmp' ); ?></h3>
			<div class="biscotti-lw-grid-2">
				<p class="biscotti-form-row"><label><?php esc_html_e( 'Marketplace Type', 'biscotti-cmp' ); ?></label>
					<select id="lw-marketplaceType" class="biscotti-svc-input">
						<?php $mt = (string) $ev( 'marketplaceType', '' ); ?>
						<option value="">—</option>
						<?php foreach ( array( 'B2C', 'C2C', 'B2B', 'HYBRID' ) as $opt ) : ?>
							<option value="<?php echo esc_attr( $opt ); ?>" <?php selected( $mt, $opt ); ?>><?php echo esc_html( $opt ); ?></option>
						<?php endforeach; ?>
					</select>
				</p>
				<p class="biscotti-form-row"><label><?php esc_html_e( 'Seller Verification', 'biscotti-cmp' ); ?></label>
					<select id="lw-marketplaceSellerVerification" class="biscotti-svc-input">
						<?php $sv = (string) $ev( 'marketplaceSellerVerification', 'email' ); ?>
						<option value="email" <?php selected( $sv, 'email' ); ?>><?php esc_html_e( 'Email', 'biscotti-cmp' ); ?></option>
						<option value="kyb" <?php selected( $sv, 'kyb' ); ?>><?php esc_html_e( 'KYB', 'biscotti-cmp' ); ?></option>
						<option value="full" <?php selected( $sv, 'full' ); ?>><?php esc_html_e( 'Full', 'biscotti-cmp' ); ?></option>
					</select>
				</p>
			</div>
			<div class="biscotti-lw-grid-2">
				<p class="biscotti-form-row"><label class="lw-cb"><input type="checkbox" id="lw-marketplaceDsaCompliant" <?php checked( false !== $ev( 'marketplaceDsaCompliant', true ) ); ?> /> <?php esc_html_e( 'DSA compliant', 'biscotti-cmp' ); ?></label></p>
				<p class="biscotti-form-row"><label class="lw-cb"><input type="checkbox" id="lw-marketplaceP2bCompliant" <?php checked( false !== $ev( 'marketplaceP2bCompliant', true ) ); ?> /> <?php esc_html_e( 'P2B compliant', 'biscotti-cmp' ); ?></label></p>
			</div>
			<p class="biscotti-form-row"><label><?php esc_html_e( 'Ranking Criteria', 'biscotti-cmp' ); ?></label><textarea id="lw-marketplaceRankingCriteria" class="biscotti-svc-input" rows="2"><?php echo esc_textarea( $ev( 'marketplaceRankingCriteria' ) ); ?></textarea></p>
		</div>
	</div>
	<?php endif; ?>

	<!-- STEP: Compliance -->
	<div class="biscotti-lw-panel" data-id="compliance">
		<div class="biscotti-card">
			<h3>✅ <?php esc_html_e( 'Compliance Analysis', 'biscotti-cmp' ); ?></h3>
			<div id="lw-compliance-results">
				<p class="biscotti-empty-state"><?php esc_html_e( 'Select a jurisdiction in the Jurisdiction step to see your compliance analysis.', 'biscotti-cmp' ); ?></p>
			</div>
		</div>
	</div>

	<?php if ( ! $is_blog ) : ?>
	<!-- STEP: Contract -->
	<div class="biscotti-lw-panel" data-id="contract">
		<div class="biscotti-card">
			<h3>💳 <?php esc_html_e( 'Contract Details', 'biscotti-cmp' ); ?></h3>

			<h4><?php esc_html_e( 'Contract Formation', 'biscotti-cmp' ); ?></h4>
			<?php $offer = (string) $ev( 'offer_type', 'invitatio' ); ?>
			<div class="biscotti-lw-radio-row">
				<label class="lw-radio"><input type="radio" name="lw-offerType" value="invitatio" <?php checked( $offer, 'invitatio' ); ?> /> <?php esc_html_e( 'Invitation to order (recommended)', 'biscotti-cmp' ); ?></label>
				<label class="lw-radio"><input type="radio" name="lw-offerType" value="binding" <?php checked( $offer, 'binding' ); ?> /> <?php esc_html_e( 'Binding offer', 'biscotti-cmp' ); ?></label>
			</div>
			<?php $concl = (string) $ev( 'contract_conclusion', 'confirmation_email' ); ?>
			<div class="biscotti-lw-radio-row">
				<label class="lw-radio"><input type="radio" name="lw-contractConclusion" value="confirmation_email" <?php checked( $concl, 'confirmation_email' ); ?> /> <?php esc_html_e( 'With order confirmation email', 'biscotti-cmp' ); ?></label>
				<label class="lw-radio"><input type="radio" name="lw-contractConclusion" value="shipment" <?php checked( $concl, 'shipment' ); ?> /> <?php esc_html_e( 'Upon shipment', 'biscotti-cmp' ); ?></label>
				<label class="lw-radio"><input type="radio" name="lw-contractConclusion" value="order" <?php checked( $concl, 'order' ); ?> /> <?php esc_html_e( 'On order completion', 'biscotti-cmp' ); ?></label>
			</div>

			<h4><?php esc_html_e( 'Payment', 'biscotti-cmp' ); ?></h4>
			<p class="biscotti-form-row"><label class="lw-cb"><input type="checkbox" id="lw-pricesIncludeVat" <?php checked( false !== $ev( 'prices_include_vat', true ) ); ?> /> <?php esc_html_e( 'Prices include VAT', 'biscotti-cmp' ); ?></label></p>
			<div class="biscotti-lw-toggle-grid">
				<?php
				$pm_labels = array(
					'prepayment'  => __( 'Prepayment', 'biscotti-cmp' ),
					'paypal'      => 'PayPal',
					'credit_card' => __( 'Credit Card', 'biscotti-cmp' ),
					'invoice'     => __( 'Invoice', 'biscotti-cmp' ),
					'sepa'        => 'SEPA',
					'klarna'      => 'Klarna',
					'sofort'      => 'Sofort',
				);
				foreach ( $pm_labels as $pm => $pm_label ) :
					?>
					<label class="lw-toggle"><input type="checkbox" class="lw-payment-cb" value="<?php echo esc_attr( $pm ); ?>" <?php checked( in_array( $pm, $payment_methods, true ) ); ?> /> <span><?php echo esc_html( $pm_label ); ?></span></label>
				<?php endforeach; ?>
			</div>

			<h4><?php esc_html_e( 'Delivery', 'biscotti-cmp' ); ?></h4>
			<?php $dt = (string) $ev( 'delivery_type', 'physical' ); ?>
			<div class="biscotti-lw-radio-row">
				<label class="lw-radio"><input type="radio" name="lw-deliveryType" value="physical" <?php checked( $dt, 'physical' ); ?> /> 📦 <?php esc_html_e( 'Physical Goods', 'biscotti-cmp' ); ?></label>
				<label class="lw-radio"><input type="radio" name="lw-deliveryType" value="digital" <?php checked( $dt, 'digital' ); ?> /> 💻 <?php esc_html_e( 'Digital / SaaS', 'biscotti-cmp' ); ?></label>
				<label class="lw-radio"><input type="radio" name="lw-deliveryType" value="mixed" <?php checked( $dt, 'mixed' ); ?> /> <?php esc_html_e( 'Both', 'biscotti-cmp' ); ?></label>
			</div>

			<h4><?php esc_html_e( 'Liability', 'biscotti-cmp' ); ?></h4>
			<div class="biscotti-lw-grid-2">
				<p class="biscotti-form-row"><label><?php esc_html_e( 'Liability Cap', 'biscotti-cmp' ); ?></label>
					<select id="lw-liabilityCap" class="biscotti-svc-input">
						<?php $lc = (string) $ev( 'liability_cap', 'contract_value' ); ?>
						<option value="contract_value" <?php selected( $lc, 'contract_value' ); ?>><?php esc_html_e( 'Contract Value', 'biscotti-cmp' ); ?></option>
						<option value="unlimited" <?php selected( $lc, 'unlimited' ); ?>><?php esc_html_e( 'Unlimited', 'biscotti-cmp' ); ?></option>
						<option value="fixed" <?php selected( $lc, 'fixed' ); ?>><?php esc_html_e( 'Fixed Amount', 'biscotti-cmp' ); ?></option>
					</select>
				</p>
				<p class="biscotti-form-row"><label class="lw-cb"><input type="checkbox" id="lw-retentionOfTitle" <?php checked( false !== $ev( 'retention_of_title', true ) ); ?> /> <?php esc_html_e( 'Retention of Title', 'biscotti-cmp' ); ?></label></p>
			</div>

			<?php
			// Full AGB questionnaire catalog — rendered inline so the single Legal
			// Wizard owns the whole flow (mirrors the Cloud app, where the Contract
			// step IS the AGB questionnaire). Fed by the get-agb-catalog response
			// that get_page_data('legal-wizard') merges into $data['agb']. The
			// discrete contract fields above persist via save-legal-entity; the
			// catalog persists via save-agb-data (legalEntity.agbData) — both are
			// consumed server-side, so nothing is lost.
			$agb = ( isset( $data['agb'] ) && is_array( $data['agb'] ) ) ? $data['agb'] : array();
			include __DIR__ . '/partials/agb-catalog.php';
			?>
		</div>
	</div>
	<?php endif; ?>

	<!-- STEP: Tech -->
	<div class="biscotti-lw-panel" data-id="tech">
		<div class="biscotti-card">
			<h3>⚙️ <?php esc_html_e( 'Tech Stack', 'biscotti-cmp' ); ?></h3>
			<p class="description"><?php esc_html_e( 'Run a cookie scan to automatically detect services. Detected services are included in your legal documents.', 'biscotti-cmp' ); ?></p>
			<p><a href="<?php echo esc_url( admin_url( 'admin.php?page=biscotti-tools' ) ); ?>" class="button">🔍 <?php esc_html_e( 'Go to Cookie Scanner', 'biscotti-cmp' ); ?> &rarr;</a>
			<a href="<?php echo esc_url( admin_url( 'admin.php?page=biscotti-services' ) ); ?>" class="button"><?php esc_html_e( 'Manage Services', 'biscotti-cmp' ); ?> &rarr;</a></p>
		</div>
	</div>

	<!-- STEP: Social -->
	<div class="biscotti-lw-panel" data-id="social">
		<div class="biscotti-card">
			<h3>📱 <?php esc_html_e( 'Social Media', 'biscotti-cmp' ); ?></h3>
			<p class="description"><?php esc_html_e( 'Select your active social media platforms. Facebook and Instagram add joint-controller clauses to your privacy policy.', 'biscotti-cmp' ); ?></p>
			<div class="biscotti-lw-toggle-grid">
				<?php foreach ( $social_platforms as $sp_id => $sp ) : ?>
					<label class="lw-toggle"><input type="checkbox" class="lw-social-cb" value="<?php echo esc_attr( $sp_id ); ?>" <?php checked( in_array( $sp_id, $social_profiles, true ) ); ?> /> <span><?php echo esc_html( $sp[0] . ' ' . $sp[1] ); ?></span></label>
				<?php endforeach; ?>
			</div>
		</div>
	</div>

	<?php if ( ! $is_blog ) : ?>
	<!-- STEP: AVV -->
	<div class="biscotti-lw-panel" data-id="avv">
		<div class="biscotti-card">
			<h3>📋 <?php esc_html_e( 'AVV / Data Processing Agreement', 'biscotti-cmp' ); ?></h3>
			<p class="description"><?php esc_html_e( 'Configure the data categories processed. These inputs are used when generating the AVV/DPA document.', 'biscotti-cmp' ); ?></p>
			<?php
			$dc           = ( isset( $e['dataCategories'] ) && is_array( $e['dataCategories'] ) ) ? $e['dataCategories'] : array();
			$avv_cats     = array(
				'contact_data'   => __( 'Contact Data', 'biscotti-cmp' ),
				'usage_data'     => __( 'Usage Data', 'biscotti-cmp' ),
				'content_data'   => __( 'Content Data', 'biscotti-cmp' ),
				'financial_data' => __( 'Financial Data', 'biscotti-cmp' ),
				'contract_data'  => __( 'Contract Data', 'biscotti-cmp' ),
			);
			?>
			<h4><?php esc_html_e( 'Data Categories', 'biscotti-cmp' ); ?></h4>
			<div class="biscotti-lw-toggle-grid">
				<?php foreach ( $avv_cats as $ac => $ac_label ) : ?>
					<label class="lw-toggle"><input type="checkbox" class="lw-avv-cat-cb" value="<?php echo esc_attr( $ac ); ?>" <?php checked( in_array( $ac, $dc, true ) ); ?> /> <span><?php echo esc_html( $ac_label ); ?></span></label>
				<?php endforeach; ?>
			</div>
		</div>
	</div>
	<?php endif; ?>

	<!-- STEP: Documents -->
	<div class="biscotti-lw-panel" data-id="documents">
		<div class="biscotti-card">
			<h3>⚠️ <?php esc_html_e( 'Disclaimer', 'biscotti-cmp' ); ?></h3>
			<div class="biscotti-lw-disclaimer">
				<p><?php esc_html_e( 'AI-generated documents do not constitute legal advice. You should have the generated documents reviewed by a qualified lawyer. No liability is assumed for the accuracy or completeness of the generated content.', 'biscotti-cmp' ); ?></p>
				<label class="lw-cb"><input type="checkbox" id="lw-disclaimerAccepted" /> <?php esc_html_e( 'I have read and understood the disclaimer.', 'biscotti-cmp' ); ?></label>
			</div>
		</div>
		<div class="biscotti-card" id="lw-gen-card" style="opacity:0.5;pointer-events:none;">
			<h3>📄 <?php esc_html_e( 'Generate Documents', 'biscotti-cmp' ); ?></h3>
			<table class="widefat biscotti-data-table">
				<thead><tr>
					<th><?php esc_html_e( 'Document', 'biscotti-cmp' ); ?></th>
					<th><?php esc_html_e( 'Status', 'biscotti-cmp' ); ?></th>
					<th><?php esc_html_e( 'Shortcode', 'biscotti-cmp' ); ?></th>
					<th></th>
				</tr></thead>
				<tbody>
					<?php foreach ( $gen_doc_types as $type => $label ) :
						$ver       = isset( $doc_versions[ $type ] ) ? $doc_versions[ $type ] : 0;
						$shortcode = sprintf( '[biscotti-document type="%s"]', strtolower( $type ) );
						?>
						<tr>
							<td><strong><?php echo esc_html( $label ); ?></strong></td>
							<td class="lw-doc-status">
								<?php if ( $ver ) : ?>
									<span class="biscotti-pill biscotti-pill-green">v<?php echo esc_html( $ver ); ?></span>
								<?php else : ?>
									<span class="biscotti-pill biscotti-pill-gray">—</span>
								<?php endif; ?>
							</td>
							<td><code class="biscotti-doc-sc"><?php echo esc_html( $shortcode ); ?></code></td>
							<td><button type="button" class="button button-small lw-gen-btn" data-type="<?php echo esc_attr( $type ); ?>"><?php echo $ver ? '🔄 ' . esc_html__( 'Regenerate', 'biscotti-cmp' ) : '✨ ' . esc_html__( 'Generate', 'biscotti-cmp' ); ?></button></td>
						</tr>
					<?php endforeach; ?>
				</tbody>
			</table>
			<p><a href="<?php echo esc_url( admin_url( 'admin.php?page=biscotti-documents' ) ); ?>" class="button"><?php esc_html_e( 'View & Publish Documents', 'biscotti-cmp' ); ?> &rarr;</a></p>
			<div id="lw-gen-status" class="biscotti-save-status" role="status"></div>
		</div>
	</div>

	<!-- Navigation -->
	<div class="biscotti-lw-nav">
		<button type="button" id="lw-btn-back" class="button" style="display:none;">&larr; <?php esc_html_e( 'Back', 'biscotti-cmp' ); ?></button>
		<span id="lw-nav-status" class="biscotti-save-status" role="status"></span>
		<button type="button" id="lw-btn-next" class="button button-primary"><?php esc_html_e( 'Next', 'biscotti-cmp' ); ?> &rarr;</button>
	</div>

	<script type="application/json" id="biscotti-lw-data"><?php echo wp_json_encode( $wizard_data ); ?></script>
	<script type="application/json" id="biscotti-lw-schema"><?php echo wp_json_encode( $lw_schema ); ?></script>
	<?php // Jurisdiction-specific local-requirements questions (single source) for first paint + their saved answers for pre-fill. JS re-fetches on jurisdiction change. ?>
	<script type="application/json" id="biscotti-lw-local-questions"><?php echo wp_json_encode( ( isset( $data['localQuestions'] ) && is_array( $data['localQuestions'] ) ) ? $data['localQuestions'] : array() ); ?></script>
	<script type="application/json" id="biscotti-lw-local-answers"><?php echo wp_json_encode( array(
		'jurisdictionAnswers'       => ( isset( $e['jurisdictionAnswers'] ) && is_array( $e['jurisdictionAnswers'] ) ) ? $e['jurisdictionAnswers'] : (object) array(),
		'visdp_name'                => $ev( 'visdpName' ),
		'visdp_street'              => $ev( 'visdpStreet' ),
		'visdp_zip'                 => $ev( 'visdpZip' ),
		'visdp_city'                => $ev( 'visdpCity' ),
		'visdp_email'               => $ev( 'visdpEmail' ),
		'blog_journalistic_content' => $ec( 'blogJournalisticContent' ),
	) ); ?></script>
</div>
