/**
 * Contentosapp Studio — Agent Adjustments editor (Phase 2)
 *
 * The raw agent prompts are no longer displayed or edited in the plugin — they
 * are canonical IP served by contentosapp-api. This editor exposes only the
 * additive, safe Adjustments (niche override, extra instructions, temperature)
 * plus their History.
 *
 * Two-panel layout: sidebar navigation + per-agent tabs (Adjustments | History).
 *
 * Depends on: costudio-admin (base enqueue — provides ajax_url + nonce).
 */
( function () {
	'use strict';

	/* ── State ───────────────────────────────────────────────────────────── */
	const dirty   = {};   // { agentNum: boolean }
	const history = {};   // { agentNum: 'loaded' | null }

	let activeAgent = 1;

	/* ── Helpers ─────────────────────────────────────────────────────────── */
	function t( key, fallback ) {
		const fos = window.CostudioData || {};
		return ( fos.i18n && fos.i18n[ key ] ) ? fos.i18n[ key ] : fallback;
	}

	function format( template, values ) {
		return String( template || '' ).replace( /\{([a-z0-9_]+)\}/gi, function ( match, key ) {
			return Object.prototype.hasOwnProperty.call( values || {}, key ) ? values[ key ] : match;
		} );
	}

	function updateTempSlider( slider ) {
		const min = parseFloat( slider.min ) || 0;
		const max = parseFloat( slider.max ) || 2;
		const val = parseFloat( slider.value ) || 0.7;
		const pct = Math.round( ( val - min ) / ( max - min ) * 100 );
		slider.style.background =
			'linear-gradient(90deg, #d8ccff 0%, var(--fos-primary, #6C47FF) ' + pct + '%, #e5e7eb ' + pct + '%, #e5e7eb 100%)';
	}

	function ajax( action, data, onSuccess, onError ) {
		const fos     = window.CostudioData || {};
		const payload = Object.assign(
			{ action, nonce: fos.nonce || '' },
			data
		);
		const form = new URLSearchParams( payload );
		const ajaxUrl = fos.ajax_url || window.ajaxurl;
		if ( ! ajaxUrl ) {
			if ( onError ) onError( 'Missing AJAX URL.' );
			return;
		}

		fetch( ajaxUrl, {
			method:  'POST',
			headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
			body:    form.toString(),
		} )
			.then( r => r.json() )
			.then( res => {
				if ( res.success ) {
					if ( onSuccess ) onSuccess( res.data );
				} else {
					if ( onError ) onError( res.data );
				}
			} )
			.catch( err => {
				if ( onError ) onError( err );
			} );
	}

	function agentEl( n ) {
		return document.getElementById( 'fos-agent-detail-' + n );
	}

	function nicheInput( n ) {
		return document.getElementById( 'fos-agent-niche-' + n );
	}

	function extraTextarea( n ) {
		return document.getElementById( 'fos-agent-extra-' + n );
	}

	function tempSlider( n ) {
		return document.getElementById( 'fos-agent-temp-' + n );
	}

	function statusEl( n ) {
		return document.getElementById( 'fos-agent-status-' + n );
	}

	function setStatus( n, msg, type ) {
		const el = statusEl( n );
		if ( ! el ) return;
		el.textContent = msg;
		el.className   = 'fos-agents-detail__status fos-agents-detail__status--' + ( type || 'info' );
		if ( msg ) {
			clearTimeout( el._timer );
			el._timer = setTimeout( () => { el.textContent = ''; el.className = 'fos-agents-detail__status'; }, 3500 );
		}
	}

	function setSidebarBadge( n, isAdjusted ) {
		const item  = document.querySelector( '.fos-agents-sidebar__item[data-agent="' + n + '"]' );
		if ( ! item ) return;
		const badge = item.querySelector( '.fos-agents-sidebar__badge' );
		if ( ! badge ) return;
		badge.textContent = isAdjusted
			? t( 'agent_badge_adjusted', 'Adjusted' )
			: t( 'agent_badge_default', 'Default' );
		badge.className = 'fos-agents-sidebar__badge ' + ( isAdjusted
			? 'fos-agents-sidebar__badge--custom'
			: 'fos-agents-sidebar__badge--default' );
	}

	function setDirty( n, isDirty ) {
		dirty[ n ] = isDirty;
		const item = document.querySelector( '.fos-agents-sidebar__item[data-agent="' + n + '"]' );
		if ( ! item ) return;
		const dot = item.querySelector( '.fos-agents-sidebar__dirty' );
		if ( dot ) dot.style.display = isDirty ? '' : 'none';
	}

	/* ── Does this agent currently carry any adjustment? ─────────────────── */
	function hasAdjustments( n ) {
		const niche = nicheInput( n );
		const extra = extraTextarea( n );
		const temp  = tempSlider( n );
		const hasNiche = !! ( niche && niche.value.trim() !== '' );
		const hasExtra = !! ( extra && extra.value.trim() !== '' );
		const hasTemp  = !! ( temp && parseFloat( temp.value ) !== 0.7 );
		return hasNiche || hasExtra || hasTemp;
	}

	/* ── Sidebar navigation ──────────────────────────────────────────────── */
	function switchAgent( n ) {
		if ( n === activeAgent ) return;

		document.querySelectorAll( '.fos-agents-sidebar__item' ).forEach( el => {
			el.classList.toggle( 'is-active', parseInt( el.dataset.agent, 10 ) === n );
		} );
		document.querySelectorAll( '.fos-agents-detail__agent' ).forEach( el => {
			el.classList.toggle( 'is-active', parseInt( el.dataset.agent, 10 ) === n );
		} );

		activeAgent = n;
	}

	/* ── Tab navigation (within a detail panel) ──────────────────────────── */
	function switchTab( agentEl, tabName ) {
		agentEl.querySelectorAll( '.fos-agents-tab-btn' ).forEach( btn => {
			const isThis = btn.dataset.agentTab === tabName;
			btn.classList.toggle( 'is-active', isThis );
			btn.setAttribute( 'aria-selected', isThis ? 'true' : 'false' );
		} );
		agentEl.querySelectorAll( '.fos-agents-tab-panel' ).forEach( panel => {
			panel.classList.toggle( 'is-active', panel.dataset.agentPanel === tabName );
		} );

		if ( tabName === 'history' ) loadHistory( parseInt( agentEl.dataset.agent, 10 ) );
	}

	/* ── Per-agent save (Adjustments only) ───────────────────────────────── */
	function saveAgent( n, btn ) {
		const niche = nicheInput( n );
		const extra = extraTextarea( n );
		const temp  = tempSlider( n );

		if ( btn ) { btn.disabled = true; btn.textContent = '…'; }

		ajax(
			'costudio_save_agent_single',
			{
				agent:       n,
				niche:       niche ? niche.value : '',
				extra:       extra ? extra.value : '',
				temperature: temp ? temp.value : '',
			},
			function ( data ) {
				if ( btn ) { btn.disabled = false; btn.textContent = btn._label; }
				setStatus( n, data.message || t( 'agent_saved', 'Agent saved.' ), 'ok' );
				setDirty( n, false );
				setSidebarBadge( n, hasAdjustments( n ) );
				history[ n ] = null; // adjustments changed — force history reload
			},
			function ( err ) {
				if ( btn ) { btn.disabled = false; btn.textContent = btn._label; }
				setStatus( n, ( typeof err === 'string' ? err : t( 'agent_save_error', 'Error saving agent.' ) ), 'error' );
			}
		);
	}

	/* ── History (of adjustments) ────────────────────────────────────────── */
	function loadHistory( n ) {
		const container = document.getElementById( 'fos-agent-history-' + n );
		if ( ! container ) return;
		if ( history[ n ] === 'loaded' ) return;

		container.innerHTML = '<p class="fos-agent-history__loading">' + esc( t( 'loading', 'Loading…' ) ) + '</p>';

		ajax(
			'costudio_get_prompt_history',
			{ agent: n },
			function ( data ) {
				history[ n ] = 'loaded';
				renderHistory( n, data.history || [] );
			},
			function () {
				if ( container ) container.innerHTML = '<p class="fos-agent-history__empty">' + esc( t( 'agent_history_load_error', 'Could not load history.' ) ) + '</p>';
			}
		);
	}

	function adjustmentsSummary( entry ) {
		const parts = [];
		if ( entry.temperature !== null && entry.temperature !== undefined && entry.temperature !== '' ) {
			parts.push( format( t( 'agent_history_temp', 'Temp: {value}' ), { value: parseFloat( entry.temperature ).toFixed( 1 ) } ) );
		}
		if ( entry.niche ) {
			parts.push( format( t( 'agent_history_niche', 'Niche: {value}' ), { value: String( entry.niche ).slice( 0, 40 ) } ) );
		}
		if ( entry.extra ) {
			parts.push( format( t( 'agent_history_extra_chars', 'Extra: {count} chars' ), { count: String( entry.extra ).length } ) );
		}
		return parts.length ? parts.join( ' · ' ) : t( 'agent_history_no_adjustments', 'No adjustments' );
	}

	function renderHistory( n, entries ) {
		const container = document.getElementById( 'fos-agent-history-' + n );
		if ( ! container ) return;

		if ( ! entries.length ) {
			container.innerHTML = '<p class="fos-agent-history__empty">' + esc( t( 'agent_history_empty', 'No history yet. A snapshot is saved each time you save this agent.' ) ) + '</p>';
			return;
		}

		const ul = document.createElement( 'ul' );
		ul.className = 'fos-agent-history__list';

		entries.forEach( function ( entry, idx ) {
			const date  = new Date( entry.timestamp * 1000 );
			const label = date.toLocaleString();
			const li    = document.createElement( 'li' );
			li.className = 'fos-agent-history__item';
			li.innerHTML =
				'<div class="fos-agent-history__item-meta">' +
					'<span class="fos-agent-history__item-date">' + esc( label ) + '</span>' +
				'</div>' +
				'<div class="fos-agent-history__item-excerpt">' + esc( adjustmentsSummary( entry ) ) + '</div>' +
				'<button type="button" class="cts-btn cts-btn--ghost cts-btn--sm fos-agent-restore-btn" ' +
					'data-agent="' + n + '" data-version="' + idx + '">↩ ' + esc( t( 'restore', 'Restore' ) ) + '</button>';
			ul.appendChild( li );
		} );

		container.innerHTML = '';
		container.appendChild( ul );
	}

	function restoreVersion( n, versionIdx, btn ) {
		if ( btn ) { btn.disabled = true; }

		ajax(
			'costudio_restore_agent_version',
			{ agent: n, version: versionIdx },
			function ( data ) {
				if ( btn ) btn.disabled = false;
				const niche = nicheInput( n );
				if ( niche && data.niche !== undefined ) niche.value = data.niche;
				const extra = extraTextarea( n );
				if ( extra && data.extra !== undefined ) extra.value = data.extra;
				const temp    = tempSlider( n );
				const tempVal = document.getElementById( 'fos-agent-temp-val-' + n );
				if ( temp && data.temperature !== null && data.temperature !== undefined ) {
					temp.value = data.temperature;
					if ( tempVal ) tempVal.textContent = parseFloat( data.temperature ).toFixed( 1 );
					updateTempSlider( temp );
				}
				history[ n ] = null; // force reload
				setStatus( n, data.message || t( 'version_restored', 'Version restored.' ), 'ok' );
				setDirty( n, false );
				setSidebarBadge( n, hasAdjustments( n ) );
				// Switch back to the Adjustments tab to show the restored values.
				const det = agentEl( n );
				if ( det ) switchTab( det, 'studio' );
			},
			function () {
				if ( btn ) btn.disabled = false;
				setStatus( n, t( 'version_restore_error', 'Error restoring version.' ), 'error' );
			}
		);
	}

	/* ── Reset all adjustments ───────────────────────────────────────────── */
	function resetAllAdjustments( btn ) {
		const msg = t( 'reset_all_confirm', 'Reset all adjustments (niche, extra instructions, temperature) for all 7 agents? This cannot be undone.' );
		if ( ! window.confirm( msg ) ) return;

		if ( btn ) { btn.disabled = true; btn.textContent = '…'; }

		const fos  = window.CostudioData || {};
		const lang = fos.lang || document.documentElement.lang || 'en_US';

		ajax(
			'costudio_restore_all_defaults',
			{ lang },
			function ( data ) {
				if ( btn ) { btn.disabled = false; btn.textContent = btn._label; }

				const defaultTemp = '0.7';
				for ( let n = 1; n <= 7; n++ ) {
					const niche = nicheInput( n );
					if ( niche ) niche.value = '';
					const extra = extraTextarea( n );
					if ( extra ) extra.value = '';
					const temp    = tempSlider( n );
					const tempVal = document.getElementById( 'fos-agent-temp-val-' + n );
					if ( temp ) {
						temp.value = defaultTemp;
						if ( tempVal ) tempVal.textContent = defaultTemp;
						updateTempSlider( temp );
					}
					setSidebarBadge( n, false );
					setDirty( n, false );
					history[ n ] = null;
				}

				setStatus( activeAgent, data.message || t( 'all_adjustments_reset', 'All adjustments reset.' ), 'ok' );
			},
			function ( err ) {
				if ( btn ) { btn.disabled = false; btn.textContent = btn._label; }
				setStatus( activeAgent, ( typeof err === 'string' ? err : t( 'reset_all_error', 'Error resetting adjustments.' ) ), 'error' );
			}
		);
	}

	/* ── Variable chip insertion (into the Extra Instructions field) ─────── */
	function insertVar( textarea, varText ) {
		if ( ! textarea || textarea.readOnly ) return;
		const start = textarea.selectionStart;
		const end   = textarea.selectionEnd;
		const val   = textarea.value;
		textarea.value = val.slice( 0, start ) + varText + val.slice( end );
		textarea.selectionStart = textarea.selectionEnd = start + varText.length;
		textarea.focus();
		textarea.dispatchEvent( new Event( 'input' ) );
	}

	/* ── Escape HTML ─────────────────────────────────────────────────────── */
	function esc( str ) {
		return String( str )
			.replace( /&/g, '&amp;' )
			.replace( /</g, '&lt;' )
			.replace( />/g, '&gt;' )
			.replace( /"/g, '&quot;' );
	}

	/* ── Boot ────────────────────────────────────────────────────────────── */
	function init() {
		const editor = document.getElementById( 'fos-agents-editor' );
		if ( ! editor ) return;

		// Cache original button labels.
		editor.querySelectorAll( '.fos-agent-save-btn' ).forEach( function ( btn ) {
			btn._label = btn.textContent.trim();
		} );

		// Reset-all button.
		const resetAllBtn = document.getElementById( 'fos-restore-all-btn' );
		if ( resetAllBtn ) {
			resetAllBtn._label = resetAllBtn.textContent.trim();
			resetAllBtn.addEventListener( 'click', function () {
				resetAllAdjustments( resetAllBtn );
			} );
		}

		// Sidebar item click / keyboard.
		editor.querySelectorAll( '.fos-agents-sidebar__item' ).forEach( function ( item ) {
			function activate() {
				switchAgent( parseInt( item.dataset.agent, 10 ) );
			}
			item.addEventListener( 'click', activate );
			item.addEventListener( 'keydown', function ( e ) {
				if ( e.key === 'Enter' || e.key === ' ' ) { e.preventDefault(); activate(); }
			} );
		} );

		// Delegated clicks.
		editor.addEventListener( 'click', function ( e ) {
			// Agent tab buttons.
			const tabBtn = e.target.closest( '.fos-agents-tab-btn' );
			if ( tabBtn ) {
				const det = tabBtn.closest( '.fos-agents-detail__agent' );
				if ( det ) switchTab( det, tabBtn.dataset.agentTab );
				return;
			}

			// Save button.
			const saveBtn = e.target.closest( '.fos-agent-save-btn' );
			if ( saveBtn ) {
				saveAgent( parseInt( saveBtn.dataset.agent, 10 ), saveBtn );
				return;
			}

			// Restore history version.
			const restoreBtn = e.target.closest( '.fos-agent-restore-btn' );
			if ( restoreBtn ) {
				restoreVersion(
					parseInt( restoreBtn.dataset.agent, 10 ),
					parseInt( restoreBtn.dataset.version, 10 ),
					restoreBtn
				);
				return;
			}

			// Variable chips → insert into the Extra Instructions field.
			const chip = e.target.closest( '.fos-agent-var' );
			if ( chip ) {
				const det = chip.closest( '.fos-agents-detail__agent' );
				if ( det ) {
					const n = parseInt( det.dataset.agent, 10 );
					insertVar( extraTextarea( n ), chip.dataset.var );
				}
				return;
			}
		} );

		// Dirty tracking — niche + extra inputs.
		editor.querySelectorAll( '.fos-agent-niche-input, .fos-agent-extra-input' ).forEach( function ( el ) {
			el.addEventListener( 'input', function () {
				setDirty( parseInt( el.dataset.agent, 10 ), true );
			} );
		} );

		// Temperature slider live value + gradient.
		editor.querySelectorAll( '.fos-agent-temp-slider' ).forEach( function ( slider ) {
			updateTempSlider( slider );   // set gradient for initial value
			slider.addEventListener( 'input', function () {
				const n      = parseInt( slider.dataset.agent, 10 );
				const valEl  = document.getElementById( 'fos-agent-temp-val-' + n );
				if ( valEl ) valEl.textContent = parseFloat( slider.value ).toFixed( 1 );
				updateTempSlider( slider );
				setDirty( n, true );
			} );
		} );

		// Initialize dirty dots as hidden.
		editor.querySelectorAll( '.fos-agents-sidebar__dirty' ).forEach( function ( dot ) {
			dot.style.display = 'none';
		} );
	}

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