/**
 * SEOvault FAQ block editor.
 *
 * Authors edit visible Q/A content like a normal block. Schema emission
 * is deferred; this UI only reports setup readiness.
 */

import { __, _n, sprintf } from '@wordpress/i18n';
import {
	useBlockProps,
	InspectorControls,
	RichText,
	BlockControls,
} from '@wordpress/block-editor';
import {
	PanelBody,
	TextControl,
	TextareaControl,
	SelectControl,
	ToggleControl,
	Button,
	ToolbarGroup,
	ToolbarButton,
	Notice,
} from '@wordpress/components';
import { useEffect, useRef } from '@wordpress/element';
import {
	createEmptyItem,
	ensureStableIds,
	insertItem,
	updateItemAt,
	removeItemAt,
	reorderItems,
} from './utils/items';
import { getFaqSetupStatus } from './utils/setup-status';

const STYLE_OPTIONS = [
	{ label: __('Clean FAQ', 'seovault-ai'), value: 'clean-faq' },
	{ label: __('Accordion cards', 'seovault-ai'), value: 'accordion-cards' },
	{ label: __('Minimal SEO', 'seovault-ai'), value: 'minimal-seo' },
	{ label: __('Soft help center', 'seovault-ai'), value: 'soft-help-center' },
	{ label: __('Bordered editorial', 'seovault-ai'), value: 'bordered-editorial' },
	{ label: __('Compact FAQ', 'seovault-ai'), value: 'compact-faq' },
	{ label: __('Dark FAQ', 'seovault-ai'), value: 'dark-faq' },
];

const COLOR_OPTIONS = [
	{ label: __('Blue', 'seovault-ai'), value: 'blue' },
	{ label: __('Green', 'seovault-ai'), value: 'green' },
	{ label: __('Purple', 'seovault-ai'), value: 'purple' },
	{ label: __('Orange', 'seovault-ai'), value: 'orange' },
	{ label: __('Dark', 'seovault-ai'), value: 'dark' },
	{ label: __('Neutral', 'seovault-ai'), value: 'neutral' },
	{ label: __('Midnight', 'seovault-ai'), value: 'midnight' },
];

const DENSITY_OPTIONS = [
	{ label: __('Compact', 'seovault-ai'), value: 'compact' },
	{ label: __('Comfortable', 'seovault-ai'), value: 'comfortable' },
	{ label: __('Spacious', 'seovault-ai'), value: 'spacious' },
];

/**
 * @param {Object}   props
 * @param {Object}   props.attributes
 * @param {Function} props.setAttributes
 * @return {JSX.Element} Editor.
 */
export default function Edit({ attributes, setAttributes }) {
	const {
		heading = '',
		intro = '',
		items = [],
		displayMode = 'accordion',
		stylePreset = 'accordion-cards',
		colorPreset = 'blue',
		density = 'comfortable',
		openFirstItem = false,
		showQuestionNumbers = false,
		sharpCorners = false,
		schemaVersion = 1,
	} = attributes;

	const normalizedItems = ensureStableIds(items);
	const setup = getFaqSetupStatus({ items: normalizedItems });
	const seededRef = useRef(false);
	const listRef = useRef(null);

	// Seed stable IDs once when the block mounts with empty/missing ids.
	useEffect(() => {
		if (seededRef.current) {
			return;
		}
		seededRef.current = true;
		const needsSeed =
			!Array.isArray(items) ||
			items.length === 0 ||
			items.some((item) => !item || !item.id) ||
			schemaVersion !== 1;
		if (needsSeed) {
			const nextItems =
				!Array.isArray(items) || items.length === 0
					? [createEmptyItem(), createEmptyItem()]
					: ensureStableIds(items);
			setAttributes({
				items: nextItems,
				schemaVersion: 1,
			});
		}
	}, [items, schemaVersion, setAttributes]);

	const blockProps = useBlockProps({
		className: [
			'seovault-faq-block-editor',
			`seovault-faq-block-editor--${displayMode}`,
			`is-setup-${setup.status}`,
		].join(' '),
		'data-faq-setup': setup.status,
	});

	const setItems = (next) => {
		setAttributes({ items: ensureStableIds(next) });
	};

	const focusItemQuestion = (index) => {
		window.requestAnimationFrame(() => {
			const root = listRef.current;
			if (!root) {
				return;
			}
			const field = root.querySelector(
				`[data-faq-editor-index="${index}"] .seovault-faq-block-editor__question input, [data-faq-editor-index="${index}"] .seovault-faq-block-editor__question textarea`
			);
			if (field && typeof field.focus === 'function') {
				field.focus();
			}
		});
	};

	const onAdd = () => {
		const next = insertItem(normalizedItems);
		setItems(next);
		focusItemQuestion(next.length - 1);
	};

	const onRemove = (index) => {
		setItems(removeItemAt(normalizedItems, index));
	};

	const onMove = (index, direction) => {
		const to = index + direction;
		setItems(reorderItems(normalizedItems, index, to));
	};

	const noticeStatus =
		setup.status === 'ready_for_schema'
			? 'success'
			: setup.status === 'incomplete'
				? 'warning'
				: 'info';

	const setupLabel =
		setup.status === 'ready_for_schema'
			? __('FAQ content ready (schema pending save)', 'seovault-ai')
			: setup.status === 'incomplete'
				? __('FAQ setup incomplete', 'seovault-ai')
				: __('FAQ setup', 'seovault-ai');

	const setupMessage =
		setup.status === 'ready_for_schema'
			? __(
					'Visible FAQ content is ready. Schema publishing is handled separately by SEOvault when this post is saved — this block does not inject JSON-LD by itself.',
					'seovault-ai'
				)
			: setup.status === 'incomplete'
				? __(
						'Finish at least one complete question and answer. Incomplete rows stay in the editor but are excluded from schema.',
						'seovault-ai'
					)
				: __(
						'Add questions and answers readers will see. Schema is not published until a complete pair exists.',
						'seovault-ai'
					);

	return (
		<>
			<BlockControls>
				<ToolbarGroup>
					<ToolbarButton
						icon="plus"
						label={__('Add question', 'seovault-ai')}
						onClick={onAdd}
					/>
				</ToolbarGroup>
			</BlockControls>
			<InspectorControls>
				<PanelBody title={__('FAQ display', 'seovault-ai')} initialOpen={true}>
					<SelectControl
						label={__('Display mode', 'seovault-ai')}
						help={__(
							'Accordion uses accessible details/summary markup on the front end. Static shows all answers expanded.',
							'seovault-ai'
						)}
						value={displayMode}
						options={[
							{ label: __('Accordion', 'seovault-ai'), value: 'accordion' },
							{ label: __('Static', 'seovault-ai'), value: 'static' },
						]}
						onChange={(value) => setAttributes({ displayMode: value })}
					/>
					<SelectControl
						label={__('Style preset', 'seovault-ai')}
						value={stylePreset}
						options={STYLE_OPTIONS}
						onChange={(value) => setAttributes({ stylePreset: value })}
					/>
					<SelectControl
						label={__('Color', 'seovault-ai')}
						value={colorPreset}
						options={COLOR_OPTIONS}
						onChange={(value) => setAttributes({ colorPreset: value })}
					/>
					<SelectControl
						label={__('Density', 'seovault-ai')}
						value={density}
						options={DENSITY_OPTIONS}
						onChange={(value) => setAttributes({ density: value })}
					/>
					<ToggleControl
						label={__('Open first item', 'seovault-ai')}
						help={__(
							'Only applies to accordion display. First complete item opens by default.',
							'seovault-ai'
						)}
						checked={!!openFirstItem}
						onChange={(value) => setAttributes({ openFirstItem: value })}
						disabled={displayMode !== 'accordion'}
					/>
					<ToggleControl
						label={__('Show question numbers', 'seovault-ai')}
						checked={!!showQuestionNumbers}
						onChange={(value) => setAttributes({ showQuestionNumbers: value })}
					/>
					<ToggleControl
						label={__('Sharp corners', 'seovault-ai')}
						checked={!!sharpCorners}
						onChange={(value) => setAttributes({ sharpCorners: value })}
					/>
				</PanelBody>
			</InspectorControls>
			<div {...blockProps}>
				<Notice
					status={noticeStatus}
					isDismissible={false}
					className="seovault-faq-block-editor__status"
					spokenMessage={`${setupLabel}. ${setupMessage}`}
				>
					<strong>{setupLabel}</strong>
					<span className="seovault-faq-block-editor__status-text">
						{' '}
						{setupMessage}
					</span>
					{setup.completeCount > 0 && (
						<span className="seovault-faq-block-editor__status-count" aria-live="polite">
							{' '}
							{sprintfComplete(setup.completeCount)}
						</span>
					)}
				</Notice>
				<div className="seovault-faq-block-editor__header">
					<TextControl
						label={__('Heading', 'seovault-ai')}
						value={heading}
						onChange={(value) => setAttributes({ heading: value })}
						placeholder={__('Frequently Asked Questions', 'seovault-ai')}
					/>
					<TextareaControl
						label={__('Intro', 'seovault-ai')}
						value={intro}
						onChange={(value) => setAttributes({ intro: value })}
						rows={2}
						placeholder={__(
							'Optional short introduction for readers.',
							'seovault-ai'
						)}
					/>
				</div>
				<div
					className="seovault-faq-block-editor__list"
					ref={listRef}
					role="list"
					aria-label={__('FAQ questions', 'seovault-ai')}
				>
					{normalizedItems.map((item, index) => (
						<div
							className="seovault-faq-block-editor__item"
							key={item.id}
							role="listitem"
							data-faq-editor-index={index}
							data-faq-item-id={item.id}
						>
							<div className="seovault-faq-block-editor__item-toolbar">
								<span className="seovault-faq-block-editor__item-label">
									{showQuestionNumbers
										? `${index + 1}. `
										: ''}
									{__('Question', 'seovault-ai')}
								</span>
								<div className="seovault-faq-block-editor__item-actions">
									<Button
										variant="tertiary"
										size="small"
										disabled={index === 0}
										onClick={() => onMove(index, -1)}
										aria-label={__('Move question up', 'seovault-ai')}
									>
										{__('Up', 'seovault-ai')}
									</Button>
									<Button
										variant="tertiary"
										size="small"
										disabled={index === normalizedItems.length - 1}
										onClick={() => onMove(index, 1)}
										aria-label={__('Move question down', 'seovault-ai')}
									>
										{__('Down', 'seovault-ai')}
									</Button>
									<Button
										isDestructive
										variant="tertiary"
										size="small"
										onClick={() => onRemove(index)}
										aria-label={__('Remove question', 'seovault-ai')}
									>
										{__('Remove', 'seovault-ai')}
									</Button>
								</div>
							</div>
							<div className="seovault-faq-block-editor__question">
								<TextControl
									hideLabelFromVision
									label={__('Question', 'seovault-ai')}
									value={item.question || ''}
									onChange={(value) =>
										setItems(updateItemAt(normalizedItems, index, { question: value }))
									}
									placeholder={__('Write the question…', 'seovault-ai')}
								/>
							</div>
							<div className="seovault-faq-block-editor__answer">
								<span className="components-base-control__label">
									{__('Answer', 'seovault-ai')}
								</span>
								<RichText
									tagName="div"
									className="seovault-faq-block-editor__answer-rich"
									value={item.answer || ''}
									onChange={(value) =>
										setItems(
											updateItemAt(normalizedItems, index, { answer: value })
										)
									}
									placeholder={__('Write the answer…', 'seovault-ai')}
									allowedFormats={[
										'core/bold',
										'core/italic',
										'core/link',
									]}
								/>
							</div>
						</div>
					))}
				</div>
				<div className="seovault-faq-block-editor__footer">
					<Button variant="secondary" onClick={onAdd}>
						{__('Add question', 'seovault-ai')}
					</Button>
				</div>
			</div>
		</>
	);
}

/**
 * @param {number} count Complete pair count.
 * @return {string} Localized count phrase.
 */
function sprintfComplete(count) {
	return sprintf(
		/* translators: %d: number of complete FAQ question/answer pairs. */
		_n('%d complete pair.', '%d complete pairs.', count, 'seovault-ai'),
		count
	);
}
