const PREVIEW_CLASS = 'is-previewing';

/**
 * Toolbar "Aperçu" button: hides every editing affordance (CSS, keyed on
 * `body.is-previewing`) and makes `.editor-content` `inert` so nothing in it can be
 * clicked, focused or typed into. Purely client-side — no editor instance is destroyed,
 * so unsaved changes survive the round trip.
 */
export class PreviewToggle {
    private readonly button: HTMLButtonElement | null;
    private readonly content: HTMLElement | null;

    constructor() {
        this.button = document.getElementById('preview-toggle-btn') as HTMLButtonElement | null;
        this.content = document.querySelector<HTMLElement>('.editor-content');
    }

    public initialize(): void {
        if (!this.button || !this.content) return;

        this.button.addEventListener('click', (e) => {
            e.preventDefault();
            this.setPreviewing(!this.isPreviewing());
        });

        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape' && this.isPreviewing()) {
                this.setPreviewing(false);
            }
        });
    }

    private isPreviewing(): boolean {
        return this.button?.getAttribute('aria-pressed') === 'true';
    }

    private setPreviewing(previewing: boolean): void {
        if (!this.button || !this.content) return;

        if (previewing) {
            // Close any in-progress edit (and its MediumEditor toolbar) before freezing the content.
            (document.activeElement as HTMLElement | null)?.blur();
        }

        document.body.classList.toggle(PREVIEW_CLASS, previewing);
        this.content.toggleAttribute('inert', previewing);

        const label = previewing ? "Retour à l'édition" : 'Aperçu';
        const iconName = previewing ? 'pencil' : 'monitor';
        this.button.setAttribute('aria-pressed', String(previewing));
        this.button.setAttribute('aria-label', label);
        this.button.setAttribute('data-tooltip', label);

        const icon = this.button.querySelector<HTMLElement>('.icon');
        if (icon) {
            icon.className = `icon icon--${iconName} editor-toolbar__action-icon`;
            icon.style.setProperty('--icon-url', `url('/build/images/icons/${iconName}.svg')`);
        }
    }
}
