/**
 * Stream form behavior: conditional sections, repeater rows (which keep the
 * stored JSON format without ever showing JSON), and remembering which
 * cards are open.
 */
( function () {
	'use strict';

	const form = document.getElementById( 'datastream-stream-form' );

	if ( ! form ) {
		return;
	}

	// ------------------------------------------------------------ Conditionals

	function toggle( selector, show ) {
		form.querySelectorAll( selector ).forEach( function ( node ) {
			node.hidden = ! show;
		} );
	}

	const pagination = form.querySelector( '[name="stream[pagination]"]' );
	if ( pagination ) {
		const update = function () {
			toggle( '[data-ds-show-pagination]', 'none' !== pagination.value );
		};
		pagination.addEventListener( 'change', update );
		update();
	}

	const postType = form.querySelector( '[name="stream[post_type]"]' );
	if ( postType ) {
		const update = function () {
			toggle( '[data-ds-show-posts]', '' !== postType.value );
			toggle( '[data-ds-show-woo]', 'product' === postType.value );
		};
		postType.addEventListener( 'change', update );
		update();
	}

	const oauthToggle = document.getElementById( 'ds-oauth-toggle' );
	const oauthFields = document.getElementById( 'ds-oauth-fields' );
	if ( oauthToggle && oauthFields ) {
		oauthToggle.addEventListener( 'change', function () {
			oauthFields.hidden = ! oauthToggle.checked;
			if ( ! oauthToggle.checked ) {
				// Turning OAuth off clears the token URL, which disables it.
				const url = document.getElementById( 'ds-oauth-url' );
				if ( url ) {
					url.value = '';
				}
			}
		} );
	}

	// ------------------------------------------------------------- Repeaters

	form.querySelectorAll( '[data-ds-repeater]' ).forEach( function ( repeater ) {
		const rows = repeater.querySelector( '.ds-repeater-rows' );
		const template = repeater.querySelector( '.ds-repeater-template' );
		const addButton = repeater.querySelector( '.ds-rep-add' );
		const target = document.getElementById( repeater.getAttribute( 'data-ds-target' ) );

		if ( ! rows || ! template || ! addButton || ! target ) {
			return;
		}

		addButton.addEventListener( 'click', function () {
			rows.appendChild( template.content.cloneNode( true ) );
			const added = rows.lastElementChild.querySelector( '.ds-rep-key' );
			if ( added ) {
				added.focus();
			}
		} );

		repeater.addEventListener( 'click', function ( event ) {
			if ( event.target.classList.contains( 'ds-rep-remove' ) ) {
				event.target.closest( '.ds-repeater-row' ).remove();
			}
		} );

		// Serialize rows into the hidden JSON field on submit.
		form.addEventListener( 'submit', function () {
			const map = {};
			rows.querySelectorAll( '.ds-repeater-row' ).forEach( function ( row ) {
				const key = row.querySelector( '.ds-rep-key' );
				const value = row.querySelector( '.ds-rep-value' );
				if ( key && value && key.value.trim() && value.value.trim() ) {
					map[ key.value.trim() ] = value.value.trim();
				}
			} );
			target.value = Object.keys( map ).length ? JSON.stringify( map ) : '';
		} );
	} );

	// -------------------------------------------------- Remember open cards

	const cards = document.querySelectorAll( '.ds-card' );
	cards.forEach( function ( card, index ) {
		const key = 'ds-card-' + index;
		try {
			const saved = window.localStorage.getItem( key );
			if ( null !== saved ) {
				card.open = '1' === saved;
			}
			card.addEventListener( 'toggle', function () {
				window.localStorage.setItem( key, card.open ? '1' : '0' );
			} );
		} catch ( e ) {
			// Private browsing: cards just use their server-side defaults.
		}
	} );
} )();
