/**
 * Biscotti CMP — Legal Documents (local admin script)
 *
 * Drives the native Documents page: generate a new document, edit content in an
 * inline modal, toggle publish/draft, copy the document shortcode and assign a
 * document to a WordPress page. All writes go through the authenticated
 * admin-ajax proxy (biscotti_proxy -> generate-document | view-document |
 * save-document-content | toggle-document) or the local handlers
 * (biscotti_get_pages, biscotti_assign_page). No remote code.
 *
 * @package Biscotti_CMP
 */
( function ( $ ) {
	'use strict';

	var cfg = window.biscottiAdmin || {};
	var i18n = cfg.i18n || {};
	function t( k, f ) { return i18n[ k ] || f; }

	function setStatus( id, msg, isError ) {
		var el = document.getElementById( id );
		if ( ! el ) { return; }
		el.textContent = msg;
		el.style.color = isError ? '#dc2626' : '#16a34a';
	}

	// Proxy POST helper.
	function proxy( proxyAction, payload ) {
		return $.ajax( {
			url: cfg.ajaxUrl,
			method: 'POST',
			data: {
				action: 'biscotti_proxy',
				nonce: cfg.nonce,
				proxy_action: proxyAction,
				payload: JSON.stringify( payload || {} )
			}
		} );
	}

	$( function () {

		// ---- Generate new document ----
		$( '#biscotti-doc-generate' ).on( 'click', function () {
			var $btn = $( this );
			var type = document.getElementById( 'biscotti-doc-gen-type' ).value;
			if ( ! type ) {
				setStatus( 'biscotti-doc-gen-status', '❌ ' + t( 'selectType', 'Please select a document type.' ), true );
				return;
			}
			var original = $btn.html();
			$btn.prop( 'disabled', true ).text( t( 'generating', 'Generating…' ) );
			setStatus( 'biscotti-doc-gen-status', t( 'generating', 'Generating…' ), false );
			proxy( 'generate-document', { documentType: type, language: 'de' } )
				.done( function ( res ) {
					if ( res && res.success ) {
						setStatus( 'biscotti-doc-gen-status', '✅ ' + t( 'saved', 'Done!' ), false );
						setTimeout( function () { window.location.reload(); }, 1500 );
					} else {
						$btn.prop( 'disabled', false ).html( original );
						setStatus( 'biscotti-doc-gen-status', '❌ ' + ( ( res && res.data ) || t( 'error', 'Error' ) ), true );
					}
				} )
				.fail( function () {
					$btn.prop( 'disabled', false ).html( original );
					setStatus( 'biscotti-doc-gen-status', '❌ ' + t( 'connectionError', 'Connection error' ), true );
				} );
		} );

		// ---- Copy shortcode ----
		$( document ).on( 'click', '.biscotti-doc-copy', function () {
			var sc = $( this ).data( 'shortcode' );
			if ( navigator.clipboard ) {
				navigator.clipboard.writeText( sc );
			} else {
				var ta = document.createElement( 'textarea' );
				ta.value = sc; document.body.appendChild( ta ); ta.select();
				document.execCommand( 'copy' ); document.body.removeChild( ta );
			}
			if ( window.BiscottiAdmin && BiscottiAdmin.showToast ) {
				BiscottiAdmin.showToast( 'success', t( 'copied', 'Copied!' ) );
			}
		} );

		// ---- Edit modal ----
		var editingId = null;
		var $editor = $( '#biscotti-doc-editor' );

		function openEditor() { $editor.addClass( 'is-open' ); }
		function closeEditor() { $editor.removeClass( 'is-open' ); editingId = null; }

		$( document ).on( 'click', '.biscotti-doc-edit', function () {
			editingId = $( this ).data( 'documentId' );
			var name = $( this ).data( 'documentName' ) || '';
			document.getElementById( 'biscotti-doc-editor-title' ).textContent = '📝 ' + name;
			var $content = $( '#biscotti-doc-editor-content' );
			$content.html( '<p style="color:#94a3b8;">' + t( 'loading', 'Loading…' ) + '</p>' );
			setStatus( 'biscotti-doc-editor-status', '', false );
			openEditor();
			proxy( 'view-document', { documentId: editingId } )
				.done( function ( res ) {
					if ( res && res.success && res.data && res.data.document && res.data.document.content ) {
						$content.html( res.data.document.content );
					} else {
						$content.html( '<p style="color:#dc2626;">' + ( ( res && res.data && typeof res.data === 'string' ? res.data : null ) || t( 'error', 'Error' ) ) + '</p>' );
					}
				} )
				.fail( function () {
					$content.html( '<p style="color:#dc2626;">' + t( 'connectionError', 'Connection error' ) + '</p>' );
				} );
		} );

		$( '#biscotti-doc-editor-close, #biscotti-doc-editor-cancel' ).on( 'click', closeEditor );
		$editor.on( 'click', function ( e ) { if ( e.target === this ) { closeEditor(); } } );

		$( '#biscotti-doc-editor-save' ).on( 'click', function () {
			if ( ! editingId ) { return; }
			var content = document.getElementById( 'biscotti-doc-editor-content' ).innerHTML;
			var $btn = $( this );
			$btn.prop( 'disabled', true );
			setStatus( 'biscotti-doc-editor-status', t( 'saving', 'Saving…' ), false );
			proxy( 'save-document-content', { documentId: editingId, content: content } )
				.done( function ( res ) {
					if ( res && res.success ) {
						setStatus( 'biscotti-doc-editor-status', '✅ ' + t( 'saved', 'Saved!' ), false );
					} else {
						setStatus( 'biscotti-doc-editor-status', '❌ ' + ( ( res && res.data ) || t( 'error', 'Error' ) ), true );
					}
				} )
				.fail( function () { setStatus( 'biscotti-doc-editor-status', '❌ ' + t( 'connectionError', 'Connection error' ), true ); } )
				.always( function () { $btn.prop( 'disabled', false ); } );
		} );

		// ---- Toggle publish/draft ----
		$( document ).on( 'click', '.biscotti-doc-toggle', function () {
			var $btn = $( this );
			var id = $btn.data( 'documentId' );
			var original = $btn.text();
			$btn.prop( 'disabled', true ).text( t( 'saving', 'Saving…' ) );
			proxy( 'toggle-document', { documentId: id } )
				.done( function ( res ) {
					if ( res && res.success ) {
						setTimeout( function () { window.location.reload(); }, 600 );
					} else {
						$btn.prop( 'disabled', false ).text( original );
						if ( window.BiscottiAdmin && BiscottiAdmin.showToast ) {
							BiscottiAdmin.showToast( 'error', ( res && res.data ) || t( 'error', 'Error' ) );
						}
					}
				} )
				.fail( function () {
					$btn.prop( 'disabled', false ).text( original );
					if ( window.BiscottiAdmin && BiscottiAdmin.showToast ) {
						BiscottiAdmin.showToast( 'error', t( 'connectionError', 'Connection error' ) );
					}
				} );
		} );

		// ---- Assign to page modal ----
		var assignType = null;
		var $assigner = $( '#biscotti-doc-assigner' );
		var pagesLoaded = false;

		function openAssigner() { $assigner.addClass( 'is-open' ); }
		function closeAssigner() { $assigner.removeClass( 'is-open' ); assignType = null; }

		function loadPages() {
			var $sel = $( '#biscotti-doc-assign-page' );
			$.post( cfg.ajaxUrl, { action: 'biscotti_get_pages', nonce: cfg.nonce } )
				.done( function ( res ) {
					$sel.empty();
					if ( res && res.success && Array.isArray( res.data ) && res.data.length ) {
						res.data.forEach( function ( p ) {
							var label = p.title + ( p.status === 'draft' ? ' (' + t( 'draft', 'Draft' ) + ')' : '' );
							$sel.append( $( '<option>' ).val( p.id ).text( label ) );
						} );
						pagesLoaded = true;
					} else {
						$sel.append( $( '<option>' ).val( '' ).text( t( 'noPages', 'No pages found' ) ) );
					}
				} )
				.fail( function () {
					$sel.empty().append( $( '<option>' ).val( '' ).text( t( 'connectionError', 'Connection error' ) ) );
				} );
		}

		$( document ).on( 'click', '.biscotti-doc-assign', function () {
			assignType = $( this ).data( 'documentType' );
			setStatus( 'biscotti-doc-assign-status', '', false );
			openAssigner();
			if ( ! pagesLoaded ) { loadPages(); }
		} );

		$( '#biscotti-doc-assigner-close, #biscotti-doc-assigner-cancel' ).on( 'click', closeAssigner );
		$assigner.on( 'click', function ( e ) { if ( e.target === this ) { closeAssigner(); } } );

		$( '#biscotti-doc-assign-confirm' ).on( 'click', function () {
			var pageId = $( '#biscotti-doc-assign-page' ).val();
			if ( ! pageId || ! assignType ) {
				setStatus( 'biscotti-doc-assign-status', '❌ ' + t( 'selectPage', 'Please select a page.' ), true );
				return;
			}
			var $btn = $( this );
			$btn.prop( 'disabled', true );
			setStatus( 'biscotti-doc-assign-status', t( 'saving', 'Saving…' ), false );
			$.post( cfg.ajaxUrl, {
				action: 'biscotti_assign_page',
				nonce: cfg.nonce,
				page_id: pageId,
				document_type: assignType
			} )
				.done( function ( res ) {
					if ( res && res.success ) {
						setStatus( 'biscotti-doc-assign-status', '✅ ' + t( 'saved', 'Assigned!' ), false );
						setTimeout( closeAssigner, 1200 );
					} else {
						setStatus( 'biscotti-doc-assign-status', '❌ ' + ( ( res && res.data ) || t( 'error', 'Error' ) ), true );
					}
				} )
				.fail( function () { setStatus( 'biscotti-doc-assign-status', '❌ ' + t( 'connectionError', 'Connection error' ), true ); } )
				.always( function () { $btn.prop( 'disabled', false ); } );
		} );

		// Close modals on Escape.
		$( document ).on( 'keydown', function ( e ) {
			if ( e.key === 'Escape' ) { closeEditor(); closeAssigner(); }
		} );
	} );
} )( jQuery );
