<?php
/**
 * AI Extras meta box for the classic product editor.
 *
 * Exposes the v1.0.6 endpoints (tags, attributes, per-variation descriptions)
 * as buttons so shop managers can use them without waiting on the React panel.
 *
 * @package CatalogPilot\AiStudio
 */

namespace CatalogPilot\AiStudio;

defined( 'ABSPATH' ) || exit;

final class AI_Extras_MetaBox {

	private static $instance = null;

	public static function instance() {
		if ( null === self::$instance ) {
			self::$instance = new self();
			add_action( 'add_meta_boxes', array( self::$instance, 'register' ) );
			add_action( 'admin_enqueue_scripts', array( self::$instance, 'enqueue' ) );
		}
		return self::$instance;
	}

	public function register() {
		add_meta_box(
			'cpais_ai_extras',
			esc_html__( 'CatalogPilot AI — Tags · Attributes · Variations', 'catalogpilot-ai-studio-for-woocommerce' ),
			array( $this, 'render' ),
			'product',
			'normal',
			'high'
		);
	}

	public function enqueue( $hook ) {
		if ( 'post.php' !== $hook && 'post-new.php' !== $hook ) {
			return;
		}
		if ( 'product' !== get_post_type() ) {
			return;
		}
		wp_add_inline_style( 'wp-admin', $this->css() );
	}

	private function css() {
		return '
		.cpais-ext{--cpp:#6366f1;--cps:#8b5cf6;--cpg:#00a32a;--cpr:#b32d2e}
		.cpais-ext__tabs{display:flex;gap:2px;border-bottom:2px solid #dcdcde;margin-bottom:14px;overflow-x:auto}
		.cpais-ext__tab{background:transparent;border:0;padding:9px 14px;cursor:pointer;font-weight:600;font-size:13px;color:#50575e;border-bottom:3px solid transparent;margin-bottom:-2px}
		.cpais-ext__tab.is-active{color:var(--cpp);border-bottom-color:var(--cpp)}
		.cpais-ext__pane{display:none}
		.cpais-ext__pane.is-active{display:block}
		.cpais-ext__row{display:flex;gap:10px;align-items:center;flex-wrap:wrap;margin-bottom:14px}
		.cpais-ext__row label{font-size:12.5px;color:#50575e}
		.cpais-ext__list{background:#f6f7f7;border-radius:6px;padding:10px 14px;font-size:13px;min-height:40px}
		.cpais-ext__chip{display:inline-block;background:#e0e7ff;color:#3730a3;padding:4px 10px;border-radius:12px;margin:3px;font-size:12px;font-weight:600}
		.cpais-ext__attr-row{background:#fff;border:1px solid #dcdcde;border-radius:6px;padding:8px 12px;margin-bottom:6px;display:grid;grid-template-columns:1fr 2fr;gap:10px;align-items:start}
		.cpais-ext__attr-row strong{color:#1e1b4b}
		.cpais-ext__status{padding:8px 12px;border-radius:6px;margin-top:10px;font-size:12.5px;display:none}
		.cpais-ext__status.ok{display:block;background:#d1e7dd;color:#0f5132;border:1px solid #a3cfbb}
		.cpais-ext__status.err{display:block;background:#f8d7da;color:#842029;border:1px solid #f1aeb5}
		.cpais-ext__status.info{display:block;background:#cff4fc;color:#055160;border:1px solid #9eeaf9}
		.cpais-ext__note{color:#666;font-size:12px;font-style:italic;margin-top:6px}
		.cpais-ext__variation{background:#fff;border:1px solid #dcdcde;border-radius:6px;padding:12px;margin-bottom:8px}
		.cpais-ext__variation-title{font-weight:600;color:#1e1b4b;margin-bottom:6px}
		.cpais-ext__variation textarea{width:100%;min-height:80px;font-family:inherit;font-size:13px}
		';
	}

	public function render( $post ) {
		$rest_url = esc_url_raw( rest_url( 'cpais/v1/' ) );
		$nonce    = wp_create_nonce( 'wp_rest' );
		$product  = wc_get_product( $post->ID );
		$is_variable = $product && $product->is_type( 'variable' );

		$variations = array();
		if ( $is_variable ) {
			foreach ( $product->get_children() as $var_id ) {
				$v = wc_get_product( $var_id );
				if ( ! $v ) { continue; }
				$attrs = array();
				foreach ( $v->get_variation_attributes() as $k => $val ) {
					$attrs[] = wc_attribute_label( str_replace( array( 'attribute_pa_', 'attribute_' ), '', $k ) ) . ': ' . $val;
				}
				$variations[] = array(
					'id'          => $var_id,
					'label'       => implode( ' · ', $attrs ) ?: sprintf( '#%d', $var_id ),
					'description' => $v->get_description(),
				);
			}
		}
		?>
		<div class="cpais-ext">
			<div class="cpais-ext__tabs" role="tablist">
				<button type="button" class="cpais-ext__tab is-active" data-tab="tags">🏷️ <?php esc_html_e( 'AI Tags', 'catalogpilot-ai-studio-for-woocommerce' ); ?></button>
				<button type="button" class="cpais-ext__tab" data-tab="attributes">📋 <?php esc_html_e( 'AI Attributes', 'catalogpilot-ai-studio-for-woocommerce' ); ?></button>
				<?php if ( $is_variable ) : ?>
				<button type="button" class="cpais-ext__tab" data-tab="variations">🎨 <?php esc_html_e( 'AI Variation Descriptions', 'catalogpilot-ai-studio-for-woocommerce' ); ?></button>
				<?php endif; ?>
				<button type="button" class="cpais-ext__tab" data-tab="bgremove">🪄 <?php esc_html_e( 'Background Remover', 'catalogpilot-ai-studio-for-woocommerce' ); ?></button>
				<button type="button" class="cpais-ext__tab" data-tab="schema">🎯 <?php esc_html_e( 'Product Schema', 'catalogpilot-ai-studio-for-woocommerce' ); ?></button>
			</div>

			<div class="cpais-ext__pane is-active" data-pane="tags">
				<div class="cpais-ext__row">
					<label for="cpais-tag-count"><?php esc_html_e( 'How many tags?', 'catalogpilot-ai-studio-for-woocommerce' ); ?></label>
					<input type="number" id="cpais-tag-count" min="3" max="15" value="6" style="width:80px">
					<button type="button" class="button button-primary" id="cpais-gen-tags"><?php esc_html_e( '🤖 Generate tag suggestions', 'catalogpilot-ai-studio-for-woocommerce' ); ?></button>
					<button type="button" class="button" id="cpais-apply-tags" style="display:none"><?php esc_html_e( '✅ Add suggested tags to product', 'catalogpilot-ai-studio-for-woocommerce' ); ?></button>
				</div>
				<div class="cpais-ext__list" id="cpais-tags-list"><em><?php esc_html_e( 'Suggested tags will appear here.', 'catalogpilot-ai-studio-for-woocommerce' ); ?></em></div>
				<p class="cpais-ext__note"><?php esc_html_e( 'Tags are added to the existing tag list — nothing is deleted.', 'catalogpilot-ai-studio-for-woocommerce' ); ?></p>
			</div>

			<div class="cpais-ext__pane" data-pane="attributes">
				<div class="cpais-ext__row">
					<label for="cpais-attr-count"><?php esc_html_e( 'How many attributes?', 'catalogpilot-ai-studio-for-woocommerce' ); ?></label>
					<input type="number" id="cpais-attr-count" min="3" max="12" value="6" style="width:80px">
					<button type="button" class="button button-primary" id="cpais-gen-attrs"><?php esc_html_e( '🤖 Suggest attributes', 'catalogpilot-ai-studio-for-woocommerce' ); ?></button>
					<button type="button" class="button" id="cpais-apply-attrs" style="display:none"><?php esc_html_e( '✅ Add attributes to product', 'catalogpilot-ai-studio-for-woocommerce' ); ?></button>
				</div>
				<div id="cpais-attrs-list"><em class="cpais-ext__note"><?php esc_html_e( 'Suggested name/value pairs will appear here as editable rows.', 'catalogpilot-ai-studio-for-woocommerce' ); ?></em></div>
			</div>

			<?php if ( $is_variable ) : ?>
			<div class="cpais-ext__pane" data-pane="variations">
				<p class="cpais-ext__note"><?php esc_html_e( 'Generate a per-variation description that highlights what makes each specific combination unique.', 'catalogpilot-ai-studio-for-woocommerce' ); ?></p>
				<?php foreach ( $variations as $v ) : ?>
					<div class="cpais-ext__variation" data-variation-id="<?php echo (int) $v['id']; ?>">
						<div class="cpais-ext__variation-title"><?php echo esc_html( $v['label'] ); ?></div>
						<textarea data-variation-text><?php echo esc_textarea( $v['description'] ); ?></textarea>
						<div class="cpais-ext__row" style="margin-top:8px">
							<label><?php esc_html_e( 'Target length', 'catalogpilot-ai-studio-for-woocommerce' ); ?>:</label>
							<input type="number" data-variation-words value="60" min="20" max="200" style="width:80px"> <?php esc_html_e( 'words', 'catalogpilot-ai-studio-for-woocommerce' ); ?>
							<button type="button" class="button button-primary" data-variation-gen><?php esc_html_e( '🤖 Generate', 'catalogpilot-ai-studio-for-woocommerce' ); ?></button>
							<button type="button" class="button" data-variation-apply><?php esc_html_e( '💾 Save to variation', 'catalogpilot-ai-studio-for-woocommerce' ); ?></button>
						</div>
					</div>
				<?php endforeach; ?>
			</div>
			<?php endif; ?>

			<?php
			$feat_id = get_post_thumbnail_id( $post->ID );
			$feat_thumb = $feat_id ? wp_get_attachment_image_url( $feat_id, 'medium' ) : '';
			$gallery_ids = $product ? $product->get_gallery_image_ids() : array();
			?>
			<div class="cpais-ext__pane" data-pane="bgremove">
				<p><?php esc_html_e( 'Remove the background from a product image with AI. Creates a transparent PNG saved to your media library and attaches it to the product.', 'catalogpilot-ai-studio-for-woocommerce' ); ?></p>
				<p class="cpais-ext__note"><?php esc_html_e( 'Requires a Replicate API token in Settings (uses the 851-labs/background-remover model).', 'catalogpilot-ai-studio-for-woocommerce' ); ?></p>

				<div class="cpais-ext__row">
					<label for="cpais-bg-source"><?php esc_html_e( 'Source image', 'catalogpilot-ai-studio-for-woocommerce' ); ?></label>
					<select id="cpais-bg-source" style="min-width:260px">
						<?php if ( $feat_id ) : ?>
							<option value="<?php echo (int) $feat_id; ?>"><?php esc_html_e( 'Featured image', 'catalogpilot-ai-studio-for-woocommerce' ); ?> (#<?php echo (int) $feat_id; ?>)</option>
						<?php endif; ?>
						<?php foreach ( $gallery_ids as $gid ) : ?>
							<option value="<?php echo (int) $gid; ?>"><?php esc_html_e( 'Gallery image', 'catalogpilot-ai-studio-for-woocommerce' ); ?> (#<?php echo (int) $gid; ?>)</option>
						<?php endforeach; ?>
					</select>
					<?php if ( ! $feat_id && empty( $gallery_ids ) ) : ?>
						<em class="cpais-ext__note"><?php esc_html_e( 'No product images yet — add one first.', 'catalogpilot-ai-studio-for-woocommerce' ); ?></em>
					<?php endif; ?>
				</div>

				<div class="cpais-ext__row">
					<label for="cpais-bg-attach"><?php esc_html_e( 'After removing', 'catalogpilot-ai-studio-for-woocommerce' ); ?></label>
					<select id="cpais-bg-attach">
						<option value="gallery"><?php esc_html_e( 'Add cutout to gallery', 'catalogpilot-ai-studio-for-woocommerce' ); ?></option>
						<option value="featured"><?php esc_html_e( 'Set cutout as featured image', 'catalogpilot-ai-studio-for-woocommerce' ); ?></option>
						<option value="none"><?php esc_html_e( 'Just save to media library', 'catalogpilot-ai-studio-for-woocommerce' ); ?></option>
					</select>
					<button type="button" class="button button-primary" id="cpais-bg-run" <?php disabled( ! $feat_id && empty( $gallery_ids ) ); ?>>🪄 <?php esc_html_e( 'Remove background', 'catalogpilot-ai-studio-for-woocommerce' ); ?></button>
				</div>

				<div id="cpais-bg-preview" style="display:none;margin-top:14px">
					<div style="display:grid;grid-template-columns:1fr 1fr;gap:14px">
						<div>
							<strong style="display:block;margin-bottom:6px"><?php esc_html_e( 'Original', 'catalogpilot-ai-studio-for-woocommerce' ); ?></strong>
							<img id="cpais-bg-original" src="<?php echo esc_url( $feat_thumb ); ?>" style="max-width:100%;border:1px solid #dcdcde;border-radius:6px">
						</div>
						<div>
							<strong style="display:block;margin-bottom:6px"><?php esc_html_e( 'Cutout (transparent PNG)', 'catalogpilot-ai-studio-for-woocommerce' ); ?></strong>
							<div id="cpais-bg-result-wrap" style="min-height:150px;background:repeating-conic-gradient(#ddd 0% 25%, #fff 0% 50%) 50% / 20px 20px;border:1px solid #dcdcde;border-radius:6px;display:flex;align-items:center;justify-content:center">
								<img id="cpais-bg-result" src="" style="max-width:100%;display:none">
							</div>
						</div>
					</div>
				</div>
			</div>

			<div class="cpais-ext__pane" data-pane="schema">
				<p><strong><?php esc_html_e( 'schema.org/Product JSON-LD is auto-emitted on the single-product page.', 'catalogpilot-ai-studio-for-woocommerce' ); ?></strong></p>
				<p><?php esc_html_e( 'Fields included: name, description, image(s), SKU, GTIN (if set), brand (from a "brand" attribute if you have one), offers (with price + currency + availability), aggregateRating (when reviews exist).', 'catalogpilot-ai-studio-for-woocommerce' ); ?></p>
				<p class="cpais-ext__note"><?php esc_html_e( 'CatalogPilot detects Yoast, Rank Math or AIOSEO and steps aside when they are active, so you never get duplicate Product schema.', 'catalogpilot-ai-studio-for-woocommerce' ); ?></p>
				<div class="cpais-ext__row">
					<a class="button" href="<?php echo esc_url( 'https://search.google.com/test/rich-results?url=' . rawurlencode( get_permalink( $post ) ) ); ?>" target="_blank" rel="noopener"><?php esc_html_e( '🔍 Test with Google Rich Results', 'catalogpilot-ai-studio-for-woocommerce' ); ?></a>
					<button type="button" class="button" id="cpais-view-schema"><?php esc_html_e( 'View emitted JSON', 'catalogpilot-ai-studio-for-woocommerce' ); ?></button>
				</div>
				<pre id="cpais-schema-preview" style="display:none;background:#f6f7f7;border:1px solid #dcdcde;border-radius:6px;padding:12px;margin-top:10px;overflow:auto;max-height:400px;font-size:11.5px"></pre>
			</div>

			<div class="cpais-ext__status" id="cpais-ext-status"></div>
		</div>

		<script>
		(function(){
			var pid=<?php echo (int) $post->ID; ?>,rest=<?php echo wp_json_encode( $rest_url ); ?>,nonce=<?php echo wp_json_encode( $nonce ); ?>;
			var permalink=<?php echo wp_json_encode( get_permalink( $post ) ); ?>;
			var st=document.getElementById('cpais-ext-status');
			var lastTags=[],lastAttrs=[];

			document.querySelectorAll('.cpais-ext__tab').forEach(function(btn){
				btn.addEventListener('click',function(){
					document.querySelectorAll('.cpais-ext__tab').forEach(function(b){b.classList.remove('is-active')});
					document.querySelectorAll('.cpais-ext__pane').forEach(function(p){p.classList.remove('is-active')});
					btn.classList.add('is-active');
					document.querySelector('.cpais-ext__pane[data-pane="'+btn.dataset.tab+'"]').classList.add('is-active');
				});
			});

			function say(msg,type){st.className='cpais-ext__status '+(type||'info');st.textContent=msg;}
			function api(path,method,body){
				say('Working...','info');
				return fetch(rest+path,{
					method:method||'POST',
					headers:{'Content-Type':'application/json','X-WP-Nonce':nonce},
					body:body?JSON.stringify(body):undefined,
					credentials:'same-origin'
				}).then(function(r){return r.json().then(function(j){return{ok:r.ok,body:j}})});
			}

			// Tags
			document.getElementById('cpais-gen-tags').addEventListener('click',function(){
				var n=parseInt(document.getElementById('cpais-tag-count').value,10)||6;
				api('generate-tags','POST',{product_id:pid,tag_count:n}).then(function(res){
					if(!res.ok){say((res.body&&res.body.message)||'Failed','err');return;}
					lastTags=res.body.tags||[];
					var html='';
					lastTags.forEach(function(t){html+='<span class="cpais-ext__chip">'+t+'</span>';});
					document.getElementById('cpais-tags-list').innerHTML=html||'<em>No tags returned</em>';
					document.getElementById('cpais-apply-tags').style.display='inline-block';
					say('Generated '+lastTags.length+' tag(s). Review then apply.','ok');
				}).catch(function(){say('Network error','err')});
			});
			document.getElementById('cpais-apply-tags').addEventListener('click',function(){
				if(!lastTags.length){say('Generate tags first','err');return;}
				api('apply-tags','POST',{product_id:pid,tags:lastTags}).then(function(res){
					if(!res.ok){say((res.body&&res.body.message)||'Failed','err');return;}
					say((res.body.applied||0)+' tag(s) applied. Reload to see them.','ok');
				});
			});

			// Attributes
			document.getElementById('cpais-gen-attrs').addEventListener('click',function(){
				var n=parseInt(document.getElementById('cpais-attr-count').value,10)||6;
				api('generate-attributes','POST',{product_id:pid,attribute_count:n}).then(function(res){
					if(!res.ok){say((res.body&&res.body.message)||'Failed','err');return;}
					lastAttrs=res.body.attributes||[];
					var wrap=document.getElementById('cpais-attrs-list');
					wrap.innerHTML='';
					lastAttrs.forEach(function(a,i){
						var row=document.createElement('div');
						row.className='cpais-ext__attr-row';
						row.innerHTML='<div><strong>'+escapeHTML(a.name)+'</strong></div><div>'+escapeHTML(a.value)+'</div>';
						wrap.appendChild(row);
					});
					document.getElementById('cpais-apply-attrs').style.display='inline-block';
					say('Suggested '+lastAttrs.length+' attribute(s).','ok');
				});
			});
			document.getElementById('cpais-apply-attrs').addEventListener('click',function(){
				if(!lastAttrs.length){say('Generate attributes first','err');return;}
				api('apply-attributes','POST',{product_id:pid,attributes:lastAttrs}).then(function(res){
					if(!res.ok){say((res.body&&res.body.message)||'Failed','err');return;}
					say((res.body.applied||0)+' attribute(s) added. Reload to see them.','ok');
				});
			});

			// Variations
			document.querySelectorAll('[data-variation-id]').forEach(function(row){
				var vid=parseInt(row.dataset.variationId,10);
				var textarea=row.querySelector('[data-variation-text]');
				var words=row.querySelector('[data-variation-words]');
				row.querySelector('[data-variation-gen]').addEventListener('click',function(){
					var n=parseInt(words.value,10)||60;
					api('generate-variation-description','POST',{variation_id:vid,variation_words:n}).then(function(res){
						if(!res.ok){say((res.body&&res.body.message)||'Failed','err');return;}
						textarea.value=(res.body.description||'').replace(/<\/?[^>]+>/g,'');
						say('Generated variation description ('+(res.body.description||'').length+' chars).','ok');
					});
				});
				row.querySelector('[data-variation-apply]').addEventListener('click',function(){
					api('apply-variation-description','POST',{variation_id:vid,description:textarea.value}).then(function(res){
						if(!res.ok){say((res.body&&res.body.message)||'Failed','err');return;}
						say('Variation description saved.','ok');
					});
				});
			});

			// Background remover
			var bgRunBtn=document.getElementById('cpais-bg-run');
			if(bgRunBtn){bgRunBtn.addEventListener('click',function(){
				var src=parseInt(document.getElementById('cpais-bg-source').value,10);
				var attach=document.getElementById('cpais-bg-attach').value;
				if(!src){say('Select an image first','err');return;}
				bgRunBtn.disabled=true;
				document.getElementById('cpais-bg-preview').style.display='block';
				document.getElementById('cpais-bg-original').src=document.getElementById('cpais-bg-source').selectedOptions[0].dataset.thumb||document.getElementById('cpais-bg-original').src;
				say('Removing background… (up to 90 sec)','info');
				api('remove-background','POST',{product_id:pid,attachment_id:src,attach_as:attach}).then(function(res){
					bgRunBtn.disabled=false;
					if(!res.ok){say((res.body&&res.body.message)||'Failed','err');return;}
					var img=document.getElementById('cpais-bg-result');
					var url=res.body.url||res.body.image_url||'';
					if(!url){say('Removed, but no URL returned (attachment id: '+(res.body.attachment_id||'?')+')','info');return;}
					img.src=url;img.style.display='block';
					say('Background removed. New attachment #'+(res.body.attachment_id||'?')+' created.','ok');
				});
			});}

			// Schema preview
			document.getElementById('cpais-view-schema').addEventListener('click',function(){
				var box=document.getElementById('cpais-schema-preview');
				box.style.display='block';
				box.textContent='Loading '+permalink+' …';
				fetch(permalink,{credentials:'same-origin'}).then(function(r){return r.text()}).then(function(html){
					var m=html.match(/<script type=\"application\/ld\+json\">([\s\S]*?)<\/script>/g);
					if(!m){box.textContent='No JSON-LD found on the frontend page.';return;}
					box.textContent=m.map(function(x){return x.replace(/<[^>]+>/g,'')}).join('\n---\n');
				}).catch(function(e){box.textContent='Could not fetch frontend: '+e.message});
			});

			function escapeHTML(s){return String(s||'').replace(/[&<>"\']/g,function(c){return{'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]});}
		})();
		</script>
		<?php
	}
}
