/**
 * Field anchors used by "fix" links in provider error messages, e.g.
 * admin.php?page=wc-ai-content-generator#wtofe_ai_model_description
 * (see AI_Content_Generator_Helper_Diagnostics). Each anchor is mapped to the
 * page that holds the field, so the router can open that page first.
 */
const ANCHOR_PAGES: Array<[ RegExp, string ]> = [
    [ /^wtofe-api-key-row$/, 'models' ],
    [ /^wtofe_ai_model_(title|description|short_description|brands|tags|image_generation)$/, 'models' ],
    [ /^wtofe_ai_request_timeout$/, 'advanced' ],
    [ /^wtofe_ai_model_review_summary$/, 'review-summary' ],
    [ /^wtofe_ai_model_meta$/, 'seo-meta' ],
    [ /^wtofe_chatbot_model$/, 'chatbot' ],
];

const handlers = new Map<string, () => void>();

/** @return Page ID, or null when the anchor is unknown. */
export function pageForAnchor( id: string ): string | null {
    const match = ANCHOR_PAGES.find( ( [ pattern ] ) => pattern.test( id ) );
    return match ? match[ 1 ] : null;
}

/**
 * The field anchor in a URL hash ("#wtofe_ai_model_title"), as opposed to a
 * route ("#/models").
 */
export function anchorFromHash( hash: string ): string | null {
    const match = hash.match( /^#([A-Za-z][\w-]*)$/ );
    return match ? match[ 1 ] : null;
}

/**
 * Lets a component prepare its field before it is focused (e.g. the saved
 * API key switches to edit mode). Returns an unsubscribe function.
 */
export function onAnchor( id: string, handler: () => void ): () => void {
    handlers.set( id, handler );
    return () => {
        handlers.delete( id );
    };
}

/**
 * Scrolls to the field, focuses it and outlines it for a moment. Retries
 * briefly, since the field may only render after the page switch or the
 * anchor handler's state change.
 */
export function focusAnchor( id: string ): void {
    handlers.get( id )?.();

    const attempt = ( remaining: number ) => {
        const target = document.getElementById( id );
        if ( ! target ) {
            if ( remaining > 0 ) {
                window.setTimeout( () => attempt( remaining - 1 ), 50 );
            }
            return;
        }

        target.scrollIntoView( { behavior: 'smooth', block: 'center' } );
        // Model pickers are buttons (Radix Select triggers).
        if ( target.matches( 'input, select, textarea, button' ) ) {
            target.focus( { preventScroll: true } );
        }

        target.classList.add( 'wtofe-highlight' );
        window.setTimeout( () => target.classList.remove( 'wtofe-highlight' ), 2000 );
    };

    window.setTimeout( () => attempt( 10 ), 0 );
}

/**
 * Turns a field anchor in the URL ("#wtofe_ai_model_title") into the route of
 * its page ("#/models"), then focuses the field once that page renders.
 * Runs now, for the URL the screen was opened with, and on every popstate,
 * which fires for in-page fix links before the router reads the new URL.
 */
export function watchFieldAnchors(): void {
    const handle = () => {
        const anchor = anchorFromHash( window.location.hash );
        const page   = anchor && pageForAnchor( anchor );
        if ( anchor && page ) {
            window.history.replaceState( window.history.state, '', `#/${ page }` );
            focusAnchor( anchor );
        }
    };

    handle();
    window.addEventListener( 'popstate', handle );
}
