/**
 * Shared admin-screen behaviours (enqueued on every plugin screen; each block
 * no-ops unless its markup is present).
 */
( function () {
	'use strict';

	// New-stocktake form: the category picker only applies to category scope.
	var scopeSel = document.getElementById( 'stwc-scope-type' );
	if ( scopeSel ) {
		scopeSel.addEventListener( 'change', function () {
			document.getElementById( 'stwc-cat-wrap' ).style.display = this.value === 'category' ? 'block' : 'none';
		} );
	}

	// Language switcher dropdown (toggle, outside-click close, Escape).
	document.querySelectorAll( '[data-stwc-lang]' ).forEach( function ( w ) {
		if ( w.dataset.wired ) { return; }
		w.dataset.wired = '1';
		var t = w.querySelector( '.stwc-lang__toggle' ), m = w.querySelector( '.stwc-lang__menu' );
		t.addEventListener( 'click', function ( e ) { e.stopPropagation(); var open = m.hidden; m.hidden = ! open; t.setAttribute( 'aria-expanded', String( open ) ); } );
		document.addEventListener( 'click', function ( e ) { if ( ! w.contains( e.target ) ) { m.hidden = true; t.setAttribute( 'aria-expanded', 'false' ); } } );
		w.addEventListener( 'keydown', function ( e ) { if ( e.key === 'Escape' ) { m.hidden = true; t.setAttribute( 'aria-expanded', 'false' ); t.focus(); } } );
	} );

	// Background snapshot notice: poll by full reload until the build finishes.
	if ( document.querySelector( '[data-stwc-autorefresh]' ) ) {
		setTimeout( function () { location.reload(); }, 5000 );
	}
}() );
