/**
 * イベント管理ページ
 *
 * 一覧・作成・編集・料金マトリックス設定。
 */
import { useState, useEffect, useCallback } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import {
	Button,
	TextControl,
	TextareaControl,
	SelectControl,
	Modal,
	Notice,
} from '@wordpress/components';
import DataTable from '../components/DataTable';
import { useEventApi } from '../hooks/useApi';
import useCan from '../hooks/useCan';
import GuideSection from '../components/GuideSection';

const STATUS_OPTIONS = [
	{ label: __( 'Draft', 'conferencemanager' ), value: 'draft' },
	{ label: __( 'Published', 'conferencemanager' ), value: 'published' },
	{ label: __( 'Closed', 'conferencemanager' ), value: 'closed' },
	{ label: __( 'Cancel', 'conferencemanager' ), value: 'cancelled' },
];

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

const PARTICIPATION_TYPES = [ 'onsite', 'online' ];
const MEMBER_TYPES = [ 'regular', 'student', 'associate', 'honorary', 'general' ];

const BASE_COLUMNS = [
	{ key: 'id', label: 'ID' },
	{ key: 'title', label: __( 'Title', 'conferencemanager' ) },
	{
		key: 'date_start',
		label: __( 'Event Date', 'conferencemanager' ),
		render: ( val ) => val ? val.substring( 0, 10 ) : '',
	},
	{ key: 'venue', label: __( 'Venue', 'conferencemanager' ) },
];

const EMPTY_FORM = {
	title: '',
	description: '',
	date_start: '',
	date_end: '',
	venue: '',
	venue_address: '',
	capacity: '',
	reg_start: '',
	reg_end: '',
	status: 'draft',
	fee_rules: {},
	fee_labels: {},
	advance_fee_deadline: '',
	fee_rules_day: {},
	fee_labels_day: {},
	advance_fee_notice: '',
	tax_rate: '10.0',
	payment_account_name: '',
	payment_account_info: '',
	organizer_info: '',
	submission_start: '',
	submission_end: '',
	submission_mode: 'form',
	submission_title_limit: '',
	submission_abstract_limit: '',
	submission_keywords_limit: '',
	submission_template_name: '',
	submission_template_file: null,
};

const TAX_RATE_OPTIONS = [
	{ label: __( 'Tax-exempt (0%)', 'conferencemanager' ), value: '0.0' },
	{ label: __( 'Reduced rate (8%)', 'conferencemanager' ), value: '8.0' },
	{ label: __( 'Standard rate (10%)', 'conferencemanager' ), value: '10.0' },
];

export default function Events() {
	const api = useEventApi();
	const canEdit = useCan( 'conf_manager_edit_events' );

	const [ events, setEvents ] = useState( [] );
	const [ total, setTotal ] = useState( 0 );
	const [ page, setPage ] = useState( 1 );
	const [ keyword, setKeyword ] = useState( '' );

	const [ isModalOpen, setModalOpen ] = useState( false );
	const [ editingId, setEditingId ] = useState( null );
	const [ form, setForm ] = useState( { ...EMPTY_FORM } );
	const [ notice, setNotice ] = useState( null );

	const handlePublish = async ( eventId, e ) => {
		e.stopPropagation();
		try {
			await api.updateEvent( eventId, { status: 'published' } );
			setNotice( { status: 'success', message: __( 'Event published.', 'conferencemanager' ) } );
			fetchEvents();
		} catch ( err ) {
			setNotice( { status: 'error', message: err.message } );
		}
	};

	const columns = [
		...BASE_COLUMNS,
		{
			key: 'status',
			label: __( 'Status', 'conferencemanager' ),
			render: ( val, row ) => {
				const s = STATUS_OPTIONS.find( ( o ) => o.value === val );
				const label = s ? s.label : val;
				if ( val === 'published' ) {
						return (
							<span style={ {
								background: '#ecfdf5',
								color: '#059669',
								padding: '2px 10px',
								borderRadius: '4px',
								fontSize: '12px',
								fontWeight: 600,
							} }>
								{ __( 'Published', 'conferencemanager' ) }
							</span>
						);
					}
					if ( val === 'draft' && canEdit ) {
					return (
						<span style={ { display: 'flex', alignItems: 'center', gap: '8px' } }>
							<span style={ {
								background: '#fcf0f0',
								color: '#8b0000',
								padding: '2px 8px',
								borderRadius: '4px',
								fontSize: '12px',
								fontWeight: 600,
							} }>
								{ label }
							</span>
							<span style={ { position: 'relative', display: 'inline-flex' } }>
								<span className="conf-manager-pulse-dot" />
								<button
									type="button"
									onClick={ ( e ) => handlePublish( row.id, e ) }
									style={ {
										background: '#059669',
										color: '#fff',
										border: 'none',
										borderRadius: '20px',
										fontSize: '12px',
										fontWeight: 600,
										padding: '5px 16px',
										cursor: 'pointer',
										lineHeight: '1.4',
										whiteSpace: 'nowrap',
									} }
								>
									{ __( 'Publish', 'conferencemanager' ) }
								</button>
							</span>
						</span>
					);
				}
				return label;
			},
		},
	];

	const fetchEvents = useCallback( async () => {
		try {
			const params = { page, per_page: 20 };
			if ( keyword ) {
				params.keyword = keyword;
			}
			const result = await api.getEvents( params );
			setEvents( result.items );
			setTotal( result.total );
		} catch ( err ) {
			// handled by hook
		}
	}, [ page, keyword ] );

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

	const openCreate = () => {
		setEditingId( null );
		setForm( { ...EMPTY_FORM } );
		setModalOpen( true );
	};

	const openEdit = ( event ) => {
		setEditingId( event.id );
		const rules = { ...( event.fee_rules || {} ) };
		const labels = { ...( rules._labels || {} ) };
		delete rules._labels;
		const rulesDay = { ...( event.fee_rules_day || {} ) };
		const labelsDay = { ...( rulesDay._labels || {} ) };
		delete rulesDay._labels;
		setForm( {
			title: event.title || '',
			description: event.description || '',
			date_start: event.date_start || '',
			date_end: event.date_end || '',
			venue: event.venue || '',
			venue_address: event.venue_address || '',
			capacity: event.capacity || '',
			reg_start: event.reg_start || '',
			reg_end: event.reg_end || '',
			status: event.status || 'draft',
			fee_rules: rules,
			fee_labels: labels,
			advance_fee_deadline: event.advance_fee_deadline || '',
			fee_rules_day: rulesDay,
			fee_labels_day: labelsDay,
			advance_fee_notice: event.advance_fee_notice || '',
			tax_rate: Number( event.tax_rate ?? 10.0 ).toFixed( 1 ),
			payment_account_name: event.payment_account_name || '',
			payment_account_info: event.payment_account_info || '',
			organizer_info: event.organizer_info || '',
			submission_start: event.submission_start || '',
			submission_end: event.submission_end || '',
			submission_mode: event.submission_settings?.submission_mode || 'form',
			submission_title_limit: event.submission_settings?.title_limit || '',
			submission_abstract_limit: event.submission_settings?.abstract_limit || '',
			submission_keywords_limit: event.submission_settings?.keywords_limit || '',
			submission_template_name: event.submission_settings?.template_file_name || '',
			submission_template_file: null,
		} );
		setModalOpen( true );
	};

	const handleSubmit = async () => {
		try {
			const data = { ...form };
			if ( data.capacity ) {
				data.capacity = parseInt( data.capacity );
			}

			// カスタム種別ラベルを fee_rules._labels にマージ
			if ( data.fee_labels && Object.keys( data.fee_labels ).length > 0 ) {
				data.fee_rules = { ...data.fee_rules, _labels: { ...data.fee_labels } };
			}
			delete data.fee_labels;

			// 当日料金のカスタム種別ラベルも同様にマージ
			if ( data.fee_labels_day && Object.keys( data.fee_labels_day ).length > 0 ) {
				data.fee_rules_day = { ...data.fee_rules_day, _labels: { ...data.fee_labels_day } };
			}
			delete data.fee_labels_day;

			// 演題投稿設定をまとめる
			data.submission_settings = {};
			if ( data.submission_mode ) data.submission_settings.submission_mode = data.submission_mode;
			if ( data.submission_title_limit ) data.submission_settings.title_limit = parseInt( data.submission_title_limit );
			if ( data.submission_abstract_limit ) data.submission_settings.abstract_limit = parseInt( data.submission_abstract_limit );
			if ( data.submission_keywords_limit ) data.submission_settings.keywords_limit = parseInt( data.submission_keywords_limit );
			delete data.submission_mode;
			delete data.submission_title_limit;
			delete data.submission_abstract_limit;
			delete data.submission_keywords_limit;
			delete data.submission_template_name;
			delete data.submission_template_file;

			if ( editingId ) {
				await api.updateEvent( editingId, data );
				setNotice( { status: 'success', message: __( 'Event updated.', 'conferencemanager' ) } );
			} else {
				const created = await api.createEvent( data );
				if ( created?.status !== 'published' ) {
					setNotice( {
						status: 'success',
						message: __( 'Event created.', 'conferencemanager' ),
						eventId: created?.id,
					} );
				} else {
					setNotice( { status: 'success', message: __( 'Event created.', 'conferencemanager' ) } );
				}
			}
			setModalOpen( false );
			fetchEvents();
		} catch ( err ) {
			setNotice( { status: 'error', message: err.message } );
		}
	};

	const handleDelete = async ( id ) => {
		if ( ! window.confirm( __( 'Cancel this event?', 'conferencemanager' ) ) ) {
			return;
		}
		try {
			await api.deleteEvent( id );
			setNotice( { status: 'success', message: __( 'Event cancelled.', 'conferencemanager' ) } );
			fetchEvents();
		} catch ( err ) {
			setNotice( { status: 'error', message: err.message } );
		}
	};

	const updateField = ( field ) => ( value ) => {
		setForm( ( prev ) => ( { ...prev, [ field ]: value } ) );
	};

	const updateFeeRule = ( memberType, participationType, value ) => {
		setForm( ( prev ) => {
			const rules = { ...prev.fee_rules };
			if ( ! rules[ memberType ] ) {
				rules[ memberType ] = {};
			}
			rules[ memberType ][ participationType ] = parseInt( value ) || 0;
			return { ...prev, fee_rules: rules };
		} );
	};

	const updateFeeRuleDay = ( memberType, participationType, value ) => {
		setForm( ( prev ) => {
			const rules = { ...prev.fee_rules_day };
			if ( ! rules[ memberType ] ) {
				rules[ memberType ] = {};
			}
			rules[ memberType ][ participationType ] = parseInt( value ) || 0;
			return { ...prev, fee_rules_day: rules };
		} );
	};

	const copyAdvanceToDay = () => {
		setForm( ( prev ) => ( {
			...prev,
			fee_rules_day: { ...prev.fee_rules },
			fee_labels_day: { ...prev.fee_labels },
		} ) );
	};

	const addCustomType = () => {
		setForm( ( prev ) => {
			const labels = { ...prev.fee_labels };
			const rules = { ...prev.fee_rules };
			// 次の連番を決定
			let n = 1;
			while ( labels[ `custom_${ n }` ] || rules[ `custom_${ n }` ] ) {
				n++;
			}
			const key = `custom_${ n }`;
			labels[ key ] = '';
			rules[ key ] = { onsite: 0, online: 0 };
			return { ...prev, fee_labels: labels, fee_rules: rules };
		} );
	};

	const removeCustomType = ( key ) => {
		setForm( ( prev ) => {
			const labels = { ...prev.fee_labels };
			const rules = { ...prev.fee_rules };
			delete labels[ key ];
			delete rules[ key ];
			return { ...prev, fee_labels: labels, fee_rules: rules };
		} );
	};

	// Remove a custom fee type from the on-site fee table only.
	// Operates on the on-site (_day) state and never touches advance (fee_labels / fee_rules).
	const removeCustomTypeDay = ( key ) => {
		setForm( ( prev ) => {
			const labels = { ...prev.fee_labels_day };
			const rules = { ...prev.fee_rules_day };
			delete labels[ key ];
			delete rules[ key ];
			return { ...prev, fee_labels_day: labels, fee_rules_day: rules };
		} );
	};

	const updateCustomLabel = ( key, value ) => {
		setForm( ( prev ) => ( {
			...prev,
			fee_labels: { ...prev.fee_labels, [ key ]: value },
		} ) );
	};

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

			<GuideSection
				hero={ {
					title: __( 'Streamline Event Operations', 'conferencemanager' ),
					description: __( 'Manage everything from creating conferences, meetings, and symposiums to setting participation fees.', 'conferencemanager' ),
				} }
				cards={ [
					{
						icon: <svg viewBox="0 0 24 24" width="32" height="32" fill="none" stroke="currentColor" strokeWidth="1.5"><rect x="3" y="4" width="18" height="18" rx="2" ry="2" /><line x1="16" y1="2" x2="16" y2="6" /><line x1="8" y1="2" x2="8" y2="6" /><line x1="3" y1="10" x2="21" y2="10" /></svg>,
						title: __( 'Create Events', 'conferencemanager' ),
						description: __( 'Register basic info such as title, dates, venue, and capacity to publish an event.', 'conferencemanager' ),
						tips: [
							__( 'Set status to "Published" to start accepting registrations', 'conferencemanager' ),
							__( 'Control registration period with start and deadline dates', 'conferencemanager' ),
							__( 'Organizer info is reflected on certificates and invoices', 'conferencemanager' ),
						],
					},
					{
						icon: <svg viewBox="0 0 24 24" width="32" height="32" fill="none" stroke="currentColor" strokeWidth="1.5"><line x1="12" y1="1" x2="12" y2="23" /><path d="M17 5H9.5a3.5 3.5 0 000 7h5a3.5 3.5 0 010 7H6" /></svg>,
						title: __( 'Pricing', 'conferencemanager' ),
						description: __( 'Set flexible fees using a member type × participation type matrix.', 'conferencemanager' ),
						tips: [
							__( 'Set individual prices for regular members, students, and non-members', 'conferencemanager' ),
							__( 'Support different prices for onsite and online participation', 'conferencemanager' ),
							__( 'Choose tax rate (0% / 8% / 10%)', 'conferencemanager' ),
						],
					},
				] }
			/>

			{ notice && (
				/*
				 * key で内容が変わるたびに Notice を再マウントさせる。
				 * 同一 Notice インスタンスを子要素の形（Publish ボタンの有無）を
				 * 変えながら再描画すると、WP の Notice 内 useSpokenMessage が
				 * フック状態を壊して落ちる（areHookInputsEqual の undefined.length）ため。
				 */
				<Notice
					key={ notice.eventId ? `create-${ notice.eventId }` : `msg-${ notice.message }` }
					status={ notice.status }
					onDismiss={ () => setNotice( null ) }
				>
					{ notice.message }
					{ notice.eventId && (
						<>
							{ ' ' }
							{ __( 'To publish this event, change the status to "Published".', 'conferencemanager' ) }
							<Button
								variant="primary"
								isDestructive
								style={ { marginLeft: '8px' } }
								onClick={ async () => {
									await api.updateEvent( notice.eventId, { status: 'published' } );
									setNotice( { status: 'success', message: __( 'Event published.', 'conferencemanager' ) } );
									fetchEvents();
								} }
							>
								{ __( 'Publish', 'conferencemanager' ) }
							</Button>
						</>
					) }
				</Notice>
			) }

			<form onSubmit={ ( e ) => { e.preventDefault(); setPage( 1 ); fetchEvents(); } } className="conf-manager-search">
				<TextControl
					placeholder={ __( 'Search by title/venue', 'conferencemanager' ) }
					value={ keyword }
					onChange={ setKeyword }
				/>
				<Button type="submit" className="conf-manager-btn--primary">
					{ __( 'Search', 'conferencemanager' ) }
				</Button>
				<span className="conf-manager-search__spacer" />
				{ canEdit && (
					<Button className="conf-manager-btn--danger" onClick={ openCreate }>
						{ __( 'New Event', 'conferencemanager' ) }
					</Button>
				) }
			</form>

			<DataTable
				columns={ columns }
				rows={ events }
				total={ total }
				page={ page }
				perPage={ 20 }
				onPageChange={ setPage }
				onRowClick={ canEdit ? openEdit : undefined }
				loading={ api.loading }
			/>

			{ isModalOpen && (
				<Modal
					title={ editingId ? __( 'Edit Event', 'conferencemanager' ) : __( 'New Event', 'conferencemanager' ) }
					onRequestClose={ () => setModalOpen( false ) }
					className="conf-manager-modal--wide"
				>
					<TextControl label={ __( 'Title', 'conferencemanager' ) } value={ form.title } onChange={ updateField( 'title' ) } required />
					<TextareaControl label={ __( 'Description', 'conferencemanager' ) } value={ form.description } onChange={ updateField( 'description' ) } />
					<TextControl label={ __( 'Start Date', 'conferencemanager' ) } type="datetime-local" value={ form.date_start.replace( ' ', 'T' ).substring( 0, 16 ) } onChange={ ( v ) => updateField( 'date_start' )( v.replace( 'T', ' ' ) + ':00' ) } required />
					<TextControl label={ __( 'End Date', 'conferencemanager' ) } type="datetime-local" value={ form.date_end.replace( ' ', 'T' ).substring( 0, 16 ) } onChange={ ( v ) => updateField( 'date_end' )( v.replace( 'T', ' ' ) + ':00' ) } required />
					<TextControl label={ __( 'Venue', 'conferencemanager' ) } value={ form.venue } onChange={ updateField( 'venue' ) } />
					<TextControl label={ __( 'Venue Address', 'conferencemanager' ) } value={ form.venue_address } onChange={ updateField( 'venue_address' ) } />
					<TextControl label={ __( 'Capacity', 'conferencemanager' ) } type="number" value={ form.capacity } onChange={ updateField( 'capacity' ) } />
					<TextControl label={ __( 'Registration Opens', 'conferencemanager' ) } type="datetime-local" value={ ( form.reg_start || '' ).replace( ' ', 'T' ).substring( 0, 16 ) } onChange={ ( v ) => updateField( 'reg_start' )( v.replace( 'T', ' ' ) + ':00' ) } />
					<TextControl label={ __( 'Registration Closes', 'conferencemanager' ) } type="datetime-local" value={ ( form.reg_end || '' ).replace( ' ', 'T' ).substring( 0, 16 ) } onChange={ ( v ) => updateField( 'reg_end' )( v.replace( 'T', ' ' ) + ':00' ) } />

					<h3>{ __( 'Abstract submission settings', 'conferencemanager' ) }</h3>
					<TextControl label={ __( 'Submission Start', 'conferencemanager' ) } type="datetime-local" value={ ( form.submission_start || '' ).replace( ' ', 'T' ).substring( 0, 16 ) } onChange={ ( v ) => updateField( 'submission_start' )( v.replace( 'T', ' ' ) + ':00' ) } />
					<TextControl label={ __( 'Submission Deadline', 'conferencemanager' ) } type="datetime-local" value={ ( form.submission_end || '' ).replace( ' ', 'T' ).substring( 0, 16 ) } onChange={ ( v ) => updateField( 'submission_end' )( v.replace( 'T', ' ' ) + ':00' ) } />

					<SelectControl
						label={ __( 'Submission mode', 'conferencemanager' ) }
						value={ form.submission_mode || 'form' }
						onChange={ updateField( 'submission_mode' ) }
						options={ [
							{ label: __( 'Form entry', 'conferencemanager' ), value: 'form' },
							{ label: __( 'Word template', 'conferencemanager' ), value: 'template' },
							{ label: __( 'Hybrid (form + template)', 'conferencemanager' ), value: 'hybrid' },
						] }
						help={ form.submission_mode === 'template'
							? __( 'Authors enter only the title in the form and upload a completed Word file.', 'conferencemanager' )
							: form.submission_mode === 'hybrid'
								? __( 'In addition to form entry (title, abstract, keywords), authors also upload a completed Word file.', 'conferencemanager' )
								: __( 'Authors enter the title, abstract, and keywords in the form (traditional method).', 'conferencemanager' )
						}
					/>

					{ /* テンプレートアップロード（template/hybridモード時） */ }
					{ ( form.submission_mode === 'template' || form.submission_mode === 'hybrid' ) && (
						<div style={ { padding: '12px', background: '#f0f6fc', border: '1px solid #c3c4c7', borderRadius: '4px', marginBottom: '12px' } }>
							<p style={ { margin: '0 0 8px', fontWeight: 'bold' } }>{ __( 'Word template (.docx)', 'conferencemanager' ) }</p>
							{ form.submission_template_name && (
								<p style={ { margin: '0 0 8px' } }>
									{ __( 'Current template:', 'conferencemanager' ) } <strong>{ form.submission_template_name }</strong>
									<Button
										isDestructive
										isSmall
										style={ { marginLeft: '8px' } }
										onClick={ async () => {
											if ( editingId ) {
												try {
													await apiFetch( { path: `/conf-manager/v1/events/${ editingId }/template`, method: 'DELETE' } );
													updateField( 'submission_template_name' )( '' );
												} catch ( err ) {
													setNotice( { status: 'error', message: err.message } );
												}
											}
										} }
									>{ __( 'Delete', 'conferencemanager' ) }</Button>
								</p>
							) }
							<input
								type="file"
								accept=".docx,application/vnd.openxmlformats-officedocument.wordprocessingml.document"
								onChange={ ( e ) => updateField( 'submission_template_file' )( e.target.files[ 0 ] || null ) }
							/>
							{ form.submission_template_file && editingId && (
								<Button
									variant="secondary"
									isSmall
									style={ { marginTop: '8px' } }
									onClick={ async () => {
										const fd = new FormData();
										fd.append( 'file', form.submission_template_file );
										try {
											const res = await apiFetch( {
												path: `/conf-manager/v1/events/${ editingId }/template`,
												method: 'POST',
												body: fd,
											} );
											updateField( 'submission_template_name' )( res.template_name );
											updateField( 'submission_template_file' )( null );
											setNotice( { status: 'success', message: __( 'The template has been uploaded.', 'conferencemanager' ) } );
										} catch ( err ) {
											setNotice( { status: 'error', message: err.message } );
										}
									} }
								>{ __( 'Upload template', 'conferencemanager' ) }</Button>
							) }
							{ ! editingId && <p style={ { fontSize: '12px', color: '#757575', margin: '8px 0 0' } }>{ __( 'Note: the template can be uploaded after the event is saved.', 'conferencemanager' ) }</p> }
						</div>
					) }

					{ /* 文字数上限（formまたはhybridモード時のみ） */ }
					{ ( ! form.submission_mode || form.submission_mode === 'form' || form.submission_mode === 'hybrid' ) && (
						<>
							<p style={ { fontSize: '12px', color: '#757575', margin: '12px 0 4px' } }>{ __( 'Character limit (blank = no limit) * Simple character count (full-width and half-width each count as 1)', 'conferencemanager' ) }</p>
							<div style={ { display: 'flex', gap: '12px' } }>
								<TextControl label={ __( 'Title Limit', 'conferencemanager' ) } type="number" value={ form.submission_title_limit } onChange={ updateField( 'submission_title_limit' ) } placeholder={ __( 'e.g., 100', 'conferencemanager' ) } />
								<TextControl label={ __( 'Abstract Limit', 'conferencemanager' ) } type="number" value={ form.submission_abstract_limit } onChange={ updateField( 'submission_abstract_limit' ) } placeholder={ __( 'e.g., 800', 'conferencemanager' ) } />
								<TextControl label={ __( 'Keywords Limit', 'conferencemanager' ) } type="number" value={ form.submission_keywords_limit } onChange={ updateField( 'submission_keywords_limit' ) } placeholder={ __( 'e.g., 200', 'conferencemanager' ) } />
							</div>
						</>
					) }
					{ form.submission_mode === 'template' && (
						<>
							<p style={ { fontSize: '12px', color: '#757575', margin: '12px 0 4px' } }>{ __( 'Character limit (template mode: title only)', 'conferencemanager' ) }</p>
							<TextControl label={ __( 'Title Limit', 'conferencemanager' ) } type="number" value={ form.submission_title_limit } onChange={ updateField( 'submission_title_limit' ) } placeholder={ __( 'e.g., 100', 'conferencemanager' ) } />
						</>
					) }

					{ editingId && (
						<SelectControl label={ __( 'Status', 'conferencemanager' ) } value={ form.status } onChange={ updateField( 'status' ) } options={ STATUS_OPTIONS } />
					) }

					<SelectControl label={ __( 'Tax Rate', 'conferencemanager' ) } value={ form.tax_rate } onChange={ updateField( 'tax_rate' ) } options={ TAX_RATE_OPTIONS } />

					<h3>{ __( 'Bank Transfer & Organizer Info', 'conferencemanager' ) }</h3>
					<TextControl label={ __( 'Account Holder Name', 'conferencemanager' ) } value={ form.payment_account_name } onChange={ updateField( 'payment_account_name' ) } />
					<TextareaControl label={ __( 'Bank Transfer Details', 'conferencemanager' ) } help={ __( 'Enter bank name, branch, account number, etc. separated by line breaks', 'conferencemanager' ) } value={ form.payment_account_info } onChange={ updateField( 'payment_account_info' ) } />
					<TextareaControl label={ __( 'Organizer Information', 'conferencemanager' ) } help={ __( 'Enter organizer name, postal code, address, etc. separated by line breaks', 'conferencemanager' ) } value={ form.organizer_info } onChange={ updateField( 'organizer_info' ) } />

					<h3>{ form.advance_fee_deadline ? __( 'Advance Fee (excl. tax)', 'conferencemanager' ) : __( 'Fee Settings (excl. tax)', 'conferencemanager' ) }</h3>
					<p style={ { margin: '0 0 8px', color: '#646970' } }>
						{ __( 'Leave blank or enter 0 to treat this as free (¥0).', 'conferencemanager' ) }
					</p>
					<table className="widefat" style={ { marginBottom: '16px' } }>
						<thead>
							<tr>
								<th>{ __( 'Member Type', 'conferencemanager' ) }</th>
								{ PARTICIPATION_TYPES.map( ( pt ) => (
									<th key={ pt }>{ pt === 'onsite' ? __( 'On-site', 'conferencemanager' ) : __( 'Online', 'conferencemanager' ) }</th>
								) ) }
								<th style={ { width: '40px' } }></th>
							</tr>
						</thead>
						<tbody>
							{ MEMBER_TYPES.map( ( mt ) => (
								<tr key={ mt }>
									<td>{ MEMBER_TYPE_LABELS[ mt ] }</td>
									{ PARTICIPATION_TYPES.map( ( pt ) => (
										<td key={ pt }>
											<input
												type="number"
												min="0"
												placeholder="0"
												value={ form.fee_rules?.[ mt ]?.[ pt ] ?? '' }
												onChange={ ( e ) => updateFeeRule( mt, pt, e.target.value ) }
												style={ { width: '100px' } }
											/>
										</td>
									) ) }
									<td></td>
								</tr>
							) ) }
							{ Object.keys( form.fee_labels ).map( ( key ) => (
								<tr key={ key }>
									<td>
										<input
											type="text"
											value={ form.fee_labels[ key ] }
											onChange={ ( e ) => updateCustomLabel( key, e.target.value ) }
											placeholder={ __( 'Enter type name', 'conferencemanager' ) }
											style={ { width: '120px' } }
										/>
									</td>
									{ PARTICIPATION_TYPES.map( ( pt ) => (
										<td key={ pt }>
											<input
												type="number"
												min="0"
												placeholder="0"
												value={ form.fee_rules?.[ key ]?.[ pt ] ?? '' }
												onChange={ ( e ) => updateFeeRule( key, pt, e.target.value ) }
												style={ { width: '100px' } }
											/>
										</td>
									) ) }
									<td>
										<button
											type="button"
											onClick={ () => removeCustomType( key ) }
											style={ { background: 'none', border: 'none', color: '#d63638', cursor: 'pointer', fontSize: '16px' } }
											title={ __( 'Delete', 'conferencemanager' ) }
										>&times;</button>
									</td>
								</tr>
							) ) }
						</tbody>
					</table>
					<Button variant="secondary" onClick={ addCustomType } style={ { marginBottom: '16px' } }>
						{ __( '+ Add Member Type', 'conferencemanager' ) }
					</Button>

					<h3>{ __( 'Advance & On-site Pricing', 'conferencemanager' ) }</h3>
					<TextControl
						label={ __( 'Advance Ticket Deadline', 'conferencemanager' ) }
						help={ __( 'When set, a two-tier pricing (advance / on-site) is applied. If not set, only the above pricing applies.', 'conferencemanager' ) }
						type="datetime-local"
						value={ ( form.advance_fee_deadline || '' ).replace( ' ', 'T' ).substring( 0, 16 ) }
						onChange={ ( v ) => updateField( 'advance_fee_deadline' )( v ? v.replace( 'T', ' ' ) + ':00' : '' ) }
						max={ form.date_start ? form.date_start.replace( ' ', 'T' ).substring( 0, 16 ) : undefined }
					/>

					{ form.advance_fee_deadline && (
						<>
							<h3>{ __( 'On-site Fee (excl. tax)', 'conferencemanager' ) }</h3>
							<div style={ { marginBottom: '8px' } }>
								<Button variant="secondary" isSmall onClick={ copyAdvanceToDay }>
									{ __( 'Copy from advance fees', 'conferencemanager' ) }
								</Button>
							</div>
							<table className="widefat" style={ { marginBottom: '16px' } }>
								<thead>
									<tr>
										<th>{ __( 'Member Type', 'conferencemanager' ) }</th>
										{ PARTICIPATION_TYPES.map( ( pt ) => (
											<th key={ pt }>{ pt === 'onsite' ? __( 'On-site', 'conferencemanager' ) : __( 'Online', 'conferencemanager' ) }</th>
										) ) }
										<th style={ { width: '40px' } }></th>
									</tr>
								</thead>
								<tbody>
									{ MEMBER_TYPES.map( ( mt ) => (
										<tr key={ mt }>
											<td>{ MEMBER_TYPE_LABELS[ mt ] }</td>
											{ PARTICIPATION_TYPES.map( ( pt ) => (
												<td key={ pt }>
													<input
														type="number"
														min="0"
														placeholder="0"
														value={ form.fee_rules_day?.[ mt ]?.[ pt ] ?? '' }
														onChange={ ( e ) => updateFeeRuleDay( mt, pt, e.target.value ) }
														style={ { width: '100px' } }
													/>
												</td>
											) ) }
											<td></td>
										</tr>
									) ) }
									{ Object.keys( form.fee_labels_day || {} ).map( ( key ) => (
										<tr key={ key }>
											<td>{ form.fee_labels_day[ key ] || key }</td>
											{ PARTICIPATION_TYPES.map( ( pt ) => (
												<td key={ pt }>
													<input
														type="number"
														min="0"
														placeholder="0"
														value={ form.fee_rules_day?.[ key ]?.[ pt ] ?? '' }
														onChange={ ( e ) => updateFeeRuleDay( key, pt, e.target.value ) }
														style={ { width: '100px' } }
													/>
												</td>
											) ) }
											<td>
												<button
													type="button"
													onClick={ () => removeCustomTypeDay( key ) }
													style={ { background: 'none', border: 'none', color: '#d63638', cursor: 'pointer', fontSize: '16px' } }
													title={ __( 'Delete from on-site fee', 'conferencemanager' ) }
												>&times;</button>
											</td>
										</tr>
									) ) }
								</tbody>
							</table>

							<TextareaControl
								label={ __( 'Registration Form Notice', 'conferencemanager' ) }
								help={ __( 'Notice about advance/on-site pricing. Shown on the registration form.', 'conferencemanager' ) }
								value={ form.advance_fee_notice }
								onChange={ updateField( 'advance_fee_notice' ) }
								placeholder={ __( 'e.g., Advance pricing is available until MM/DD. After the deadline, on-site pricing applies.', 'conferencemanager' ) }
							/>
						</>
					) }

					<div style={ { display: 'flex', gap: '8px' } }>
						<Button variant="primary" onClick={ handleSubmit } isBusy={ api.loading }>
							{ editingId ? __( 'Update', 'conferencemanager' ) : __( 'Create', 'conferencemanager' ) }
						</Button>
						{ editingId && (
							<Button variant="secondary" isDestructive onClick={ () => { setModalOpen( false ); handleDelete( editingId ); } }>
								{ __( 'Cancel', 'conferencemanager' ) }
							</Button>
						) }
						<Button variant="tertiary" onClick={ () => setModalOpen( false ) }>
							{ __( 'Close', 'conferencemanager' ) }
						</Button>
					</div>
				</Modal>
			) }
		</div>
	);
}
