/**
 * Easy Chat Support - Capripio — admin dashboard.
 * Apple-style liquid glass: floating frosted panels, segmented
 * controls, iMessage-style bubbles. Vanilla JS.
 */
( function () {
	'use strict';

	if ( typeof CPECS_ADMIN === 'undefined' ) {
		return;
	}

	var root = document.getElementById( 'cpecs-app' );
	if ( ! root ) {
		return;
	}

	var view = root.getAttribute( 'data-view' );

	var SETTINGS_TABS = [
		{ key: 'widget', label: 'Widget' },
		{ key: 'notifications', label: 'Notifications' },
		{ key: 'retention', label: 'Retention' },
		{ key: 'branding', label: 'Branding' },
		{ key: 'advanced', label: 'Advanced' },
	];

	var state = {
		conversations: [],
		activeId: null,
		lastMessageId: 0,
		pollTimer: null,
		sending: false,
		settings: Object.assign( {}, CPECS_ADMIN.settings ),
		settingsTab: 'widget',
	};

	// -----------------------------------------------------------------
	// DOM + fetch helpers
	// -----------------------------------------------------------------

	function el( tag, attrs, children ) {
		var node = document.createElement( tag );
		attrs = attrs || {};
		Object.keys( attrs ).forEach( function ( k ) {
			if ( k === 'class' ) node.className = attrs[ k ];
			else if ( k === 'html' ) node.innerHTML = attrs[ k ];
			else node.setAttribute( k, attrs[ k ] );
		} );
		( children || [] ).forEach( function ( c ) {
			if ( c ) node.appendChild( c );
		} );
		return node;
	}

	function escapeHtml( str ) {
		var div = document.createElement( 'div' );
		div.appendChild( document.createTextNode( str || '' ) );
		return div.innerHTML;
	}

	function restFetch( path, options ) {
		options = options || {};
		var headers = options.headers || {};
		headers['Content-Type'] = 'application/json';
		headers['X-WP-Nonce'] = CPECS_ADMIN.restNonce;

		return fetch( CPECS_ADMIN.restUrl + path, {
			method: options.method || 'GET',
			headers: headers,
			credentials: 'same-origin',
			body: options.body ? JSON.stringify( options.body ) : undefined,
		} ).then( function ( res ) {
			return res.json().then( function ( data ) {
				if ( ! res.ok ) throw data;
				return data;
			} );
		} );
	}

	function ajaxPost( action, body ) {
		var form = new URLSearchParams();
		form.set( 'action', action );
		form.set( 'nonce', CPECS_ADMIN.ajaxNonce );
		Object.keys( body || {} ).forEach( function ( k ) {
			form.set( k, typeof body[ k ] === 'object' ? JSON.stringify( body[ k ] ) : body[ k ] );
		} );

		return fetch( CPECS_ADMIN.ajaxUrl, {
			method: 'POST',
			credentials: 'same-origin',
			headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
			body: form.toString(),
		} ).then( function ( res ) {
			return res.json();
		} );
	}

	function relativeTime( isoLike ) {
		if ( ! isoLike ) return '';
		var d = new Date( isoLike.replace( ' ', 'T' ) );
		if ( isNaN( d.getTime() ) ) return '';
		var diff = Math.round( ( Date.now() - d.getTime() ) / 1000 );
		if ( diff < 45 ) return 'now';
		if ( diff < 3600 ) return Math.round( diff / 60 ) + 'm';
		if ( diff < 86400 ) return Math.round( diff / 3600 ) + 'h';
		return Math.round( diff / 86400 ) + 'd';
	}

	function formatClock( isoLike ) {
		var d = isoLike ? new Date( isoLike.replace( ' ', 'T' ) ) : new Date();
		if ( isNaN( d.getTime() ) ) d = new Date();
		var h = d.getHours();
		var m = d.getMinutes();
		var ampm = h >= 12 ? 'PM' : 'AM';
		h = h % 12;
		if ( h === 0 ) h = 12;
		return h + ':' + ( m < 10 ? '0' : '' ) + m + ' ' + ampm;
	}

	function initials( name ) {
		if ( ! name ) return 'V';
		var parts = name.trim().split( /\s+/ );
		var out = parts[0].charAt( 0 );
		if ( parts.length > 1 ) out += parts[ parts.length - 1 ].charAt( 0 );
		return escapeHtml( out.toUpperCase() );
	}

	function icon( paths ) {
		return '<svg viewBox="0 0 24 24" width="15" height="15" fill="none" xmlns="http://www.w3.org/2000/svg" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">' + paths + '</svg>';
	}
	function iconChat() { return icon( '<path d="M4 12C4 7.58 7.58 4 12 4C16.42 4 20 7.58 20 12C20 16.42 16.42 20 12 20C10.45 20 9.01 19.56 7.78 18.8L4 20L5.2 16.22C4.44 14.99 4 13.55 4 12Z"/>' ); }
	function iconInboxEmpty() { return icon( '<path d="M4 4h16v11l-3 5H7l-3-5z"/><path d="M4 12h4l1.5 3h5L16 12h4"/>' ); }
	function iconSend() { return icon( '<path d="M4 12L20 4L14 20L11 13L4 12Z"/>' ); }

	// -----------------------------------------------------------------
	// Frame: aurora background + floating glass topbar
	// -----------------------------------------------------------------

	function buildFrame( activeView, pageNode ) {
		var navItems = ( CPECS_ADMIN.navItems && CPECS_ADMIN.navItems.length ) ? CPECS_ADMIN.navItems : [
			{ key: 'inbox', label: 'Inbox', url: 'admin.php?page=cpecs-inbox' },
			{ key: 'settings', label: 'Settings', url: 'admin.php?page=cpecs-settings' },
		];

		var topbar = el( 'div', { class: 'cpecs-topbar cpecs-glass' }, [
			el( 'div', { class: 'cpecs-brand' }, [
				el( 'span', { class: 'cpecs-brand-mark', html: iconChat() } ),
				el( 'span', { class: 'cpecs-brand-name', html: "Capripio's Easy Chat Support" } ),
			] ),
			el( 'nav', { class: 'cpecs-segmented' }, navItems.map( function ( item ) {
				return el( 'a', {
					href: item.url,
					class: 'cpecs-seg-item' + ( activeView === item.key ? ' cpecs-seg-active' : '' ),
					html: item.label,
				} );
			} ) ),
			el( 'div', { class: 'cpecs-topbar-right' }, [
				el( 'span', { class: 'cpecs-live-pill' }, [ el( 'span', { class: 'cpecs-live-dot' } ), document.createTextNode( 'Live' ) ] ),
			] ),
		] );

		root.innerHTML = '';
		root.appendChild( el( 'div', { class: 'cpecs-aurora' }, [
			el( 'span', { class: 'cpecs-blob cpecs-blob-1' } ),
			el( 'span', { class: 'cpecs-blob cpecs-blob-2' } ),
			el( 'span', { class: 'cpecs-blob cpecs-blob-3' } ),
			el( 'span', { class: 'cpecs-blob cpecs-blob-4' } ),
		] ) );

		var frame = el( 'div', { class: 'cpecs-frame' }, [ topbar, pageNode ] );
		root.appendChild( frame );
	}

	// -----------------------------------------------------------------
	// Inbox
	// -----------------------------------------------------------------

	function buildProPromoSidebar() {
		var promo = CPECS_ADMIN.proPromo;
		if ( ! promo ) {
			return null; // Pro is already active.
		}

		return el( 'aside', { class: 'cpecs-promo-side' }, [
			el( 'div', { class: 'cpecs-promo-badge', html: '&#10024;' } ),
			el( 'h2', { class: 'cpecs-promo-title', html: escapeHtml( promo.title ) } ),
			el( 'p', { class: 'cpecs-promo-tagline', html: escapeHtml( promo.tagline ) } ),
			el( 'ul', { class: 'cpecs-promo-features' }, promo.features.map( function ( f ) {
				return el( 'li', { html: escapeHtml( f ) } );
			} ) ),
			el( 'div', { class: 'cpecs-promo-price', html: escapeHtml( promo.pricing ) } ),
			el( 'a', { href: promo.url, target: '_blank', rel: 'noopener', class: 'cpecs-promo-cta', html: escapeHtml( promo.cta ) } ),
		] );
	}

	function renderInbox() {
		var stats = el( 'div', { class: 'cpecs-stats', id: 'cpecs-stats' } );
		var listPane = el( 'div', { class: 'cpecs-list-pane cpecs-glass', id: 'cpecs-list-pane' } );
		var threadPane = el( 'div', { class: 'cpecs-thread-pane cpecs-glass', id: 'cpecs-thread-pane' }, [ emptyThread() ] );

		var grid = el( 'div', { class: 'cpecs-inbox-grid' }, [ listPane, threadPane ] );
		var main = el( 'div', { class: 'cpecs-page-main' }, [
			el( 'h1', { class: 'cpecs-page-title', html: 'Inbox' } ),
			el( 'p', { class: 'cpecs-page-sub', html: 'Conversations from your site visitors, in real time.' } ),
			stats,
			grid,
		] );

		var sidebar = buildProPromoSidebar();
		var page = sidebar
			? el( 'div', { class: 'cpecs-page' }, [ el( 'div', { class: 'cpecs-page-body' }, [ main, sidebar ] ) ] )
			: el( 'div', { class: 'cpecs-page' }, [ main ] );

		buildFrame( 'inbox', page );
		loadConversations();

		clearInterval( state.pollTimer );
		state.pollTimer = setInterval( function () {
			loadConversations();
			if ( state.activeId ) pollThread();
		}, 5000 );
	}

	function emptyThread() {
		return el( 'div', { class: 'cpecs-empty' }, [
			el( 'span', { class: 'cpecs-empty-icon', html: iconChat() } ),
			el( 'p', { html: 'Select a conversation' } ),
			el( 'span', { class: 'cpecs-empty-hint', html: 'Replies show up here instantly.' } ),
		] );
	}

	function loadConversations() {
		restFetch( '/admin/conversations' ).then( function ( data ) {
			state.conversations = data.conversations;
			renderStats( data.total_open, data.total_new );
			renderList();
		} ).catch( function () {} );
	}

	function renderStats( open, fresh ) {
		var wrap = document.getElementById( 'cpecs-stats' );
		if ( ! wrap ) return;
		wrap.innerHTML = '';
		wrap.appendChild( tile( open, 'Open', 'open' ) );
		wrap.appendChild( tile( fresh, 'New', 'new' ) );
	}

	function tile( count, label, tone ) {
		return el( 'div', { class: 'cpecs-tile cpecs-glass cpecs-tile-' + tone }, [
			el( 'span', { class: 'cpecs-tile-dot' } ),
			el( 'span', { class: 'cpecs-tile-text' }, [
				el( 'span', { class: 'cpecs-tile-num', html: String( count ) } ),
				el( 'span', { class: 'cpecs-tile-label', html: label } ),
			] ),
		] );
	}

	function renderList() {
		var wrap = document.getElementById( 'cpecs-list-pane' );
		if ( ! wrap ) return;
		wrap.innerHTML = '';

		if ( ! state.conversations.length ) {
			wrap.appendChild( el( 'div', { class: 'cpecs-empty' }, [
				el( 'span', { class: 'cpecs-empty-icon', html: iconInboxEmpty() } ),
				el( 'p', { html: 'No conversations yet' } ),
				el( 'span', { class: 'cpecs-empty-hint', html: 'New visitor messages will show up here.' } ),
			] ) );
			return;
		}

		state.conversations.forEach( function ( c ) {
			var row = el( 'button', {
				type: 'button',
				'data-conversation-id': c.id,
				class: 'cpecs-row cpecs-status-' + c.status + ( c.id === state.activeId ? ' cpecs-row-active' : '' ),
			}, [
				el( 'span', { class: 'cpecs-row-status' } ),
				el( 'span', { class: 'cpecs-avatar', html: initials( c.visitor_name ) } ),
				el( 'span', { class: 'cpecs-row-main' }, [
					el( 'span', { class: 'cpecs-row-top' }, [
						el( 'span', { class: 'cpecs-row-name', html: escapeHtml( c.visitor_name ) } ),
						el( 'span', { class: 'cpecs-row-time', html: relativeTime( c.updated_at ) } ),
					] ),
					el( 'span', { class: 'cpecs-row-preview', html: escapeHtml( c.last_message ) } ),
				] ),
			] );
			row.addEventListener( 'click', function () {
				openThread( c.id );
			} );
			wrap.appendChild( row );
			document.dispatchEvent( new CustomEvent( 'cpecs:row-render', { detail: { conversation: c, rowEl: row } } ) );
		} );
	}

	function openThread( id ) {
		state.activeId = id;
		state.lastMessageId = 0;
		state.sending = false;
		renderList();

		restFetch( '/admin/conversations/' + id ).then( function ( data ) {
			renderThread( data );
		} ).catch( function () {} );
	}

	function renderThread( data ) {
		var pane = document.getElementById( 'cpecs-thread-pane' );
		if ( ! pane ) return;
		pane.innerHTML = '';

		var header = el( 'div', { class: 'cpecs-thread-header' }, [
			el( 'span', { class: 'cpecs-thread-avatar', html: initials( data.visitor_name ) } ),
			el( 'div', { class: 'cpecs-thread-headtext' }, [
				el( 'span', { class: 'cpecs-thread-name', html: escapeHtml( data.visitor_name || 'Visitor' ) } ),
				el( 'span', { class: 'cpecs-thread-meta', html: escapeHtml( data.visitor_email || 'No email provided' ) } ),
			] ),
			el( 'button', { type: 'button', class: 'cpecs-pill-btn', id: 'cpecs-close-conv', html: 'Close' } ),
		] );

		var messages = el( 'div', { class: 'cpecs-thread-messages', id: 'cpecs-thread-messages' } );
		data.messages.forEach( function ( m ) {
			messages.appendChild( bubble( m ) );
			state.lastMessageId = Math.max( state.lastMessageId, m.id );
		} );

		var input = el( 'input', { type: 'text', class: 'cpecs-compose-input', placeholder: 'Type a reply…' } );
		var sendBtn = el( 'button', { type: 'submit', class: 'cpecs-compose-send', 'aria-label': 'Send', html: iconSend() } );
		var compose = el( 'form', { class: 'cpecs-compose' }, [ input, sendBtn ] );

		compose.addEventListener( 'submit', function ( e ) {
			e.preventDefault();
			var val = input.value.trim();
			if ( ! val ) return;

			input.value = '';
			messages.appendChild( bubble( { sender_type: 'agent', message: val, created_at: '' } ) );
			messages.scrollTop = messages.scrollHeight;

			state.sending = true;
			restFetch( '/admin/conversations/' + data.id + '/reply', { method: 'POST', body: { message: val } } ).then( function ( res ) {
				if ( res && res.message_id ) {
					state.lastMessageId = Math.max( state.lastMessageId, res.message_id );
				}
			} ).catch( function () {} ).then( function () {
				state.sending = false;
			} );
		} );

		pane.appendChild( header );
		pane.appendChild( messages );
		pane.appendChild( compose );
		messages.scrollTop = messages.scrollHeight;

		document.getElementById( 'cpecs-close-conv' ).addEventListener( 'click', function () {
			restFetch( '/admin/conversations/' + data.id + '/close', { method: 'POST' } ).then( function () {
				loadConversations();
			} );
		} );

		document.dispatchEvent( new CustomEvent( 'cpecs:thread-render', {
			detail: { id: data.id, data: data, headerEl: header, paneEl: pane, messagesEl: messages },
		} ) );
	}

	function bubble( m ) {
		var out = m.sender_type !== 'visitor';
		return el( 'div', { class: 'cpecs-bubble-row ' + ( out ? 'cpecs-out' : 'cpecs-in' ) }, [
			el( 'div', { class: 'cpecs-bubble' }, [
				el( 'span', { html: escapeHtml( m.message ) } ),
				el( 'span', { class: 'cpecs-bubble-time', html: formatClock( m.created_at ) } ),
			] ),
		] );
	}

	function pollThread() {
		if ( ! state.activeId || state.sending ) return;
		restFetch( '/admin/conversations/' + state.activeId ).then( function ( data ) {
			var messages = document.getElementById( 'cpecs-thread-messages' );
			if ( ! messages ) return;
			data.messages.forEach( function ( m ) {
				if ( m.id > state.lastMessageId ) {
					messages.appendChild( bubble( m ) );
					state.lastMessageId = m.id;
				}
			} );
			messages.scrollTop = messages.scrollHeight;
		} );
	}

	// -----------------------------------------------------------------
	// Settings — segmented control tabs
	// -----------------------------------------------------------------

	function renderSettings() {
		var tabsEl = el( 'nav', { class: 'cpecs-segmented cpecs-subseg', id: 'cpecs-settings-tabs' } );
		var panelEl = el( 'div', { class: 'cpecs-tabpanel-wrap', id: 'cpecs-settings-panel' } );

		var saveRow = el( 'div', { class: 'cpecs-save-row' }, [
			el( 'button', { type: 'button', class: 'cpecs-btn-primary', id: 'cpecs-save-settings', html: 'Save changes' } ),
			el( 'span', { class: 'cpecs-save-status', id: 'cpecs-save-status' } ),
		] );

		var wrap = el( 'div', { class: 'cpecs-settings-wrap' }, [ tabsEl, panelEl, saveRow ] );
		var main = el( 'div', { class: 'cpecs-page-main' }, [
			el( 'h1', { class: 'cpecs-page-title', html: 'Settings' } ),
			el( 'p', { class: 'cpecs-page-sub', html: 'Configure how your chat widget looks and behaves.' } ),
			wrap,
		] );

		var sidebar = buildProPromoSidebar();
		var page = sidebar
			? el( 'div', { class: 'cpecs-page' }, [ el( 'div', { class: 'cpecs-page-body' }, [ main, sidebar ] ) ] )
			: el( 'div', { class: 'cpecs-page' }, [ main ] );

		buildFrame( 'settings', page );
		renderTabs();
		renderPanel();

		document.getElementById( 'cpecs-save-settings' ).addEventListener( 'click', saveSettings );
	}

	function renderTabs() {
		var tabsEl = document.getElementById( 'cpecs-settings-tabs' );
		if ( ! tabsEl ) return;
		tabsEl.innerHTML = '';
		SETTINGS_TABS.forEach( function ( t ) {
			var btn = el( 'button', {
				type: 'button',
				class: 'cpecs-seg-item' + ( state.settingsTab === t.key ? ' cpecs-seg-active' : '' ),
				html: t.label,
			} );
			btn.addEventListener( 'click', function () {
				state.settingsTab = t.key;
				renderTabs();
				renderPanel();
			} );
			tabsEl.appendChild( btn );
		} );
	}

	function renderPanel() {
		var panelEl = document.getElementById( 'cpecs-settings-panel' );
		if ( ! panelEl ) return;
		panelEl.innerHTML = '';

		var s = state.settings;
		var builders = {
			widget: buildWidgetPanel,
			notifications: buildNotificationsPanel,
			retention: buildRetentionPanel,
			branding: buildBrandingPanel,
			advanced: buildAdvancedPanel,
		};
		panelEl.appendChild( builders[ state.settingsTab ]( s ) );
	}

	function buildWidgetPanel( s ) {
		return el( 'div', { class: 'cpecs-tabpanel' }, [
			card( 'Availability', [
				toggleRow( 'enabled', 'Enable chat widget on your site', s.enabled ),
			] ),
			card( 'Greetings', [
				textRow( 'welcome_message', 'Welcome message', s.welcome_message, 'textarea' ),
				textRow( 'offline_message', 'Offline message', s.offline_message, 'textarea' ),
			] ),
			card( 'Appearance', [
				colorRow( 'widget_color', 'Widget color', s.widget_color ),
				selectRow( 'widget_position', 'Widget position', s.widget_position, [
					[ 'bottom-right', 'Bottom right' ],
					[ 'bottom-left', 'Bottom left' ],
				] ),
			] ),
		] );
	}

	function buildNotificationsPanel( s ) {
		return el( 'div', { class: 'cpecs-tabpanel' }, [
			card( 'Email alerts', [
				toggleRow( 'notify_on_message', 'Email me on new visitor messages', s.notify_on_message ),
				textRow( 'notify_email', 'Notification email', s.notify_email, 'text' ),
			] ),
		] );
	}

	function buildRetentionPanel( s ) {
		return el( 'div', { class: 'cpecs-tabpanel' }, [
			card( 'Message retention', [
				toggleRow( 'retention_enabled', 'Automatically delete old conversations', s.retention_enabled ),
				numberRow( 'retention_days', 'Delete conversations older than (days)', s.retention_days ),
				el( 'div', { class: 'cpecs-frow' }, [
					el( 'div', { class: 'cpecs-frow-label', html: 'Run cleanup now using the setting above' } ),
					el( 'button', { type: 'button', class: 'cpecs-btn-secondary', id: 'cpecs-run-cleanup', html: 'Run now' } ),
				] ),
				el( 'div', { class: 'cpecs-hint', id: 'cpecs-cleanup-status', html: cleanupStatusText() } ),
			] ),
		] );
	}

	function buildBrandingPanel( s ) {
		var toggle = toggleRow( 'show_branding', 'Show "Powered by Capripio" in the chat widget', s.show_branding );
		return el( 'div', { class: 'cpecs-tabpanel' }, [
			el( 'div', { class: 'cpecs-callout' }, [
				el( 'span', { class: 'cpecs-callout-badge', html: '&#9733;' } ),
				el( 'div', { class: 'cpecs-callout-body' }, [
					el( 'h2', { class: 'cpecs-callout-title', html: 'Support Capripio' } ),
					el( 'p', { class: 'cpecs-callout-text', html: 'This plugin is free because a small link back to capripio.com helps us keep building it. Turning this on adds a subtle "Powered by Capripio" credit to the bottom of your chat widget — off by default, entirely your call.' } ),
					toggle,
				] ),
			] ),
		] );
	}

	function buildAdvancedPanel( s ) {
		return el( 'div', { class: 'cpecs-tabpanel' }, [
			card( 'Danger zone', [
				toggleRow( 'delete_data_on_uninstall', 'Delete all chat data when this plugin is uninstalled', s.delete_data_on_uninstall ),
			] ),
		] );
	}

	function cleanupStatusText() {
		var lc = CPECS_ADMIN.lastCleanup;
		if ( ! lc.ran_at ) return 'Cleanup has not run yet.';
		return 'Last run ' + lc.ran_at + ' — ' + lc.count + ' conversation(s) deleted.';
	}

	function card( title, rows ) {
		return el( 'section', { class: 'cpecs-card cpecs-glass' }, [ el( 'h2', { class: 'cpecs-card-title', html: title } ) ].concat( rows ) );
	}

	function toggleRow( key, label, value ) {
		var input = el( 'input', { type: 'checkbox', class: 'cpecs-switch-input', id: 'cpecs-f-' + key } );
		input.checked = !! value;
		input.addEventListener( 'change', function () {
			state.settings[ key ] = input.checked;
		} );
		return el( 'label', { class: 'cpecs-frow', for: 'cpecs-f-' + key }, [
			el( 'span', { class: 'cpecs-frow-label', html: label } ),
			el( 'span', { class: 'cpecs-switch' }, [ input, el( 'span', { class: 'cpecs-switch-track' } ) ] ),
		] );
	}

	function textRow( key, label, value, type ) {
		var input = 'textarea' === type
			? el( 'textarea', { class: 'cpecs-field', rows: '3', id: 'cpecs-f-' + key } )
			: el( 'input', { type: 'text', class: 'cpecs-field', id: 'cpecs-f-' + key } );
		input.value = value || '';
		input.addEventListener( 'input', function () {
			state.settings[ key ] = input.value;
		} );
		return el( 'div', { class: 'cpecs-frow cpecs-frow-stack' }, [
			el( 'label', { class: 'cpecs-frow-label', for: 'cpecs-f-' + key, html: label } ),
			input,
		] );
	}

	function numberRow( key, label, value ) {
		var input = el( 'input', { type: 'number', min: '1', class: 'cpecs-field cpecs-field-number', id: 'cpecs-f-' + key } );
		input.value = value;
		input.addEventListener( 'input', function () {
			state.settings[ key ] = parseInt( input.value, 10 ) || 1;
		} );
		return el( 'div', { class: 'cpecs-frow' }, [
			el( 'label', { class: 'cpecs-frow-label', for: 'cpecs-f-' + key, html: label } ),
			input,
		] );
	}

	function colorRow( key, label, value ) {
		var input = el( 'input', { type: 'color', class: 'cpecs-field-color', id: 'cpecs-f-' + key } );
		input.value = value || '#5b3df5';
		var valueTag = el( 'span', { class: 'cpecs-color-value', html: value } );
		input.addEventListener( 'input', function () {
			state.settings[ key ] = input.value;
			valueTag.textContent = input.value;
		} );
		return el( 'div', { class: 'cpecs-frow' }, [
			el( 'label', { class: 'cpecs-frow-label', for: 'cpecs-f-' + key, html: label } ),
			el( 'div', { class: 'cpecs-color-wrap' }, [ input, valueTag ] ),
		] );
	}

	function selectRow( key, label, value, options ) {
		var select = el( 'select', { class: 'cpecs-field cpecs-select-field', id: 'cpecs-f-' + key } );
		options.forEach( function ( opt ) {
			var o = el( 'option', { value: opt[0], html: opt[1] } );
			if ( opt[0] === value ) o.setAttribute( 'selected', 'selected' );
			select.appendChild( o );
		} );
		select.addEventListener( 'change', function () {
			state.settings[ key ] = select.value;
		} );
		return el( 'div', { class: 'cpecs-frow' }, [
			el( 'label', { class: 'cpecs-frow-label', for: 'cpecs-f-' + key, html: label } ),
			select,
		] );
	}

	function saveSettings() {
		var status = document.getElementById( 'cpecs-save-status' );
		status.textContent = 'Saving…';
		ajaxPost( 'cpecs_save_settings', { settings: state.settings } ).then( function ( res ) {
			if ( res.success ) {
				state.settings = res.data.settings;
				status.textContent = 'Saved';
			} else {
				status.textContent = 'Could not save';
			}
			setTimeout( function () { status.textContent = ''; }, 2500 );
		} );
	}

	function runCleanupNow() {
		var statusEl = document.getElementById( 'cpecs-cleanup-status' );
		if ( ! statusEl ) return;
		statusEl.textContent = 'Running…';
		ajaxPost( 'cpecs_run_cleanup_now', {} ).then( function ( res ) {
			if ( res.success ) {
				CPECS_ADMIN.lastCleanup = { ran_at: res.data.ran_at, count: res.data.deleted };
				statusEl.textContent = cleanupStatusText();
			} else {
				statusEl.textContent = 'Cleanup failed.';
			}
		} );
	}

	// Delegated: the cleanup button lives inside a panel rebuilt on
	// every tab switch, so bind once on the root instead.
	root.addEventListener( 'click', function ( e ) {
		if ( e.target && e.target.id === 'cpecs-run-cleanup' ) {
			runCleanupNow();
		}
	} );

	// -----------------------------------------------------------------

	// -----------------------------------------------------------------
	// Extension surface for the Pro plugin (optional; safe if unused).
	// Pro listens for 'cpecs:row-render' / 'cpecs:thread-render' events
	// on document and can reuse these authenticated fetch helpers.
	// -----------------------------------------------------------------
	window.CPECSAdminAPI = {
		restFetch: restFetch,
		ajaxPost: ajaxPost,
		escapeHtml: escapeHtml,
		el: el,
		buildFrame: buildFrame,
	};

	if ( view === 'settings' ) {
		renderSettings();
	} else if ( view === 'inbox' ) {
		renderInbox();
	}
} )();
