/**
 * Odysseo SEO — meta box admin script.
 * Char counters + "Generate with AI" (AJAX). No jQuery dependency.
 */
( function () {
	'use strict';

	var cfg = window.OdysseoSeo || {};

	// Map AI JSON keys -> meta-box field keys (data-field).
	var MAP = {
		seo_title: 'title',
		meta_description: 'desc',
		focus_keywords: 'keywords',
		og_title: 'og_title',
		og_description: 'og_desc'
	};

	function field( key ) {
		return document.querySelector( '.odysseo-seo-input[data-field="' + key + '"]' );
	}

	function updateCounter( key, recommended ) {
		var input = field( key );
		var hint = document.querySelector( '.odysseo-seo-hint[data-counter="' + key + '"]' );
		if ( ! input || ! hint ) {
			return;
		}
		var len = ( input.value || '' ).length;
		hint.textContent = len + ' / ~' + recommended + ' characters';
		hint.style.color = len > recommended + 10 ? '#b32d2e' : '';
	}

	function wireCounters() {
		[ [ 'title', 60 ], [ 'desc', 155 ] ].forEach( function ( pair ) {
			var input = field( pair[ 0 ] );
			if ( ! input ) {
				return;
			}
			updateCounter( pair[ 0 ], pair[ 1 ] );
			input.addEventListener( 'input', function () {
				updateCounter( pair[ 0 ], pair[ 1 ] );
			} );
		} );
	}

	function setStatus( msg, isError ) {
		var el = document.querySelector( '.odysseo-seo-status' );
		if ( ! el ) {
			return;
		}
		el.textContent = msg || '';
		el.style.color = isError ? '#b32d2e' : '#1a7a3c';
	}

	function setBusy( busy ) {
		var btn = document.getElementById( 'odysseo-seo-generate' );
		var sp = document.querySelector( '.odysseo-seo-spinner' );
		if ( btn ) {
			btn.disabled = busy;
		}
		if ( sp ) {
			sp.classList.toggle( 'is-active', busy );
		}
	}

	function generate( postId ) {
		setBusy( true );
		setStatus( ( cfg.i18n && cfg.i18n.generating ) || 'Generating…', false );

		var body = new FormData();
		body.append( 'action', 'odysseo_seo_generate' );
		body.append( 'nonce', cfg.nonce || '' );
		body.append( 'post_id', postId );

		fetch( cfg.ajaxurl, { method: 'POST', credentials: 'same-origin', body: body } )
			.then( function ( r ) {
				return r.json().catch( function () {
					throw new Error( 'bad-json' );
				} );
			} )
			.then( function ( res ) {
				if ( ! res || ! res.success || ! res.data ) {
					var m = res && res.data && res.data.message ? res.data.message : ( cfg.i18n && cfg.i18n.error );
					throw new Error( m || 'error' );
				}
				Object.keys( MAP ).forEach( function ( aiKey ) {
					var input = field( MAP[ aiKey ] );
					if ( input && typeof res.data[ aiKey ] === 'string' && res.data[ aiKey ] !== '' ) {
						input.value = res.data[ aiKey ];
					}
				} );
				updateCounter( 'title', 60 );
				updateCounter( 'desc', 155 );
				setStatus( ( cfg.i18n && cfg.i18n.done ) || 'Done.', false );
			} )
			.catch( function ( err ) {
				setStatus( ( err && err.message ) || ( cfg.i18n && cfg.i18n.error ) || 'Error', true );
			} )
			.then( function () {
				setBusy( false );
			} );
	}

	document.addEventListener( 'DOMContentLoaded', function () {
		wireCounters();
		var btn = document.getElementById( 'odysseo-seo-generate' );
		if ( btn ) {
			btn.addEventListener( 'click', function () {
				var postId = btn.getAttribute( 'data-post' );
				if ( ! postId || postId === '0' ) {
					setStatus( ( cfg.i18n && cfg.i18n.saveFirst ) || 'Save a draft first.', true );
					return;
				}
				generate( postId );
			} );
		}
	} );
} )();
