/**
 * マイページ
 *
 * メールOTP認証後、サイドメニューで申込履歴・会員情報・帳票・参加証を確認。
 */
import { useState, useEffect } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import apiFetch from '@wordpress/api-fetch';

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 = {
	regular: __( 'Regular Member', 'conferencemanager' ),
	student: __( 'Student Member', 'conferencemanager' ),
	associate: __( 'Associate Member', 'conferencemanager' ),
	honorary: __( 'Honorary Member', 'conferencemanager' ),
	general: __( 'Non-member', 'conferencemanager' ),
};

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 );

	// トークンローテーション: レスポンスから新トークンを取得して更新
	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; };
	}, [] );

	const handleSendOtp = async () => {
		if ( ! email ) return;
		setLoading( true );
		setError( null );
		try {
			await apiFetch( {
				path: '/conf-manager/v1/public/mypage/send-otp',
				method: 'POST',
				data: { email },
			} );
			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(),
				},
			} );
			// ローカル state を更新し、PDF リンクはキャッシュバストして最新を開けるようにする
			const bustedUrl = res.receipt_url ? `${ res.receipt_url }?t=${ Date.now() }` : reg.receipt_url;
			setRegistrations( ( prev ) => prev.map( ( r ) => (
				r.id === reg.id
					? {
						...r,
						receipt_url: bustedUrl,
						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 );
		}
	};

	// 領収書がある申込に対し「宛名を編集」ボタンとインライン編集フォームを描画する
	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>
				<div className="conf-manager-mypage__otp-actions">
					<button onClick={ () => { setOtp( '' ); setError( null ); handleSendOtp(); } } className="conf-manager-form__link" disabled={ loading }>
						{ __( '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.invoice_url || r.receipt_url );

	// プログラム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>
														{ 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">
														{ reg.invoice_url && (
															<a href={ reg.invoice_url } target="_blank" rel="noopener noreferrer" className="conf-manager-mypage__pdf-btn">{ __( 'Invoice', 'conferencemanager' ) }</a>
														) }
														{ reg.receipt_url && (
															<a href={ reg.receipt_url } target="_blank" rel="noopener noreferrer" className="conf-manager-mypage__pdf-btn conf-manager-mypage__pdf-btn--receipt">{ __( 'Receipt', 'conferencemanager' ) }</a>
														) }
													</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">
												{ reg.invoice_url && (
													<a href={ reg.invoice_url } target="_blank" rel="noopener noreferrer" className="conf-manager-mypage__pdf-btn">{ __( 'Invoice', 'conferencemanager' ) }</a>
												) }
												{ reg.receipt_url && (
													<a href={ reg.receipt_url } target="_blank" rel="noopener noreferrer" className="conf-manager-mypage__pdf-btn conf-manager-mypage__pdf-btn--receipt">{ __( 'Receipt', 'conferencemanager' ) }</a>
												) }
											</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>
	);
}
