/**
 * BWD Support Copilot — popup chat panel.
 *
 * Host-agnostic: reads its per-instance configuration from the
 * data-bwdsc-config attribute rendered by class-bwd-support-copilot.php,
 * so multiple copilot instances can coexist on one admin page.
 *
 * The widget is read-only by design: it renders replies as escaped text,
 * keeps the conversation in page memory only, and every server interaction
 * goes through the host plugin's AJAX proxy (the hub token never reaches
 * the browser).
 */
( function () {
	'use strict';

	function initInstance( root ) {
		var cfg;
		try {
			cfg = JSON.parse( root.getAttribute( 'data-bwdsc-config' ) || '{}' );
		} catch ( e ) {
			return;
		}
		var S = cfg.strings || {};

		var launcher   = root.querySelector( '.bwdsc-launcher' );
		var panel      = root.querySelector( '.bwdsc-panel' );
		var consentBox = root.querySelector( '.bwdsc-consent' );
		var chatBox    = root.querySelector( '.bwdsc-chat' );
		var messages   = root.querySelector( '.bwdsc-messages' );
		var followup   = root.querySelector( '.bwdsc-followup' );
		var statusBar  = root.querySelector( '.bwdsc-status' );
		var input      = root.querySelector( '.bwdsc-input' );
		var sendBtn    = root.querySelector( '.bwdsc-send' );

		if ( ! launcher || ! panel || ! messages || ! input || ! sendBtn ) {
			return;
		}

		// Conversation state — page-lifetime only, sent in full each turn
		// (the hub is stateless).
		var history      = [];
		var lastCategory = 'other';
		var pending      = false;
		var screenId     = ( document.body.className.match( /(?:^|\s)(toplevel_page_[^\s]+|[^\s]+_page_[^\s]+)/ ) || [ '', '' ] )[ 1 ] || '';

		// ------------------------------------------------------------------
		// Helpers
		// ------------------------------------------------------------------

		function post( action, fields ) {
			var body = new FormData();
			body.append( 'action', action );
			body.append( 'nonce', cfg.nonce );
			body.append( 'screen', screenId );
			Object.keys( fields || {} ).forEach( function ( k ) {
				body.append( k, fields[ k ] );
			} );
			return fetch( cfg.ajaxUrl, { method: 'POST', credentials: 'same-origin', body: body } )
				.then( function ( r ) { return r.json(); } );
		}

		function addMessage( role, text ) {
			var el = document.createElement( 'div' );
			el.className = 'bwdsc-msg bwdsc-msg--' + role;
			el.textContent = text; // textContent = escaped by construction.
			messages.appendChild( el );
			messages.scrollTop = messages.scrollHeight;
			return el;
		}

		function setPending( on ) {
			pending = on;
			sendBtn.disabled = on;
			input.disabled = on;
		}

		function clearFollowup() {
			followup.hidden = true;
			followup.innerHTML = '';
		}

		/**
		 * Shows an error inside the consent view (e.g. the user lacks the
		 * capability to accept consent for the site).
		 */
		function showConsentError( text ) {
			if ( ! consentBox ) {
				return;
			}
			var el = consentBox.querySelector( '.bwdsc-consent__error' );
			if ( ! el ) {
				el = document.createElement( 'p' );
				el.className = 'bwdsc-consent__error';
				consentBox.appendChild( el );
			}
			el.textContent = text;
		}

		/**
		 * Marks an assistant message as generated by the site's own AI.
		 */
		function addLocalBadge( msgEl ) {
			var badge = document.createElement( 'span' );
			badge.className = 'bwdsc-msg__badge';
			badge.textContent = S.answered_local || "Answered by your site's AI";
			badge.title = S.answered_local_title || '';
			msgEl.appendChild( badge );
		}

		/**
		 * Shows the free-tier allowance line when the hub reports one.
		 */
		function updateAllowance( data ) {
			if ( 'free' === data.tier && null !== data.remaining_allowance && undefined !== data.remaining_allowance ) {
				statusBar.textContent = ( S.allowance_left || '%d left' ).replace( '%d', String( data.remaining_allowance ) );
				statusBar.hidden = false;
			}
		}

		// ------------------------------------------------------------------
		// Escalation UI
		// ------------------------------------------------------------------

		function showEscalationForm() {
			followup.innerHTML = '';
			followup.hidden = false;

			var label = document.createElement( 'label' );
			label.className = 'bwdsc-escalate__label';
			label.textContent = S.escalate_confirm_label || 'Your email for ticket replies';

			var email = document.createElement( 'input' );
			email.type = 'email';
			email.className = 'bwdsc-escalate__email';
			email.value = cfg.email || '';
			email.title = S.escalate_confirm_hint || '';

			var hint = document.createElement( 'p' );
			hint.className = 'bwdsc-escalate__hint';
			hint.textContent = S.escalate_confirm_hint || '';

			var send = document.createElement( 'button' );
			send.type = 'button';
			send.className = 'button button-primary bwdsc-escalate__send';
			send.textContent = S.escalate_send || 'Create ticket';

			var cancel = document.createElement( 'button' );
			cancel.type = 'button';
			cancel.className = 'button bwdsc-escalate__cancel';
			cancel.textContent = S.escalate_cancel || 'Cancel';

			cancel.addEventListener( 'click', clearFollowup );
			send.addEventListener( 'click', function () {
				if ( pending ) {
					return;
				}
				setPending( true );
				send.disabled = true;
				post( cfg.actionEscalate, {
					email: email.value,
					category: lastCategory,
					history: JSON.stringify( history.slice( -cfg.maxHistory ) )
				} ).then( function ( res ) {
					setPending( false );
					if ( res && res.success ) {
						clearFollowup();
						addMessage( 'system', ( S.escalated_prefix || 'Ticket created:' ) + ' #' + res.data.ticket_id + '. ' + ( res.data.message || '' ) );
					} else {
						send.disabled = false;
						addMessage( 'system', ( res && res.data && res.data.message ) || S.error_generic || 'Error.' );
					}
				} ).catch( function () {
					setPending( false );
					send.disabled = false;
					addMessage( 'system', S.error_generic || 'Error.' );
				} );
			} );

			followup.appendChild( label );
			followup.appendChild( email );
			followup.appendChild( send );
			followup.appendChild( cancel );
			followup.appendChild( hint );
			email.focus();
		}

		/**
		 * After each assistant reply: escalation button (escalatable
		 * categories) or the soft-gate line with a low-key "escalate anyway"
		 * link (widget-only categories — allowed per spec, hub tags
		 * howto-deflected).
		 */
		function showFollowup( escalationOffered ) {
			followup.innerHTML = '';
			followup.hidden = false;

			if ( escalationOffered ) {
				var offer = document.createElement( 'span' );
				offer.className = 'bwdsc-followup__text';
				offer.textContent = S.escalate_offer || '';

				var btn = document.createElement( 'button' );
				btn.type = 'button';
				btn.className = 'button bwdsc-followup__escalate';
				btn.textContent = S.escalate_button || 'Send to support';
				btn.addEventListener( 'click', showEscalationForm );

				followup.appendChild( offer );
				followup.appendChild( btn );
			} else {
				var gate = document.createElement( 'span' );
				gate.className = 'bwdsc-followup__text bwdsc-followup__softgate';
				gate.textContent = S.soft_gate || '';

				var anyway = document.createElement( 'a' );
				anyway.href = '#';
				anyway.className = 'bwdsc-followup__anyway';
				anyway.textContent = S.escalate_anyway || 'Still need to raise a ticket?';
				anyway.addEventListener( 'click', function ( e ) {
					e.preventDefault();
					showEscalationForm();
				} );

				followup.appendChild( gate );
				followup.appendChild( anyway );
			}
		}

		// ------------------------------------------------------------------
		// Chat
		// ------------------------------------------------------------------

		function sendMessage() {
			var text = input.value.trim();
			if ( '' === text || pending ) {
				return;
			}
			input.value = '';
			clearFollowup();
			addMessage( 'user', text );

			var thinking = addMessage( 'assistant', S.thinking || '…' );
			thinking.classList.add( 'bwdsc-msg--thinking' );
			setPending( true );

			post( cfg.actionChat, {
				message: text,
				history: JSON.stringify( history.slice( -cfg.maxHistory ) )
			} ).then( function ( res ) {
				setPending( false );
				thinking.remove();
				if ( res && res.success ) {
					var d = res.data;
					var msgEl = addMessage( 'assistant', d.reply );
					if ( 'local' === d.answered_by ) {
						addLocalBadge( msgEl );
					}
					updateAllowance( d );
					history.push( { role: 'user', content: text } );
					history.push( { role: 'assistant', content: d.reply } );
					lastCategory = d.category_guess || 'other';
					showFollowup( !! d.escalation_offered );
				} else {
					addMessage( 'system', ( res && res.data && res.data.message ) || S.error_generic || 'Error.' );
				}
				input.focus();
			} ).catch( function () {
				setPending( false );
				thinking.remove();
				addMessage( 'system', S.error_generic || 'Error.' );
			} );
		}

		function resetChat() {
			history = [];
			lastCategory = 'other';
			clearFollowup();
			statusBar.hidden = true;
			statusBar.textContent = '';
			messages.innerHTML = '';
			addMessage( 'assistant', S.greeting || '' );
		}

		// ------------------------------------------------------------------
		// Wiring
		// ------------------------------------------------------------------

		launcher.addEventListener( 'click', function () {
			panel.hidden = ! panel.hidden;
			if ( ! panel.hidden && cfg.consented ) {
				input.focus();
			}
		} );

		root.querySelector( '.bwdsc-close' ).addEventListener( 'click', function () {
			panel.hidden = true;
		} );

		root.querySelector( '.bwdsc-newchat' ).addEventListener( 'click', resetChat );

		var acceptBtn = root.querySelector( '.bwdsc-consent__accept' );
		if ( acceptBtn ) {
			acceptBtn.addEventListener( 'click', function () {
				acceptBtn.disabled = true;
				post( cfg.actionConsent, {} ).then( function ( res ) {
					if ( res && res.success ) {
						cfg.consented = true;
						consentBox.hidden = true;
						chatBox.hidden = false;
						input.focus();
					} else {
						acceptBtn.disabled = false;
						showConsentError( ( res && res.data && res.data.message ) || S.error_generic || 'Error.' );
					}
				} ).catch( function () {
					acceptBtn.disabled = false;
					showConsentError( S.error_generic || 'Error.' );
				} );
			} );
		}

		sendBtn.addEventListener( 'click', sendMessage );
		input.addEventListener( 'keydown', function ( e ) {
			if ( 'Enter' === e.key && ! e.shiftKey ) {
				e.preventDefault();
				sendMessage();
			}
		} );
	}

	function boot() {
		document.querySelectorAll( '.bwdsc-root[data-bwdsc-config]' ).forEach( initInstance );
	}

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