/**
 * 初期設定ページ
 *
 * システムに必要な初期設定の状態確認と案内を表示する。
 */
import { useState, useEffect, useCallback } from '@wordpress/element';
import { __, sprintf } from '@wordpress/i18n';
import { Notice, Modal, Button, TextControl, SelectControl, CheckboxControl } from '@wordpress/components';
import apiFetch from '@wordpress/api-fetch';
import GuideSection from '../components/GuideSection';

function CheckItem( { ok, label, description, warning } ) {
	return (
		<div className="conf-manager-setup__item">
			<div className="conf-manager-setup__item-header">
				<span className={ `conf-manager-setup__status ${ ok ? 'is-ok' : ( warning ? 'is-warning' : 'is-error' ) }` }>
					{ ok ? '✓' : ( warning ? '!' : '✗' ) }
				</span>
				<strong>{ label }</strong>
			</div>
			{ description && <p className="conf-manager-setup__item-desc">{ description }</p> }
		</div>
	);
}

function Section( { title, children } ) {
	return (
		<div className="conf-manager-setup__section">
			<h3>{ title }</h3>
			{ children }
		</div>
	);
}

/**
 * 暗号化キー設定モーダル
 */
function EncryptionModal( { isOpen, onClose, keySet, keyHash, keySource } ) {
	if ( ! isOpen ) {
		return null;
	}

	return (
		<Modal
			title={ __( 'About the Encryption Key', 'conferencemanager' ) }
			onRequestClose={ onClose }
			className="conf-manager-modal--wide conf-manager-encryption-modal"
		>
			{ /* メリット */ }
			<div className="conf-manager-encryption-modal__section">
				<h3>{ __( 'What is Encryption?', 'conferencemanager' ) }</h3>
				<p>
					{ __( 'This plugin encrypts personal data such as email addresses, phone numbers, and addresses using AES-256-GCM before storing them in the database.', 'conferencemanager' ) }
				</p>
			</div>

			<div className="conf-manager-encryption-modal__section">
				<h3>{ __( 'Benefits of Encryption', 'conferencemanager' ) }</h3>
				<ul className="conf-manager-encryption-modal__benefits">
					<li>
						<strong>{ __( 'Compliance with data protection regulations and GDPR', 'conferencemanager' ) }</strong>
						<span>{ keySource === 'config'
							? __( 'The key is kept outside the database, so encrypted personal data stays unreadable even if the database alone is compromised.', 'conferencemanager' )
							: __( 'Encrypted personal data cannot be read without the encryption key. With the default setup the key is stored in the database as well, so keep database access and backups restricted.', 'conferencemanager' )
						}</span>
					</li>
					<li>
						<strong>{ __( 'Meets security standards for medical and academic conferences', 'conferencemanager' ) }</strong>
						<span>{ __( 'Meets the high security standards required by academic conferences.', 'conferencemanager' ) }</span>
					</li>
					<li>
						<strong>{ __( 'Zero operational overhead', 'conferencemanager' ) }</strong>
						<span>{ __( 'Encryption and decryption are handled automatically. It does not affect admin panel operations.', 'conferencemanager' ) }</span>
					</li>
				</ul>
			</div>

			<div className="conf-manager-encryption-modal__section">
				<h3>{ __( 'How It Works', 'conferencemanager' ) }</h3>
				<div className="conf-manager-encryption-modal__diagram">
					<div className="conf-manager-encryption-modal__diagram-step">
						<span className="conf-manager-encryption-modal__diagram-label">{ __( 'Input Data', 'conferencemanager' ) }</span>
						<code>user@example.com</code>
					</div>
					<span className="conf-manager-encryption-modal__diagram-arrow">→</span>
					<div className="conf-manager-encryption-modal__diagram-step is-highlight">
						<span className="conf-manager-encryption-modal__diagram-label">AES-256-GCM</span>
						<span className="conf-manager-encryption-modal__diagram-sub">{ __( 'Transform with Encryption Key', 'conferencemanager' ) }</span>
					</div>
					<span className="conf-manager-encryption-modal__diagram-arrow">→</span>
					<div className="conf-manager-encryption-modal__diagram-step">
						<span className="conf-manager-encryption-modal__diagram-label">{ __( 'Database', 'conferencemanager' ) }</span>
						<code>a3f8c1...</code>
					</div>
				</div>
				<ul className="conf-manager-encryption-modal__features">
					<li>{ __( 'Encrypted with a unique random nonce each time — ciphertext differs even for the same data', 'conferencemanager' ) }</li>
					<li>{ __( 'Tamper detection (GCM mode) — automatically detects unauthorized modifications', 'conferencemanager' ) }</li>
					<li>{ __( 'Uses HKDF-SHA256 for key derivation — safely generates encryption keys from the master key', 'conferencemanager' ) }</li>
				</ul>
			</div>

			{ /* 設定状況: config（wp-config.php）の場合 */ }
			{ keySet && keySource === 'config' && (
				<div className="conf-manager-encryption-modal__section is-success">
					<h3>{ __( 'Configuration Status', 'conferencemanager' ) }</h3>
					<p>
						<span className="conf-manager-setup__status is-ok">✓</span>{ ' ' }
						{ __( 'Encryption key is set in wp-config.php (most secure method).', 'conferencemanager' ) }
					</p>
					{ keyHash && (
						<p className="conf-manager-encryption-modal__key-id">
							{ __( 'Key identifier:', 'conferencemanager' ) } <code>{ keyHash }</code>
						</p>
					) }
					<div className="conf-manager-encryption-modal__warning">
						<strong>{ __( 'Important:', 'conferencemanager' ) }</strong>{ ' ' }
						{ __( 'Never change the encryption key. Changing it will make all encrypted data (email addresses, phone numbers, addresses, etc.) permanently unrecoverable.', 'conferencemanager' ) }
					</div>
				</div>
			) }

			{ /* 設定状況: database（自動生成）の場合 */ }
			{ keySet && keySource === 'database' && (
				<div className="conf-manager-encryption-modal__section is-success">
					<h3>{ __( 'Configuration Status', 'conferencemanager' ) }</h3>
					<p>
						<span className="conf-manager-setup__status is-ok">✓</span>{ ' ' }
						{ __( 'Encryption is active. Personal data is protected with an auto-generated key.', 'conferencemanager' ) }
					</p>
					{ keyHash && (
						<p className="conf-manager-encryption-modal__key-id">
							{ __( 'Key identifier:', 'conferencemanager' ) } <code>{ keyHash }</code>
						</p>
					) }

					<div className="conf-manager-encryption-modal__upgrade">
						<h4>{ __( 'For Enhanced Security (Optional)', 'conferencemanager' ) }</h4>
						<p>
							{ __( 'Currently, the encryption key is stored in the database. Moving it to wp-config.php protects the key even if the database is compromised.', 'conferencemanager' ) }
						</p>
						<table className="conf-manager-encryption-modal__comparison">
							<thead>
								<tr>
									<th></th>
									<th>{ __( 'Current Method (Auto)', 'conferencemanager' ) }</th>
									<th>{ __( 'wp-config.php (Recommended)', 'conferencemanager' ) }</th>
								</tr>
							</thead>
							<tbody>
								<tr>
									<td>{ __( 'Setup Effort', 'conferencemanager' ) }</td>
									<td>{ __( 'None (Automatic)', 'conferencemanager' ) }</td>
									<td>{ __( 'File editing required', 'conferencemanager' ) }</td>
								</tr>
								<tr>
									<td>{ __( 'If DB is compromised', 'conferencemanager' ) }</td>
									<td>{ __( 'Key may also be exposed', 'conferencemanager' ) }</td>
									<td><strong>{ __( 'Key remains safe', 'conferencemanager' ) }</strong></td>
								</tr>
								<tr>
									<td>{ __( 'If server is compromised', 'conferencemanager' ) }</td>
									<td>{ __( 'Same risk level', 'conferencemanager' ) }</td>
									<td>{ __( 'Same risk level', 'conferencemanager' ) }</td>
								</tr>
							</tbody>
						</table>
						<p className="conf-manager-setup__note">
							{ __( '* Encryption works without migration. There is no issue for normal operations.', 'conferencemanager' ) }
						</p>

						<details className="conf-manager-encryption-modal__migrate-details">
							<summary>{ __( 'View migration steps for wp-config.php', 'conferencemanager' ) }</summary>
							<div className="conf-manager-encryption-modal__step">
								<h4>{ __( 'Step 1: Check the current key', 'conferencemanager' ) }</h4>
								<p>{ __( 'The encryption key stored in the database is in the wp_options table. You can retrieve it by running the following SQL in phpMyAdmin or similar:', 'conferencemanager' ) }</p>
								<div className="conf-manager-encryption-modal__code-block">
									<pre>{ "SELECT option_value FROM wp_options WHERE option_name = 'conf_manager_encryption_key';" }</pre>
								</div>
							</div>
							<div className="conf-manager-encryption-modal__step">
								<h4>{ __( 'Step 2: Add to wp-config.php', 'conferencemanager' ) }</h4>
								<p>
									{ __( 'Using the retrieved key, add the following to wp-config.php above', 'conferencemanager' ) }
									{ ' ' }<code>/* That&apos;s all, stop editing! */</code>{ ' ' }
									{ __( ':', 'conferencemanager' ) }
								</p>
								<div className="conf-manager-encryption-modal__code-block">
									<pre>{ `define( 'CONF_MANAGER_ENCRYPTION_KEY', '${ __( 'paste the copied key here', 'conferencemanager' ) }' );` }</pre>
								</div>
								<p className="conf-manager-setup__note">
									{ __( '* The wp-config.php constant takes priority, so the DB key will be automatically ignored after migration.', 'conferencemanager' ) }
								</p>
							</div>
						</details>
					</div>

					<div className="conf-manager-encryption-modal__warning">
						<strong>{ __( 'Important:', 'conferencemanager' ) }</strong>{ ' ' }
						{ __( 'Never change or delete the encryption key. Changing it will make encrypted data permanently unrecoverable.', 'conferencemanager' ) }
					</div>
				</div>
			) }
		</Modal>
	);
}

export default function Setup() {
	const [ status, setStatus ] = useState( null );
	const [ loading, setLoading ] = useState( true );
	const [ showEncryptionModal, setShowEncryptionModal ] = useState( false );
	const [ paymentMethods, setPaymentMethods ] = useState( [ 'bank' ] );
	const [ taxRegistrationNo, setTaxRegistrationNo ] = useState( '' );
	const [ paymentSaving, setPaymentSaving ] = useState( false );
	const [ paymentNotice, setPaymentNotice ] = useState( null );
	const [ adminNotifyRegistration, setAdminNotifyRegistration ] = useState( true );
	const [ notificationEmail, setNotificationEmail ] = useState( '' );
	const [ requireApproval, setRequireApproval ] = useState( false );
	// 会員種別に前置する学会の略称。空 ＝ 何も付けない（既定）。
	const [ societyShortName, setSocietyShortName ] = useState( '' );
	const [ smtpHost, setSmtpHost ] = useState( '' );
	const [ smtpPort, setSmtpPort ] = useState( '587' );
	const [ smtpUser, setSmtpUser ] = useState( '' );
	const [ smtpPassword, setSmtpPassword ] = useState( '' );
	const [ smtpSecure, setSmtpSecure ] = useState( 'tls' );
	const [ notifSaving, setNotifSaving ] = useState( false );
	const [ notifNotice, setNotifNotice ] = useState( null );
	const [ smtpTesting, setSmtpTesting ] = useState( false );

	const fetchStatus = useCallback( () => {
		apiFetch( { path: '/conf-manager/v1/admin/system-status' } )
			.then( ( data ) => {
				setStatus( data );
				if ( data.payment_settings ) {
					setPaymentMethods( data.payment_settings.methods || [ 'bank' ] );
					setTaxRegistrationNo( data.payment_settings.tax_registration_no || '' );
				}
				if ( data.notification_settings ) {
					setAdminNotifyRegistration( !! data.notification_settings.admin_notify_registration );
					setNotificationEmail( data.notification_settings.notification_email || '' );
					setRequireApproval( !! data.notification_settings.require_approval );
					setSocietyShortName( data.notification_settings.society_short_name || '' );
				}
				if ( data.smtp && data.smtp.source === 'database' ) {
					setSmtpHost( data.smtp.host || '' );
					setSmtpPort( String( data.smtp.port || 587 ) );
					setSmtpUser( data.smtp.user || '' );
					setSmtpSecure( data.smtp.secure || 'tls' );
				}
			} )
			.catch( () => {} )
			.finally( () => setLoading( false ) );
	}, [] );

	useEffect( () => {
		fetchStatus();
	}, [ fetchStatus ] );

	if ( loading ) {
		return (
			<div>
				<h2>{ __( 'Setup', 'conferencemanager' ) }</h2>
				<p>{ __( 'Loading...', 'conferencemanager' ) }</p>
			</div>
		);
	}

	if ( ! status ) {
		return (
			<div>
				<h2>{ __( 'Setup', 'conferencemanager' ) }</h2>
				<p>{ __( 'Failed to retrieve system status.', 'conferencemanager' ) }</p>
			</div>
		);
	}

	const checklist = [
		{
			ok: !! status.encryption?.key_set,
			section: __( '1. Encryption (Data Protection)', 'conferencemanager' ),
			label: __( 'Encryption key is not set. Please reactivate the plugin.', 'conferencemanager' ),
		},
		{
			ok: !! status.timezone?.is_set,
			section: __( '2. Timezone Settings', 'conferencemanager' ),
			label: __( 'The timezone is not set. Please select "Tokyo" (or your timezone) under WordPress Settings → General → Timezone.', 'conferencemanager' ),
		},
		{
			ok: !! status.pages?.registration,
			section: __( '3. Pages (Shortcodes)', 'conferencemanager' ),
			label: __( 'The registration page was not found. Reactivate the plugin to create it automatically, or create a page containing the [conf_manager] shortcode.', 'conferencemanager' ),
		},
		{
			ok: !! status.pages?.mypage,
			section: __( '3. Pages (Shortcodes)', 'conferencemanager' ),
			label: __( 'My Page was not found. Reactivate the plugin to create it automatically, or create a page containing the [conf_manager view="mypage"] shortcode.', 'conferencemanager' ),
		},
		{
			ok: !! status.any_font_exists,
			section: __( '4. PDF Fonts', 'conferencemanager' ),
			label: __( 'The Japanese fonts for PDF generation are not installed. Please install them from "Font Download" on the Dashboard.', 'conferencemanager' ),
		},
	];
	const pendingItems = checklist.filter( ( item ) => ! item.ok );
	const allOk = pendingItems.length === 0;

	return (
		<div>
			<div className="conf-manager-page-header">
				<h2>{ __( 'Setup', 'conferencemanager' ) }</h2>
			</div>

			<GuideSection
				hero={ {
					title: __( 'Before You Start', 'conferencemanager' ),
					description: __( 'Complete the initial setup for security and PDF generation. You can start operations once all checks pass.', 'conferencemanager' ),
				} }
				cards={ [
					{
						icon: <svg viewBox="0 0 24 24" width="32" height="32" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M21 2l-2 2m-7.61 7.61a5.5 5.5 0 11-7.778 7.778 5.5 5.5 0 017.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4" /></svg>,
						title: __( 'Encryption Key Setup', 'conferencemanager' ),
						description: __( 'Set up the AES-256-GCM encryption key to protect member personal data.', 'conferencemanager' ),
						tips: [
							__( 'Set as a constant in wp-config.php', 'conferencemanager' ),
							__( 'Cannot be changed once set (data would become unrecoverable)', 'conferencemanager' ),
							__( 'Always keep a backup in a safe location', 'conferencemanager' ),
						],
					},
					{
						icon: <svg viewBox="0 0 24 24" width="32" height="32" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8z" /><polyline points="14 2 14 8 20 8" /><line x1="16" y1="13" x2="8" y2="13" /><line x1="16" y1="17" x2="8" y2="17" /></svg>,
						title: __( 'PDF Font Installation', 'conferencemanager' ),
						description: __( 'Install the Japanese fonts required for generating invoice, receipt, and certificate PDFs.', 'conferencemanager' ),
						tips: [
							__( 'Can be auto-downloaded from the Dashboard', 'conferencemanager' ),
							__( 'Two fonts required: IPAex Gothic and IPAex Mincho', 'conferencemanager' ),
							__( 'Open source license — safe for commercial use', 'conferencemanager' ),
						],
					},
					{
						icon: <svg viewBox="0 0 24 24" width="32" height="32" fill="none" stroke="currentColor" strokeWidth="1.5"><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" /><polyline points="22 6 12 13 2 6" /></svg>,
						title: __( 'Email Preferences', 'conferencemanager' ),
						description: __( 'Configure SMTP settings required for sending automatic emails such as registration confirmations and payment notifications.', 'conferencemanager' ),
						tips: [
							__( 'Configure in WordPress admin under Settings → SMTP', 'conferencemanager' ),
							__( 'For Xserver, check SMTP details in the server panel', 'conferencemanager' ),
							__( 'Verify by sending a test email', 'conferencemanager' ),
						],
					},
				] }
			/>

			{ allOk && (
				<div className="conf-manager-setup__complete">
					<div className="conf-manager-setup__complete-icon" aria-hidden="true">
						<svg viewBox="0 0 24 24" width="40" height="40" fill="none" stroke="currentColor" strokeWidth="2"><path d="M22 11.08V12a10 10 0 11-5.93-9.14" /><polyline points="22 4 12 14.01 9 11.01" /></svg>
					</div>
					<div>
						<h3>{ __( 'All initial setup is complete', 'conferencemanager' ) }</h3>
						<p>{ __( 'Security, PDF generation, and email delivery settings are all working correctly. You can start managing events.', 'conferencemanager' ) }</p>
						<ul>
							<li>{ __( 'Always back up the encryption key to a safe location — never lose it', 'conferencemanager' ) }</li>
							<li>{ __( 'Font files may need to be re-installed after server migration', 'conferencemanager' ) }</li>
							<li>{ __( 'After changing SMTP settings, verify by sending a test email', 'conferencemanager' ) }</li>
						</ul>
					</div>
				</div>
			) }

			{ !allOk && (
				<div className="conf-manager-setup__incomplete">
					<div className="conf-manager-setup__complete-icon" aria-hidden="true">
						<svg viewBox="0 0 24 24" width="40" height="40" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="12" cy="12" r="10" /><line x1="12" y1="8" x2="12" y2="12" /><line x1="12" y1="16" x2="12.01" y2="16" /></svg>
					</div>
					<div>
						<h3>
							{ sprintf(
								/* translators: %d: number of pending setup items */
								__( '%d setup item(s) are incomplete', 'conferencemanager' ),
								pendingItems.length
							) }
						</h3>
						<p>{ __( 'Please configure the items below. Once all checks pass, you are ready to go live.', 'conferencemanager' ) }</p>
						<ul className="conf-manager-setup__incomplete-list">
							{ pendingItems.map( ( item, idx ) => (
								<li key={ idx }>
									<strong>{ item.section }</strong> — { item.label }
								</li>
							) ) }
						</ul>
					</div>
				</div>
			) }

			{ /* 1. 暗号化 */ }
			<Section title={ __( '1. Encryption (Data Protection)', 'conferencemanager' ) }>
				{ /*
				  ⚠️ 3 状態にする。既定（wp-config.php に定数が無い）の環境では、
				  Encryption::get_master_key() が鍵を自動生成して **wp_options に保存**する
				  ＝ **暗号文と鍵が同じデータベースに並ぶ**。以前はこの状態を緑のチェックと
				  「追加の設定は不要です」で伝えていたが、**バックアップが流出したときの
				  利得がほとんど無い状態を「問題なし」と言い切っていた**。
				  ⚠️ ✗（赤）にはしない。暗号化自体は効いている（鍵が外に出ていないだけ）ので、
				  赤にすると「壊れている」と読まれる。
				  ⚠️ 管理画面全体の通知（admin notice）にはしない。**既定の構成すべてで出る**ため。
				*/ }
				<CheckItem
					ok={ status.encryption?.key_set && 'config' === status.encryption?.key_source }
					warning={ status.encryption?.key_set && 'config' !== status.encryption?.key_source }
					label={ status.encryption?.key_set
						? ( status.encryption?.key_source === 'config'
							? __( 'Encryption key — set in wp-config.php', 'conferencemanager' )
							: __( 'Encryption key — auto-generated (stored in the database)', 'conferencemanager' )
						)
						: __( 'Encryption Key', 'conferencemanager' )
					}
					description={ status.encryption?.key_set
						? ( status.encryption?.key_source === 'config'
							? __( 'Personal data is encrypted with AES-256-GCM. The key is stored outside the database, which is the most secure setup.', 'conferencemanager' )
							: __( 'Personal data is encrypted with AES-256-GCM. However, the key is stored in the database as well, so encryption offers limited protection if a database backup is leaked. Define CONF_MANAGER_ENCRYPTION_KEY in wp-config.php to move the key out of the database.', 'conferencemanager' )
						)
						: __( 'Encryption key is not set. Please reactivate the plugin.', 'conferencemanager' )
					}
				/>
				<div style={ { marginLeft: 30, marginTop: 4 } }>
					<Button
						variant="link"
						onClick={ () => setShowEncryptionModal( true ) }
						isSmall
					>
						{ __( 'Learn more about encryption', 'conferencemanager' ) }
					</Button>
				</div>
			</Section>

			<EncryptionModal
				isOpen={ showEncryptionModal }
				onClose={ () => setShowEncryptionModal( false ) }
				keySet={ status.encryption?.key_set }
				keyHash={ status.encryption?.key_hash }
				keySource={ status.encryption?.key_source }
			/>

			{ /* 2. タイムゾーン */ }
			<Section title={ __( '2. Timezone Settings', 'conferencemanager' ) }>
				<CheckItem
					ok={ status.timezone?.is_set }
					label={ `${ __( 'Timezone', 'conferencemanager' ) }: ${ status.timezone?.display || __( 'Not configured', 'conferencemanager' ) }` }
					description={ status.timezone?.is_set
						? __( 'The timezone is set. Event times and early-bird pricing deadlines are evaluated using this timezone.', 'conferencemanager' )
						: __( 'Please set the timezone under WordPress Admin → Settings → General → Timezone. For Japan, select "Tokyo". It is used to evaluate event times and early-bird pricing deadlines.', 'conferencemanager' )
					}
				/>
				{ status.timezone?.is_set && (
					<p className="conf-manager-setup__note">
						{ __( 'To change:', 'conferencemanager' ) } <a href="options-general.php">{ __( 'Settings → General', 'conferencemanager' ) }</a>
					</p>
				) }
			</Section>

			{ /* 3. 固定ページ */ }
			<Section title={ __( '3. Pages (Shortcodes)', 'conferencemanager' ) }>
				<CheckItem
					ok={ status.pages?.registration }
					label={ __( 'Registration Page', 'conferencemanager' ) }
					description={ status.pages?.registration
						? __( 'A published page containing the [conf_manager] shortcode was found.', 'conferencemanager' )
						: __( 'Create a page, enter [conf_manager] in the content, and publish it. Recommended slug: /c-registration/', 'conferencemanager' )
					}
				/>
				<CheckItem
					ok={ status.pages?.mypage }
					label={ __( 'My Page', 'conferencemanager' ) }
					description={ status.pages?.mypage
						? __( 'A published page containing the [conf_manager view="mypage"] shortcode was found.', 'conferencemanager' )
						: __( 'Create a page, enter [conf_manager view="mypage"] in the content, and publish it. Recommended slug: /c-mypage/', 'conferencemanager' )
					}
				/>
			</Section>

			{ /* 4. フォント */ }
			<Section title={ __( '4. PDF Fonts', 'conferencemanager' ) }>
				<CheckItem
					ok={ status.fonts?.ipaexg?.exists }
					label="IPAexゴシック (ipaexg.ttf)"
					description={ status.fonts?.ipaexg?.exists
						? null
						: __( 'Can be downloaded using the "Download IPAex Fonts" button on the Dashboard.', 'conferencemanager' )
					}
				/>
				<CheckItem
					ok={ status.fonts?.ipaexm?.exists }
					label="IPAex明朝 (ipaexm.ttf)"
				/>
				<CheckItem
					ok={ status.fonts?.notosansjp?.exists }
					label="Noto Sans JP"
				/>
				{ ! status.any_font_exists && (
					<p className="conf-manager-setup__note">
						{ __( 'Japanese fonts are required for PDF generation (invoices, receipts, certificates). Download them from the Dashboard.', 'conferencemanager' ) }
					</p>
				) }
			</Section>

			{ /* 5. メール配信設定 */ }
			<Section title={ __( '5. Email delivery settings', 'conferencemanager' ) }>
				<div className="conf-manager-setup__mail-recommend">
					<h4>{ __( 'Recommended Setup (Anti-spoofing & Deliverability)', 'conferencemanager' ) }</h4>
					<p>{ __( 'To prevent conference emails from being flagged as spam, the following setup is strongly recommended.', 'conferencemanager' ) }</p>
					<div className="conf-manager-setup__mail-recommend-cards">
						<div className="conf-manager-setup__mail-recommend-card">
							<span className="conf-manager-setup__mail-recommend-step">1</span>
							<div>
								<strong>{ __( 'Use an email address with your own domain', 'conferencemanager' ) }</strong>
								<p>{ __( 'Set the FROM address to the same domain as your site (e.g., info@your-conference.jp). Free email services like Gmail may fail domain authentication and be flagged as spoofing.', 'conferencemanager' ) }</p>
							</div>
						</div>
						<div className="conf-manager-setup__mail-recommend-card">
							<span className="conf-manager-setup__mail-recommend-step">2</span>
							<div>
								<strong>{ __( 'Send via authenticated server using an SMTP plugin', 'conferencemanager' ) }</strong>
								<p>{ __( 'WordPress default wp_mail() uses the server\'s sendmail, which is easily spoofed and often rejected. SMTP authentication establishes you as a legitimate sender.', 'conferencemanager' ) }</p>
							</div>
						</div>
						<div className="conf-manager-setup__mail-recommend-card">
							<span className="conf-manager-setup__mail-recommend-step">3</span>
							<div>
								<strong>{ __( 'Set up SPF + DKIM + DMARC', 'conferencemanager' ) }</strong>
								<p>{ __( 'These three together provide sender legitimacy, tamper prevention, and failure policy — preventing email spoofing. Since February 2024, Gmail rejects emails from senders without these settings.', 'conferencemanager' ) }</p>
							</div>
						</div>
					</div>
				</div>

				<CheckItem
					ok={ status.mail?.smtp_plugin }
					warning={ true }
					label={ status.mail?.smtp_plugin
						? `${ __( 'SMTP plugin:', 'conferencemanager' ) } ${ status.mail?.smtp_plugin_name }`
						: __( 'SMTP plugin: Not detected', 'conferencemanager' )
					}
					description={ status.mail?.smtp_plugin
						? __( 'SMTP plugin is active. Email deliverability is improved.', 'conferencemanager' )
						: __( 'An SMTP plugin is strongly recommended for better email deliverability. The default wp_mail() is often flagged as spam.', 'conferencemanager' )
					}
				/>

				{ ! status.mail?.smtp_plugin && (
					<div className="conf-manager-setup__mail-guide">
						<h4>{ __( 'Recommended SMTP Plugins', 'conferencemanager' ) }</h4>
						<table className="widefat striped">
							<thead>
								<tr>
									<th>{ __( 'Plugin', 'conferencemanager' ) }</th>
									<th>{ __( 'Features', 'conferencemanager' ) }</th>
									<th>{ __( 'Supported Services', 'conferencemanager' ) }</th>
								</tr>
							</thead>
							<tbody>
								<tr>
									<td><strong>WP Mail SMTP</strong></td>
									<td>{ __( 'Most popular and stable. Free version covers basic needs', 'conferencemanager' ) }</td>
									<td>Gmail, SendGrid, Mailgun, Amazon SES, SMTP</td>
								</tr>
								<tr>
									<td><strong>Post SMTP</strong></td>
									<td>{ __( 'Includes send logs and resend. Completely free', 'conferencemanager' ) }</td>
									<td>Gmail API, Mailgun, SendGrid, SMTP</td>
								</tr>
							</tbody>
						</table>
						<p className="conf-manager-setup__note">
							{ __( 'Search and install from WordPress admin → Plugins → Add New.', 'conferencemanager' ) }
						</p>
					</div>
				) }

				<div className="conf-manager-setup__mail-guide">
					<h4>{ __( 'DNS Authentication (SPF / DKIM / DMARC)', 'conferencemanager' ) }</h4>
					<p className="conf-manager-setup__note">
						{ __( 'To prevent emails from being flagged as spam, configure the following DNS authentication records for your sending domain.', 'conferencemanager' ) }
						<br />
						{ status.mail?.domain && (
							<>{ ' ' }{ __( 'Target domain:', 'conferencemanager' ) } <strong>{ status.mail.domain }</strong></>
						) }
					</p>

					<table className="widefat striped">
						<thead>
							<tr>
								<th>{ __( 'Authentication Method', 'conferencemanager' ) }</th>
								<th>{ __( 'Purpose', 'conferencemanager' ) }</th>
								<th>{ __( 'DNS Record Example', 'conferencemanager' ) }</th>
							</tr>
						</thead>
						<tbody>
							<tr>
								<td><strong>SPF</strong></td>
								<td>{ __( 'Proves the legitimacy of the sending server', 'conferencemanager' ) }</td>
								<td>
									<code>TXT @ "v=spf1 +a +mx include:sv*.xserver.jp ~all"</code>
									<br />
									<span className="conf-manager-setup__note">{ __( '* For Xserver. Varies by hosting provider', 'conferencemanager' ) }</span>
								</td>
							</tr>
							<tr>
								<td><strong>DKIM</strong></td>
								<td>{ __( 'Proves the email has not been tampered with', 'conferencemanager' ) }</td>
								<td>
									<span className="conf-manager-setup__note">
										{ __( 'Enable in the server or SMTP service admin panel. Records are auto-generated', 'conferencemanager' ) }
									</span>
								</td>
							</tr>
							<tr>
								<td><strong>DMARC</strong></td>
								<td>{ __( 'Policy for SPF/DKIM failures', 'conferencemanager' ) }</td>
								<td>
									<code>TXT _dmarc "v=DMARC1; p=quarantine; rua=mailto:{ status.mail?.admin_email || 'admin@example.com' }"</code>
								</td>
							</tr>
						</tbody>
					</table>

					<h4 style={ { marginTop: '16px' } }>{ __( 'Setup Steps by Server', 'conferencemanager' ) }</h4>
					<table className="widefat striped">
						<thead>
							<tr>
								<th>{ __( 'Server', 'conferencemanager' ) }</th>
								<th>SPF</th>
								<th>DKIM</th>
								<th>{ __( 'Configuration Location', 'conferencemanager' ) }</th>
							</tr>
						</thead>
						<tbody>
							<tr>
								<td>Xserver</td>
								<td>{ __( 'Auto-configured', 'conferencemanager' ) }</td>
								<td>{ __( 'Enable in Server Panel', 'conferencemanager' ) }</td>
								<td>{ __( 'Server Panel → Email → DKIM Settings', 'conferencemanager' ) }</td>
							</tr>
							<tr>
								<td>{ __( 'Sakura Rental Server', 'conferencemanager' ) }</td>
								<td>{ __( 'Add manually in DNS settings', 'conferencemanager' ) }</td>
								<td>{ __( 'Not supported (SMTP service recommended)', 'conferencemanager' ) }</td>
								<td>{ __( 'Control Panel → Domain → DNS', 'conferencemanager' ) }</td>
							</tr>
							<tr>
								<td>ConoHa WING</td>
								<td>{ __( 'Auto-configured', 'conferencemanager' ) }</td>
								<td>{ __( 'Add manually in DNS settings', 'conferencemanager' ) }</td>
								<td>{ __( 'Control Panel → DNS', 'conferencemanager' ) }</td>
							</tr>
							<tr>
								<td>SendGrid / Mailgun</td>
								<td colSpan="2">{ __( 'Auto-generated with setup guide in service dashboard', 'conferencemanager' ) }</td>
								<td>{ __( 'Service dashboard', 'conferencemanager' ) }</td>
							</tr>
						</tbody>
					</table>

					<h4 style={ { marginTop: '16px' } }>{ __( 'Checklist to Avoid Spam Filtering', 'conferencemanager' ) }</h4>
					<ul className="conf-manager-setup__checklist">
						<li>{ __( 'Install an SMTP plugin and send via authenticated SMTP server', 'conferencemanager' ) }</li>
						<li>{ __( 'Set SPF records in DNS (sender legitimacy)', 'conferencemanager' ) }</li>
						<li>{ __( 'Enable DKIM (email tamper prevention)', 'conferencemanager' ) }</li>
						<li>{ __( 'Set DMARC policy (handling for authentication failures)', 'conferencemanager' ) }</li>
						<li>{ __( 'Use an email address on the same domain as your site for the FROM address', 'conferencemanager' ) }</li>
						<li>{ __( 'Consider dedicated email services like SendGrid for bulk sending', 'conferencemanager' ) }</li>
					</ul>
				</div>
			</Section>

			{ /* 6. 決済手段・オプション設定 */ }
			<Section title={ __( '6. Payment methods and options', 'conferencemanager' ) }>
				<div className="conf-manager-setup__payment-methods">
					<h4 style={ { margin: '0 0 8px' } }>{ __( 'Payment Methods', 'conferencemanager' ) }</h4>
					<p style={ { fontSize: '13px', color: '#50575e', margin: '0 0 12px' } }>
						{ __( 'Select payment methods to show on the registration form. Multiple selections allowed.', 'conferencemanager' ) }
					</p>
					<label className="conf-manager-setup__checkbox">
						<input type="checkbox" checked={ paymentMethods.includes( 'bank' ) }
							onChange={ ( e ) => {
								setPaymentMethods( ( prev ) => e.target.checked ? [ ...prev, 'bank' ] : prev.filter( ( m ) => m !== 'bank' ) );
							} } />
						{ __( 'Bank Transfer', 'conferencemanager' ) }
					</label>

					<div style={ { marginTop: '16px', borderTop: '1px solid #dcdcde', paddingTop: '16px' } }>
						<TextControl
							label={ __( 'Qualified Invoice Issuer Registration Number', 'conferencemanager' ) }
							value={ taxRegistrationNo }
							onChange={ setTaxRegistrationNo }
							placeholder="T1234567890123"
							help={ __( 'Enter your registration number under the Invoice System. It will appear on invoices and receipts.', 'conferencemanager' ) }
						/>
					</div>

					<div style={ { marginTop: '12px' } }>
						<Button
							variant="primary"
							isBusy={ paymentSaving }
							disabled={ paymentSaving }
							onClick={ async () => {
								setPaymentSaving( true );
								setPaymentNotice( null );
								try {
									await apiFetch( {
										path: '/conf-manager/v1/admin/payment-settings',
										method: 'POST',
										data: { methods: paymentMethods, tax_registration_no: taxRegistrationNo },
									} );
									setPaymentNotice( { status: 'success', message: __( 'Payment method settings saved.', 'conferencemanager' ) } );
								} catch ( err ) {
									setPaymentNotice( { status: 'error', message: err.message } );
								} finally {
									setPaymentSaving( false );
								}
							} }
						>
							{ __( 'Save Payment Methods', 'conferencemanager' ) }
						</Button>
						{ paymentNotice && (
							<Notice status={ paymentNotice.status } isDismissible={ false } style={ { marginTop: '8px' } }>
								{ paymentNotice.message }
							</Notice>
						) }
					</div>
				</div>

			</Section>

			<Section title={ __( 'Notification Settings', 'conferencemanager' ) }>
				<CheckboxControl
					label={ __( 'Email admin on new registration', 'conferencemanager' ) }
					checked={ adminNotifyRegistration }
					onChange={ setAdminNotifyRegistration }
					help={ __( 'Send a notification email each time a participant registers for an event.', 'conferencemanager' ) }
				/>
				<TextControl
					label={ __( 'Notification email address(es)', 'conferencemanager' ) }
					type="text"
					value={ notificationEmail }
					onChange={ setNotificationEmail }
					placeholder={ status.admin_email || '' }
					help={ sprintf(
						/* translators: %s: WordPress admin email */
						__( 'Where to send new-registration notices. Separate multiple addresses with commas. Leave blank to use the admin email (%s).', 'conferencemanager' ),
						status.admin_email || ''
					) }
				/>
				<CheckboxControl
					label={ __( 'Require admin approval for self-registration', 'conferencemanager' ) }
					checked={ requireApproval }
					onChange={ setRequireApproval }
					help={ __( 'When enabled, self-registrations will have "pending" status until approved by an admin. Approve or reject from Member Management.', 'conferencemanager' ) }
				/>
				<div style={ { marginTop: '16px', borderTop: '1px solid #dcdcde', paddingTop: '16px' } }>
					<h4>{ __( 'Society Name Prefix', 'conferencemanager' ) }</h4>
					<TextControl
						label={ __( 'Society short name', 'conferencemanager' ) }
						type="text"
						value={ societyShortName }
						onChange={ setSocietyShortName }
						help={ __( 'Shown in front of member types, e.g. "JXX Society_Regular Member". Useful for co-hosted events, where attendees who belong to another society may otherwise read "Regular Member" as their own. Leave blank to show member types unchanged.', 'conferencemanager' ) }
					/>
					{ /* 入力の手間を減らすためのボタン。
					     🔴 「空欄ならサイト名を使う」という既定にはしない。
					        それだとサイト名を変えた瞬間に全画面の表記が変わる。 */ }
					<Button
						variant="secondary"
						onClick={ () => setSocietyShortName( status.mail?.site_name || '' ) }
						disabled={ ! status.mail?.site_name }
					>
						{ __( 'Use site name', 'conferencemanager' ) }
					</Button>
					<p style={ { fontSize: '13px', color: '#50575e', marginTop: '8px' } }>
						{ societyShortName
							? sprintf(
								/* translators: %s: example of a decorated member type, e.g. "JXX Society_Regular Member" */
								__( 'Preview: %s', 'conferencemanager' ),
								`${ societyShortName }_${ __( 'Regular Member', 'conferencemanager' ) }`
							)
							: __( 'Preview: member types are shown as-is.', 'conferencemanager' ) }
					</p>
				</div>

				<div style={ { marginTop: '16px', borderTop: '1px solid #dcdcde', paddingTop: '16px' } }>
					<h4>{ __( 'Email Delivery Settings (SMTP)', 'conferencemanager' ) }</h4>
					<p style={ { fontSize: '13px', color: '#50575e', marginBottom: '12px' } }>
						{ __( 'Send emails via SMTP using your own domain email account. Falls back to PHP mail() if not configured.', 'conferencemanager' ) }
					</p>
					{ status.smtp?.source === 'config' ? (
						<div>
							<p style={ { color: '#00a32a' } }>
								<span className="conf-manager-setup__status is-ok">✓</span>
								{ __( 'SMTP is configured in wp-config.php (recommended).', 'conferencemanager' ) }
							</p>
							<dl style={ { fontSize: '13px', margin: '8px 0' } }>
								<dt style={ { fontWeight: 600, display: 'inline' } }>{ __( 'Host:', 'conferencemanager' ) }</dt>
								<dd style={ { display: 'inline', marginLeft: '4px' } }>{ status.smtp.host }:{ status.smtp.port } ({ status.smtp.secure.toUpperCase() })</dd>
							</dl>
						</div>
					) : (
						<div>
							<div style={ { display: 'grid', gridTemplateColumns: '1fr 100px 100px', gap: '8px', marginBottom: '8px' } }>
								<TextControl
									label={ __( 'SMTP Host', 'conferencemanager' ) }
									value={ smtpHost }
									onChange={ setSmtpHost }
									placeholder="sv12345.xserver.jp"
									__nextHasNoMarginBottom
								/>
								<TextControl
									label={ __( 'Port', 'conferencemanager' ) }
									type="number"
									value={ smtpPort }
									onChange={ setSmtpPort }
									__nextHasNoMarginBottom
								/>
								<SelectControl
									label={ __( 'Encryption', 'conferencemanager' ) }
									value={ smtpSecure }
									onChange={ setSmtpSecure }
									options={ [
										{ label: 'STARTTLS (587)', value: 'tls' },
										{ label: 'SSL/TLS (465)', value: 'ssl' },
									] }
									__nextHasNoMarginBottom
								/>
							</div>
							<div style={ { display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px' } }>
								<TextControl
									label={ __( 'Username (email address)', 'conferencemanager' ) }
									value={ smtpUser }
									onChange={ setSmtpUser }
									placeholder="conference@example.com"
									__nextHasNoMarginBottom
								/>
								<TextControl
									label={ __( 'Password', 'conferencemanager' ) }
									type="password"
									value={ smtpPassword }
									onChange={ setSmtpPassword }
									placeholder={ status.smtp?.configured ? __( '(Already set — enter only to change)', 'conferencemanager' ) : '' }
									__nextHasNoMarginBottom
								/>
							</div>
							<p style={ { fontSize: '12px', color: '#757575', marginTop: '4px' } }>
								{ __( 'Security recommendation: You can also define constants like CONF_MANAGER_SMTP_HOST in wp-config.php.', 'conferencemanager' ) }
							</p>
						</div>
					) }
					<div style={ { marginTop: '8px', display: 'flex', gap: '8px', alignItems: 'center' } }>
						<Button
							variant="secondary"
							isSmall
							isBusy={ smtpTesting }
							disabled={ smtpTesting }
							onClick={ async () => {
								setSmtpTesting( true );
								try {
									const res = await apiFetch( { path: '/conf-manager/v1/admin/smtp-test', method: 'POST' } );
									setNotifNotice( { status: res.success ? 'success' : 'error', message: res.message } );
								} catch ( err ) {
									setNotifNotice( { status: 'error', message: err.message } );
								} finally {
									setSmtpTesting( false );
								}
							} }
						>
							{ __( 'Send Test', 'conferencemanager' ) }
						</Button>
						{ status.mail_bounces_count > 0 && (
							<span style={ { fontSize: '13px', color: '#d63638' } }>
								{ sprintf( __( 'Bounce records: %d', 'conferencemanager' ), status.mail_bounces_count ) }
							</span>
						) }
					</div>
				</div>

				<div style={ { marginTop: '12px' } }>
					<Button
						variant="primary"
						isBusy={ notifSaving }
						disabled={ notifSaving }
						onClick={ async () => {
							setNotifSaving( true );
							setNotifNotice( null );
							try {
								await apiFetch( {
									path: '/conf-manager/v1/admin/notification-settings',
									method: 'POST',
									data: {
									admin_notify_registration: adminNotifyRegistration,
									notification_email: notificationEmail,
									require_approval: requireApproval,
									// ⚠️ 空文字も必ず送る。空にするのが「前置をやめる」唯一の手段。
									society_short_name: societyShortName,
									smtp_host: smtpHost,
									smtp_port: parseInt( smtpPort ) || 587,
									smtp_user: smtpUser,
									smtp_secure: smtpSecure,
									...( smtpPassword ? { smtp_password: smtpPassword } : {} ),
								},
								} );
								setNotifNotice( { status: 'success', message: __( 'Notification settings saved.', 'conferencemanager' ) } );
							} catch ( err ) {
								setNotifNotice( { status: 'error', message: err.message } );
							} finally {
								setNotifSaving( false );
							}
						} }
					>
						{ __( 'Save Notification Settings', 'conferencemanager' ) }
					</Button>
					{ notifNotice && (
						<Notice status={ notifNotice.status } isDismissible={ false } style={ { marginTop: '8px' } }>
							{ notifNotice.message }
						</Notice>
					) }
				</div>
			</Section>

		</div>
	);
}
