import Popup, { PopupState } from './parts/popup';
import { requestAccessibleDocument } from './parts/request';

const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

/**
 * Returns the PDF URL if a click on this link should open the popup, otherwise null.
 * Only PDFs of this site are handled: they must be in the Media Library to be processed.
 */
function pdfUrlFromLink(link: HTMLAnchorElement): string | null {
    let url: URL;
    try {
        url = new URL(link.href, window.location.href);
    } catch {
        return null;
    }
    if (!/\.pdf$/i.test(url.pathname)) {
        return null;
    }
    return url.origin === window.location.origin ? url.href : null;
}

function init(): void {
    if (typeof accessible_docs_object === 'undefined' || accessible_docs_object.is_popup_enabled !== '1') {
        return;
    }
    const root = document.getElementById('accessible-docs-popup');
    if (!root) {
        return;
    }

    const popup = new Popup(root);
    const form = root.querySelector<HTMLFormElement>('.js-accessible-docs-form');
    const emailInput = root.querySelector<HTMLInputElement>('.js-accessible-docs-email');
    const emailError = root.querySelector<HTMLElement>('.js-accessible-docs-popup-error');
    let currentPdf = '';

    document.addEventListener('click', (event) => {
        // Let the browser handle Ctrl/Cmd/Shift/Alt-clicks and non-primary buttons (open in new tab etc.).
        if (event.defaultPrevented || event.button !== 0 || event.ctrlKey || event.metaKey || event.shiftKey || event.altKey) {
            return;
        }
        const link = (event.target as Element | null)?.closest?.('a[href]') as HTMLAnchorElement | null;
        if (!link || root.contains(link)) {
            return;
        }
        const pdfUrl = pdfUrlFromLink(link);
        if (!pdfUrl) {
            return;
        }
        event.preventDefault();
        currentPdf = pdfUrl;
        popup.open(pdfUrl, link);
    });

    form?.addEventListener('submit', async (event) => {
        event.preventDefault();
        if (!emailInput || !currentPdf) {
            return;
        }

        const email = emailInput.value.trim();
        if (!EMAIL_PATTERN.test(email)) {
            emailInput.setAttribute('aria-invalid', 'true');
            if (emailError) {
                emailError.style.display = 'block';
            }
            emailInput.focus();
            return;
        }
        emailInput.removeAttribute('aria-invalid');
        if (emailError) {
            emailError.style.display = 'none';
        }

        popup.setLoading(true);
        let state: PopupState;
        try {
            const status = await requestAccessibleDocument(email, currentPdf);
            state = status === 'completed' ? 'completed' : 'in-process';
        } catch (error) {
            console.error('AccessibleDocs:', error);
            state = 'error';
        }
        popup.setLoading(false);
        popup.setState(state);
    });
}

if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', init);
} else {
    init();
}
