/**
 * Streams tab: "Preview & Detect Fields" — fetch one page of the API without
 * saving anything, show what came back, and make the field names clickable
 * so non-technical users can build their display without guessing.
 */
( function ( wp ) {
	'use strict';

	const apiFetch = wp && wp.apiFetch;
	const button = document.getElementById( 'datastream-stream-preview' );
	const result = document.getElementById( 'datastream-preview-result' );

	if ( ! apiFetch || ! button || ! result ) {
		return;
	}

	function el( tag, className, text ) {
		const node = document.createElement( tag );
		if ( className ) {
			node.className = className;
		}
		if ( text ) {
			node.textContent = text;
		}
		return node;
	}

	button.addEventListener( 'click', async function () {
		const stream = button.getAttribute( 'data-stream' ) || '';
		const urlField = document.getElementById( 'ds-url' );
		const url = urlField ? urlField.value.trim() : '';

		result.innerHTML = '';
		result.appendChild( el( 'p', 'description', 'Fetching…' ) );
		button.disabled = true;

		try {
			const data = await apiFetch( {
				path: '/datastream/v1/preview',
				method: 'POST',
				data: { stream: stream, url: stream ? '' : url },
			} );

			result.innerHTML = '';

			const summary = el( 'p', '' );
			summary.appendChild( el( 'strong', '', data.success ? 'Connected. ' : 'Failed. ' ) );
			summary.appendChild(
				document.createTextNode(
					( data.message || '' ) +
						( data.success
							? ' ' + data.item_count + ' items detected, ' + data.body_bytes + ' bytes, ' + data.duration_ms + ' ms.'
							: '' )
				)
			);
			result.appendChild( summary );

			if ( data.fields && data.fields.length ) {
				result.appendChild( el( 'p', 'description', 'Detected fields — click to copy for the fields="" setting:' ) );
				const chips = el( 'p', 'datastream-field-chips' );

				data.fields.forEach( function ( field ) {
					const chip = el( 'button', 'button button-small', field );
					chip.type = 'button';
					chip.style.marginRight = '4px';
					chip.style.marginBottom = '4px';
					chip.addEventListener( 'click', function () {
						if ( navigator.clipboard ) {
							navigator.clipboard.writeText( field );
						}
						chip.textContent = field + ' ✓';
						setTimeout( function () {
							chip.textContent = field;
						}, 1200 );
					} );
					chips.appendChild( chip );
				} );

				result.appendChild( chips );
			}

			if ( data.sample ) {
				const pre = el( 'pre', 'datastream-payload is-open' );
				pre.style.maxHeight = '260px';
				pre.style.overflow = 'auto';
				pre.textContent = JSON.stringify( data.sample, null, 2 );
				result.appendChild( el( 'p', 'description', 'First record:' ) );
				result.appendChild( pre );
			}
		} catch ( error ) {
			result.innerHTML = '';
			result.appendChild( el( 'p', '', 'Preview failed: ' + ( error.message || 'unknown error' ) ) );
		} finally {
			button.disabled = false;
		}
	} );
} )( window.wp );
