/**
 * マイページ
 *
 * メールOTP認証後、サイドメニューで申込履歴・会員情報・帳票・参加証を確認。
 */
import { useState, useEffect } from '@wordpress/element';
import { __, sprintf } from '@wordpress/i18n';
import apiFetch from '@wordpress/api-fetch';
import useResendCooldown from '../hooks/use-resend-cooldown';
import downloadBase64Pdf from '../../common/pdf-download';
import { decorateMemberTypeLabels } from '../../common/member-type-label';

const SESSION_KEY = 'conf_manager_auth_token';

const STATUS_LABELS = {
	pending: __( 'Pending', 'conferencemanager' ),
	confirmed: __( 'Confirmed', 'conferencemanager' ),
	paid: __( 'Paid', 'conferencemanager' ),
	attended: __( 'Attended', 'conferencemanager' ),
	cancelled: __( 'Cancel', 'conferencemanager' ),
};

const MEMBER_TYPE_LABELS_BASE = {
	regular: __( 'Regular Member', 'conferencemanager' ),
	student: __( 'Student Member', 'conferencemanager' ),
	associate: __( 'Associate Member', 'conferencemanager' ),
	honorary: __( 'Honorary Member', 'conferencemanager' ),
	general: __( 'Non-member', 'conferencemanager' ),
};

// 🔴 表示名の装飾はここ 1 箇所だけ。**元の定義（上）は 1 文字も変えない。**
// 学会の略称（初期設定）が入っていれば標準 5 区分にだけ前置する。
// ⚠️ サーバから来る値（`fee_type_label` など）は**サーバ側でだけ**装飾している。
//    ここで二重に通さないこと。
const MEMBER_TYPE_LABELS = decorateMemberTypeLabels( MEMBER_TYPE_LABELS_BASE );

const BASE_MENU_ITEMS = [
	{ key: 'registrations', label: __( 'Registration History', 'conferencemanager' ) },
	{ key: 'member', label: __( 'Member Information', 'conferencemanager' ) },
	{ key: 'documents', label: __( 'Documents', 'conferencemanager' ) },
	{ key: 'email-settings', label: __( 'Email Preferences', 'conferencemanager' ) },
];

export default function Mypage() {
	const [ step, setStep ] = useState( 'email' );
	const [ email, setEmail ] = useState( '' );
	const [ otp, setOtp ] = useState( '' );
	const [ authToken, setAuthToken ] = useState( null );
	const [ member, setMember ] = useState( null );
	const [ registrations, setRegistrations ] = useState( [] );
	const [ loading, setLoading ] = useState( false );
	const [ error, setError ] = useState( null );
	const [ activeMenu, setActiveMenu ] = useState( () => {
		const params = new URLSearchParams( window.location.search );
		return params.get( 'tab' ) || 'registrations';
	} );
	const [ expandedReg, setExpandedReg ] = useState( null );
	const [ staffData, setStaffData ] = useState( {} );
	const [ programPdfs, setProgramPdfs ] = useState( [] );
	const [ emailOptOut, setEmailOptOut ] = useState( false );
	const [ emailPrefSaving, setEmailPrefSaving ] = useState( false );
	const [ emailPrefMessage, setEmailPrefMessage ] = useState( null );
	const [ editingReceiptReg, setEditingReceiptReg ] = useState( null );
	const [ receiptName, setReceiptName ] = useState( '' );
	const [ receiptDept, setReceiptDept ] = useState( '' );
	const [ receiptSaving, setReceiptSaving ] = useState( false );
	const [ receiptMessage, setReceiptMessage ] = useState( null );
	// 帳票のダウンロード（押している間は同じ申込の 2 つのボタンを止める）
	const [ downloadingId, setDownloadingId ] = useState( null );
	const [ downloadError, setDownloadError ] = useState( null );

	// トークンローテーション: レスポンスから新トークンを取得して更新
	const updateTokenIfRotated = ( data, currentToken ) => {
		if ( data.new_auth_token ) {
			setAuthToken( data.new_auth_token );
			sessionStorage.setItem( SESSION_KEY, data.new_auth_token );
			return data.new_auth_token;
		}
		return currentToken;
	};

	// ページ遷移・リロード後にセッションを復元
	useEffect( () => {
		const savedToken = sessionStorage.getItem( SESSION_KEY );
		if ( ! savedToken ) return;
		let cancelled = false;
		( async () => {
			try {
				const mypageData = await apiFetch( {
					path: '/conf-manager/v1/public/mypage',
					method: 'POST',
					data: { auth_token: savedToken },
				} );
				if ( cancelled ) return;
				const token = mypageData.new_auth_token || savedToken;
				setAuthToken( token );
				sessionStorage.setItem( SESSION_KEY, token );
				setMember( mypageData.member );
				setRegistrations( mypageData.registrations );
				setProgramPdfs( mypageData.program_pdfs || [] );
				setEmailOptOut( !! mypageData.member.email_opt_out );
				setStep( 'authenticated' );
			} catch {
				// トークン期限切れ → ストレージをクリア
				sessionStorage.removeItem( SESSION_KEY );
			}
		} )();
		return () => { cancelled = true; };
	}, [] );

	// 「再送信」の連打を止める（1 回ごとにレート制限の枠を消費するため）
	const { remaining, isCoolingDown, start: startCooldown } = useResendCooldown();

	const handleSendOtp = async () => {
		if ( ! email || isCoolingDown ) return;
		setLoading( true );
		setError( null );
		try {
			await apiFetch( {
				path: '/conf-manager/v1/public/mypage/send-otp',
				method: 'POST',
				data: { email },
			} );
			startCooldown();
			setStep( 'otp' );
		} catch ( err ) {
			setError( err.message );
		} finally {
			setLoading( false );
		}
	};

	const handleVerifyOtp = async () => {
		if ( ! otp ) return;
		setLoading( true );
		setError( null );
		try {
			const result = await apiFetch( {
				path: '/conf-manager/v1/public/mypage/verify-otp',
				method: 'POST',
				data: { email, otp },
			} );
			if ( result.authenticated && result.auth_token ) {
				let token = result.auth_token;
				setAuthToken( token );
				sessionStorage.setItem( SESSION_KEY, token );
				const mypageData = await apiFetch( {
					path: '/conf-manager/v1/public/mypage',
					method: 'POST',
					data: { auth_token: token },
				} );
				token = updateTokenIfRotated( mypageData, token );
				setMember( mypageData.member );
				setRegistrations( mypageData.registrations );
				setProgramPdfs( mypageData.program_pdfs || [] );
				setEmailOptOut( !! mypageData.member.email_opt_out );
				setStep( 'authenticated' );
			}
		} catch ( err ) {
			setError( err.message );
		} finally {
			setLoading( false );
		}
	};

	const handleLogout = async () => {
		// サーバー側のトークンも無効化
		if ( authToken ) {
			try {
				await apiFetch( {
					path: '/conf-manager/v1/public/mypage/logout',
					method: 'POST',
					data: { auth_token: authToken },
				} );
			} catch {
				// ログアウト失敗でも画面は初期化する
			}
		}
		sessionStorage.removeItem( SESSION_KEY );
		setStep( 'email' );
		setAuthToken( null );
		setMember( null );
		setRegistrations( [] );
		setEmail( '' );
		setOtp( '' );
		setError( null );
		setActiveMenu( 'registrations' );
		setExpandedReg( null );
		setStaffData( {} );
		setProgramPdfs( [] );
	};

	const toggleExpand = async ( reg ) => {
		if ( expandedReg === reg.id ) {
			setExpandedReg( null );
			return;
		}
		setExpandedReg( reg.id );
		if ( reg.is_representative && reg.staff_count > 0 && ! staffData[ reg.id ] ) {
			try {
				const data = await apiFetch( {
					path: '/conf-manager/v1/public/mypage/group-staff',
					method: 'POST',
					data: { auth_token: authToken, registration_id: reg.id },
				} );
				setStaffData( ( prev ) => ( { ...prev, [ reg.id ]: data } ) );
			} catch ( err ) {
				// ignore
			}
		}
	};

	// 領収書の宛名編集フォームを開く（現在値、無ければ申込者名をプリフィル）
	const openReceiptEdit = ( reg ) => {
		setEditingReceiptReg( reg.id );
		setReceiptName( ( reg.receipt && reg.receipt.addressee_name ) || reg.registered_name || '' );
		setReceiptDept( ( reg.receipt && reg.receipt.addressee_dept ) || '' );
		setReceiptMessage( null );
	};

	const closeReceiptEdit = () => {
		setEditingReceiptReg( null );
		setReceiptName( '' );
		setReceiptDept( '' );
	};

	// 宛名を保存して領収書 PDF を再発行する
	const handleSaveReceiptAddressee = async ( reg ) => {
		const name = receiptName.trim();
		if ( ! name ) return;
		setReceiptSaving( true );
		setReceiptMessage( null );
		try {
			const res = await apiFetch( {
				path: '/conf-manager/v1/public/mypage/receipt-addressee',
				method: 'POST',
				data: {
					auth_token: authToken,
					receipt_id: reg.receipt.id,
					addressee_name: name,
					addressee_dept: receiptDept.trim(),
				},
			} );
			// ⭐ URL のキャッシュバストは要らない。帳票は要求のたびに描画されるので、
			//    次のダウンロードに新しい宛名が入る。
			setRegistrations( ( prev ) => prev.map( ( r ) => (
				r.id === reg.id
					? {
						...r,
						receipt: { ...r.receipt, addressee_name: res.addressee_name, addressee_dept: res.addressee_dept },
					}
					: r
			) ) );
			setReceiptMessage( { regId: reg.id, text: __( 'Receipt addressee updated.', 'conferencemanager' ), isError: false } );
			closeReceiptEdit();
		} catch ( err ) {
			setReceiptMessage( { regId: reg.id, text: err.message || __( 'Failed to update the receipt.', 'conferencemanager' ), isError: true } );
		} finally {
			setReceiptSaving( false );
		}
	};

	/**
	 * 請求書・領収書を取得して保存させる
	 *
	 * 🔴 公開 URL は無い。所有権を検証する REST を叩いて base64 で受け取る。
	 */
	const handleDownloadDocument = async ( reg, type ) => {
		setDownloadingId( reg.id );
		setDownloadError( null );
		try {
			const data = await apiFetch( {
				path: '/conf-manager/v1/public/mypage/document',
				method: 'POST',
				data: { auth_token: authToken, registration_id: reg.id, type },
			} );
			downloadBase64Pdf( data.pdf_b64, data.filename );
		} catch ( err ) {
			setDownloadError( { regId: reg.id, text: err.message } );
		} finally {
			setDownloadingId( null );
		}
	};

	/** 帳票のボタン 2 つ（一覧と詳細で同じものを使う） */
	const renderDocumentButtons = ( reg ) => (
		<>
			{ reg.has_invoice && (
				<button
					type="button"
					className="conf-manager-mypage__pdf-btn"
					disabled={ downloadingId === reg.id }
					onClick={ () => handleDownloadDocument( reg, 'invoice' ) }
				>
					{ __( 'Invoice', 'conferencemanager' ) }
				</button>
			) }
			{ reg.has_receipt && (
				<button
					type="button"
					className="conf-manager-mypage__pdf-btn conf-manager-mypage__pdf-btn--receipt"
					disabled={ downloadingId === reg.id }
					onClick={ () => handleDownloadDocument( reg, 'receipt' ) }
				>
					{ __( 'Receipt', 'conferencemanager' ) }
				</button>
			) }
			{ downloadError && downloadError.regId === reg.id && (
				<p className="conf-manager-form__error">{ downloadError.text }</p>
			) }
		</>
	);

	// 領収書がある申込に対し「宛名を編集」ボタンとインライン編集フォームを描画する
	const renderReceiptEdit = ( reg ) => {
		if ( ! reg.receipt ) return null;
		const isEditing = editingReceiptReg === reg.id;
		const msg = receiptMessage && receiptMessage.regId === reg.id ? receiptMessage : null;
		return (
			<div className="conf-manager-mypage__receipt-edit">
				{ ! isEditing && (
					<button type="button" className="conf-manager-mypage__pdf-btn conf-manager-mypage__pdf-btn--edit" onClick={ () => openReceiptEdit( reg ) }>
						{ __( 'Edit addressee', 'conferencemanager' ) }
					</button>
				) }
				{ msg && ! isEditing && (
					<p className={ msg.isError ? 'conf-manager-form__error' : 'conf-manager-mypage__success' }>{ msg.text }</p>
				) }
				{ isEditing && (
					<div className="conf-manager-mypage__receipt-edit-form">
						<p className="conf-manager-mypage__receipt-edit-ref">
							{ __( 'Registered name (applicant)', 'conferencemanager' ) }: { reg.registered_name }
						</p>
						<label>
							{ __( 'Addressee', 'conferencemanager' ) }
							<input type="text" value={ receiptName } onChange={ ( e ) => setReceiptName( e.target.value ) } placeholder={ __( 'e.g. ABC Co., Ltd.', 'conferencemanager' ) } disabled={ receiptSaving } />
						</label>
						<label>
							{ __( 'Company / Department (optional)', 'conferencemanager' ) }
							<input type="text" value={ receiptDept } onChange={ ( e ) => setReceiptDept( e.target.value ) } placeholder={ __( 'e.g. Accounting Dept.', 'conferencemanager' ) } disabled={ receiptSaving } />
						</label>
						<p className="conf-manager-mypage__receipt-edit-hint">
							{ __( 'You can change the addressee if you need a receipt issued to a company or workplace. The field cannot be empty. Saving will reissue the receipt under the same receipt number.', 'conferencemanager' ) }
						</p>
						{ msg && msg.isError && <p className="conf-manager-form__error">{ msg.text }</p> }
						<div className="conf-manager-mypage__receipt-edit-actions">
							<button type="button" className="conf-manager-mypage__pdf-btn" onClick={ () => handleSaveReceiptAddressee( reg ) } disabled={ receiptSaving || ! receiptName.trim() }>
								{ receiptSaving ? __( 'Saving...', 'conferencemanager' ) : __( 'Save and reissue', 'conferencemanager' ) }
							</button>
							<button type="button" className="conf-manager-mypage__pdf-btn conf-manager-mypage__pdf-btn--cancel" onClick={ closeReceiptEdit } disabled={ receiptSaving }>
								{ __( 'Cancel', 'conferencemanager' ) }
							</button>
						</div>
					</div>
				) }
			</div>
		);
	};

	// === ログイン前の画面 ===
	if ( step === 'email' ) {
		return (
			<div className="conf-manager-public conf-manager-mypage">
				<h2>{ __( 'My Page', 'conferencemanager' ) }</h2>
				<p>{ __( 'Enter your registered email address. A verification code will be sent.', 'conferencemanager' ) }</p>
				{ error && <div className="conf-manager-form__error">{ error }</div> }
				<div className="conf-manager-form__field">
					<input type="email" value={ email } onChange={ ( e ) => setEmail( e.target.value ) } placeholder="example@email.com" onKeyDown={ ( e ) => e.key === 'Enter' && handleSendOtp() } />
					<button onClick={ handleSendOtp } disabled={ loading } className="conf-manager-form__login-btn">
						{ loading ? __( 'Submitting...', 'conferencemanager' ) : __( 'Send Verification Code', 'conferencemanager' ) }
					</button>
				</div>
			</div>
		);
	}

	if ( step === 'otp' ) {
		return (
			<div className="conf-manager-public conf-manager-mypage">
				<h2>{ __( 'My Page', 'conferencemanager' ) }</h2>
				<p>{ __( 'Enter the 6-digit verification code sent to your email.', 'conferencemanager' ) }</p>
				<p className="conf-manager-mypage__email-hint">{ email }</p>
				{ error && <div className="conf-manager-form__error">{ error }</div> }
				<div className="conf-manager-form__field">
					<input type="text" inputMode="numeric" maxLength={ 6 } value={ otp } onChange={ ( e ) => setOtp( e.target.value.replace( /\D/g, '' ) ) } placeholder="000000" onKeyDown={ ( e ) => e.key === 'Enter' && handleVerifyOtp() } autoFocus />
					<button onClick={ handleVerifyOtp } disabled={ loading || otp.length !== 6 } className="conf-manager-form__login-btn">
						{ loading ? __( 'Verifying...', 'conferencemanager' ) : __( 'Log In', 'conferencemanager' ) }
					</button>
				</div>
				<p className="conf-manager-mypage__email-hint">
					{ __( 'It may take a few minutes for the email to arrive. Please also check your spam folder.', 'conferencemanager' ) }
				</p>
				<div className="conf-manager-mypage__otp-actions">
					<button onClick={ () => { setOtp( '' ); setError( null ); handleSendOtp(); } } className="conf-manager-form__link" disabled={ loading || isCoolingDown }>
						{ isCoolingDown
							? sprintf(
								/* translators: %d: seconds remaining before the code can be resent */
								__( 'Resend Verification Code (%ds)', 'conferencemanager' ),
								remaining
							)
							: __( 'Resend Verification Code', 'conferencemanager' ) }
					</button>
					<button onClick={ () => { setStep( 'email' ); setError( null ); } } className="conf-manager-form__link">
						{ __( 'Change Email Address', 'conferencemanager' ) }
					</button>
				</div>
			</div>
		);
	}

	// === ログイン後: サイドメニュー + コンテンツ ===

	const activeRegs = registrations.filter( ( r ) => r.status !== 'cancelled' );
	const docsRegs = registrations.filter( ( r ) => r.has_invoice || r.has_receipt );

	// プログラムPDFがある場合のみタブを追加
	const menuItems = programPdfs.length > 0
		? [ ...BASE_MENU_ITEMS, { key: 'program-pdfs', label: __( 'Program & abstracts', 'conferencemanager' ) } ]
		: BASE_MENU_ITEMS;

	return (
		<div className="conf-manager-public conf-manager-mypage">
			<div className="conf-manager-mypage__header">
				<h2>{ __( 'My Page', 'conferencemanager' ) }</h2>
			</div>

			<div className="conf-manager-mypage__layout">
				{ /* サイドメニュー */ }
				<nav className="conf-manager-mypage__nav">
					<p className="conf-manager-mypage__welcome">
						{ __( 'Welcome', 'conferencemanager' ) }<br />{ member?.name_sei } { member?.name_mei } { __( ' ', 'conferencemanager' ) }
					</p>
					<div className="conf-manager-mypage__nav-items">
						{ menuItems.map( ( item ) => (
							<button
								key={ item.key }
								onClick={ () => setActiveMenu( item.key ) }
								className={ `conf-manager-mypage__nav-item ${ activeMenu === item.key ? 'is-active' : '' }` }
							>
								{ item.label }
							</button>
						) ) }
					</div>
				</nav>

				{ /* コンテンツ */ }
				<div className="conf-manager-mypage__content">

					{ /* 申込履歴 */ }
					{ activeMenu === 'registrations' && (
						<div>
							<h3>{ __( 'Registration History', 'conferencemanager' ) }</h3>
							{ registrations.length === 0 ? (
								<p>
									{ __( 'No registration history.', 'conferencemanager' ) }
									<a href="/c-registration/" style={ { marginLeft: '12px' } }>
										{ __( 'Register Here', 'conferencemanager' ) }
									</a>
								</p>
							) : (
								<div className="conf-manager-mypage__reg-list">
									{ registrations.map( ( reg ) => (
										<div key={ reg.id } className={ `conf-manager-mypage__reg-card ${ expandedReg === reg.id ? 'is-expanded' : '' }` }>
											<div className="conf-manager-mypage__reg-header" onClick={ () => toggleExpand( reg ) }>
												<div className="conf-manager-mypage__reg-summary">
													<strong>{ reg.event_title }</strong>
													<span className="conf-manager-mypage__reg-meta">
														{ reg.registration_no } / { reg.event_date ? reg.event_date.substring( 0, 10 ) : '' }
														{ reg.is_representative && reg.staff_count > 0 && (
															<span className="conf-manager-mypage__badge">{ __( 'Group', 'conferencemanager' ) } ({ reg.staff_count }{ __( 'First Name', 'conferencemanager' ) })</span>
														) }
													</span>
												</div>
												<div className="conf-manager-mypage__reg-right">
													<span className="conf-manager-mypage__reg-amount">&yen;{ ( reg.amount + reg.tax ).toLocaleString() }</span>
													<span className={ `conf-manager-mypage__status conf-manager-mypage__status--${ reg.status }` }>
														{ STATUS_LABELS[ reg.status ] || reg.status }
													</span>
													<span className="conf-manager-mypage__reg-toggle">{ expandedReg === reg.id ? '▲' : '▼' }</span>
												</div>
											</div>

											{ expandedReg === reg.id && (
												<div className="conf-manager-mypage__reg-detail">
													<dl className="conf-manager-mypage__info">
														<dt>{ __( 'Participation Type', 'conferencemanager' ) }</dt>
														<dd>{ reg.participation_type === 'online' ? __( 'Online', 'conferencemanager' ) : __( 'On-site', 'conferencemanager' ) }</dd>
														{ /* 参加区分（イベント編集画面の料金表に登録した会員種別）。
														     ⚠️ ここで decorateMemberTypeLabel() を呼ばないこと。
														        学会名の前置は**サーバ側で済んでいる**ので、通すと 2 回入る。
														     ⚠️ 空ガードを外さないこと。古い申込は fee_type_label が空で、
														        そのときは行ごと出さない（帳票と同じ扱い）。 */ }
														{ reg.fee_type_label && (
															<>
																<dt>{ __( 'Fee Category', 'conferencemanager' ) }</dt>
																<dd>{ reg.fee_type_label }</dd>
															</>
														) }
														{ reg.tax > 0 && (
															<>
																<dt>{ __( 'Amount (excl. tax)', 'conferencemanager' ) }</dt>
																<dd>&yen;{ reg.amount.toLocaleString() }</dd>
																<dt>{ __( 'Tax', 'conferencemanager' ) }</dt>
																<dd>&yen;{ reg.tax.toLocaleString() }</dd>
															</>
														) }
													</dl>
													<div className="conf-manager-mypage__pdf-links">
														{ renderDocumentButtons( reg ) }
													</div>
													{ renderReceiptEdit( reg ) }
													{ reg.is_representative && reg.staff_count > 0 && (
														<div className="conf-manager-mypage__staff-section">
															<h4>{ __( 'Registered Staff', 'conferencemanager' ) }</h4>
															{ staffData[ reg.id ] ? (
																<div className="conf-manager-mypage__table-wrap">
																	<table className="conf-manager-mypage__table">
																		<thead><tr><th>{ __( 'Name', 'conferencemanager' ) }</th><th>{ __( 'Email', 'conferencemanager' ) }</th><th>{ __( 'Participation Type', 'conferencemanager' ) }</th><th>{ __( 'Status', 'conferencemanager' ) }</th></tr></thead>
																		<tbody>
																			{ staffData[ reg.id ].map( ( s ) => (
																				<tr key={ s.id }>
																					<td>{ s.name }</td>
																					<td>{ s.email }</td>
																					<td>{ s.participation_type === 'online' ? __( 'Online', 'conferencemanager' ) : __( 'Venue', 'conferencemanager' ) }</td>
																					<td><span className={ `conf-manager-mypage__status conf-manager-mypage__status--${ s.status === 'active' ? 'paid' : 'cancelled' }` }>{ s.status === 'active' ? __( 'Active', 'conferencemanager' ) : __( 'Cancel', 'conferencemanager' ) }</span></td>
																				</tr>
																			) ) }
																		</tbody>
																	</table>
																</div>
															) : (
																<p>{ __( 'Loading...', 'conferencemanager' ) }</p>
															) }
														</div>
													) }
												</div>
											) }
										</div>
									) ) }
								</div>
							) }
						</div>
					) }

					{ /* 会員情報 */ }
					{ activeMenu === 'member' && (
						<div>
							<h3>{ __( 'Member Information', 'conferencemanager' ) }</h3>
							<dl className="conf-manager-mypage__info">
								<dt>{ __( 'Name', 'conferencemanager' ) }</dt>
								<dd>{ member.name_sei } { member.name_mei }</dd>
								<dt>{ __( 'Member Type', 'conferencemanager' ) }</dt>
								<dd>{ MEMBER_TYPE_LABELS[ member.member_type ] || member.member_type }</dd>
								{ member.org_name && (
									<>
										<dt>{ __( 'Organization', 'conferencemanager' ) }</dt>
										<dd>{ member.org_name }</dd>
									</>
								) }
								{ member.org_dept && (
									<>
										<dt>{ __( 'Department', 'conferencemanager' ) }</dt>
										<dd>{ member.org_dept }</dd>
									</>
								) }
							</dl>
						</div>
					) }

					{ /* 帳票 */ }
					{ activeMenu === 'documents' && (
						<div>
							<h3>{ __( 'Documents', 'conferencemanager' ) }</h3>
							{ docsRegs.length === 0 ? (
								<p>{ __( 'No documents issued.', 'conferencemanager' ) }</p>
							) : (
								<div className="conf-manager-mypage__docs-list">
									{ docsRegs.map( ( reg ) => (
										<div key={ reg.id } className="conf-manager-mypage__docs-row">
											<div>
												<strong>{ reg.event_title }</strong>
												<span className="conf-manager-mypage__reg-meta">{ reg.registration_no }</span>
											</div>
											<div className="conf-manager-mypage__pdf-links">
												{ renderDocumentButtons( reg ) }
											</div>
											{ renderReceiptEdit( reg ) }
										</div>
									) ) }
								</div>
							) }
						</div>
					) }

					{ /* プログラム・抄録集PDF */ }
					{ activeMenu === 'program-pdfs' && (
						<div>
							<h3>{ __( 'Program & abstracts', 'conferencemanager' ) }</h3>
							{ programPdfs.map( ( eventGroup ) => (
								<div key={ eventGroup.event_id } className="conf-manager-mypage__docs-list">
									<h4>{ eventGroup.event_title }</h4>
									{ eventGroup.pdfs.map( ( pdf ) => (
										<div key={ pdf.id } className="conf-manager-mypage__docs-row">
											<div>
												<strong>{ pdf.description }</strong>
											</div>
											<div className="conf-manager-mypage__pdf-links">
												<a
													href={ pdf.url }
													target="_blank"
													rel="noopener noreferrer"
													className="conf-manager-mypage__pdf-btn"
												>
													{ __( 'Download', 'conferencemanager' ) }
												</a>
											</div>
										</div>
									) ) }
								</div>
							) ) }
						</div>
					) }

					{ /* メール配信設定 */ }
					{ activeMenu === 'email-settings' && (
						<div>
							<h3>{ __( 'Email Preferences', 'conferencemanager' ) }</h3>
							<p className="conf-manager-mypage__email-desc">
								{ __( 'You can change your event notification email settings. Service-essential emails such as OTP and registration confirmations cannot be unsubscribed.', 'conferencemanager' ) }
							</p>
							<label className="conf-manager-mypage__email-opt-out-label">
								<input
									type="checkbox"
									checked={ emailOptOut }
									onChange={ ( e ) => setEmailOptOut( e.target.checked ) }
									disabled={ emailPrefSaving }
								/>
								{ __( 'Unsubscribe from event notification emails', 'conferencemanager' ) }
							</label>
							<div style={ { marginTop: '1rem' } }>
								<button
									className="conf-manager-btn conf-manager-btn--primary"
									disabled={ emailPrefSaving }
									onClick={ async () => {
										setEmailPrefSaving( true );
										setEmailPrefMessage( null );
										try {
											const res = await apiFetch( {
												path: '/conf-manager/v1/public/mypage/email-preferences',
												method: 'POST',
												data: {
													auth_token: authToken,
													email_opt_out: emailOptOut,
												},
											} );
											setEmailOptOut( res.email_opt_out );
											setEmailPrefMessage( __( 'Settings saved.', 'conferencemanager' ) );
										} catch {
											setEmailPrefMessage( __( 'Failed to save settings.', 'conferencemanager' ) );
										} finally {
											setEmailPrefSaving( false );
										}
									} }
								>
									{ emailPrefSaving
										? __( 'Saving…', 'conferencemanager' )
										: __( 'Save Settings', 'conferencemanager' )
									}
								</button>
								{ emailPrefMessage && (
									<p style={ { marginTop: '0.5rem' } }>{ emailPrefMessage }</p>
								) }
							</div>
						</div>
					) }

				</div>

				<div className="conf-manager-mypage__footer">
					<button onClick={ handleLogout } className="conf-manager-mypage__logout">
						{ __( 'Log Out', 'conferencemanager' ) }
					</button>
				</div>
			</div>
		</div>
	);
}
