jQuery(document).ready(function($) {

	let isProcessing = false;
	let currentFilter = 'all';

	const nonce   = window.r_llm_seo_vars?.nonce || '';
	const ajaxurl = window.r_llm_seo_vars?.ajaxurl || window.ajaxurl;
	const i18n    = window.r_llm_seo_vars?.i18n || {};

	const $tagbox = $('#f02-tagbox');
	const $input  = $('#f02-keyword-input');
	const $pt     = $('#f02-post-type');
	const $btnGen = $('#f02-generate');
	const $tbody  = $('#f02-table-body');

	const $filterAll = $('#f02-filter-all');
	const $filterFav = $('#f02-filter-fav');
	const $btnDelAll = $('#f02-delete-all');

	const state = {
		keywords: [],
		items: []
	};

	function t(key, fallback) {
		const v = i18n?.[key];
		return (typeof v === 'string' && v.trim() !== '') ? v : fallback;
	}

	function setUILock(lock) {
		isProcessing = lock;

		$('#f02-generate, #f02-post-type, #f02-keyword-input, #f02-delete-all').prop('disabled', lock);
		$('.f02-draft, .f02-fav, .f02-del').prop('disabled', lock);
		$('#f02-filter-all, #f02-filter-fav').prop('disabled', lock);
	}

	function pickMessage(res, xhr) {
		const m1 = res?.data?.message;
		if (typeof m1 === 'string' && m1.trim() !== '') return m1.trim();

		const m2 = res?.message;
		if (typeof m2 === 'string' && m2.trim() !== '') return m2.trim();

		const m3 = xhr?.responseJSON?.data?.message || xhr?.responseJSON?.message;
		if (typeof m3 === 'string' && m3.trim() !== '') return m3.trim();

		return '';
	}

	function pickCode(res, xhr) {
		const c1 = res?.data?.code ?? res?.code;
		if (typeof c1 === 'string' && c1 !== '') return c1;

		const c2 = xhr?.responseJSON?.data?.code ?? xhr?.responseJSON?.code;
		if (typeof c2 === 'string' && c2 !== '') return c2;

		return '';
	}

	function toUserMessage(res, xhr) {
		const http = xhr?.status || 0;
		const code = pickCode(res, xhr);
		const serverMsg = pickMessage(res, xhr);

		if (code === 'config_error') {
			return t('config_error', 'APIキーが設定されていません。設定ページからAPIキーを入力してください。');
		}

		if (serverMsg) return serverMsg;
		if (http) return `${t('ajax_error', '処理に失敗しました。')}（HTTP ${http}）`;
		return t('ajax_error', '処理に失敗しました。');
	}

	function handleAjaxError(tag, res, xhr) {
		console.error('AJAX ERROR:', tag, res, xhr?.status, xhr?.responseText);
		alert(toUserMessage(res, xhr));
	}

	function cooldownButton($btn, seconds, finalText) {
		seconds = Number(seconds || 3);

		const originalText =
			(typeof finalText === 'string' && finalText.trim() !== '') ? finalText :
			($btn.data('original-text') || $btn.text());

		$btn.data('original-text', originalText);

		const prevTimer = $btn.data('cooldown-timer');
		if (prevTimer) {
			clearInterval(prevTimer);
			$btn.removeData('cooldown-timer');
		}

		let remain = seconds;

		$btn.prop('disabled', true).addClass('ui-locked');
		$btn.text(`${remain}s`);

		const timer = setInterval(function() {
			remain--;

			if (remain <= 0) {
				clearInterval(timer);
				$btn.removeData('cooldown-timer');
				$btn.text(originalText);

				if (!isProcessing) {
					$btn.prop('disabled', false).removeClass('ui-locked');
				}
				return;
			}

			$btn.text(`${remain}s`);
		}, 1000);

		$btn.data('cooldown-timer', timer);
	}

	function renderTags() {
		$tagbox.find('.f02-tag').remove();

		state.keywords.forEach((kw, idx) => {
			const $tag = $('<span class="f02-tag"></span>');
			$tag.append(document.createTextNode(kw));

			const $x = $('<button type="button" class="f02-tag-x">×</button>');
			$x.on('click', function(){
				state.keywords.splice(idx, 1);
				renderTags();
			});

			$tag.append($x);
			$input.before($tag);
		});
	}

	function addKeyword(kw) {
		kw = (kw || '').trim();
		if (!kw) return;
		if (state.keywords.includes(kw)) return;
		state.keywords.push(kw);
		renderTags();
	}

	function splitAndAdd(v) {
		const parts = (v || '').split(/[\t ]+/).map(s => s.trim()).filter(Boolean);
		parts.forEach(addKeyword);
	}

	$input.on('keydown', function(e){
		if (e.key === 'Tab' || e.key === 'Enter' || e.key === ' ') {
			e.preventDefault();
			splitAndAdd($input.val());
			$input.val('');
		}
		if (e.key === 'Backspace' && $input.val() === '' && state.keywords.length) {
			state.keywords.pop();
			renderTags();
		}
	});
	$tagbox.on('click', function(){ $input.trigger('focus'); });

	function clearEmptyRows() {
		$tbody.find('tr.f02-empty').remove();
	}

	function showEmptyRow(msg) {
		const text = msg || t('empty_default', 'まだタイトル案がありません。キーワードを入れて「タイトル案生成」を押してください。');

		clearEmptyRows();

		const $tr = $('<tr class="f02-empty"></tr>');
		const $td = $('<td colspan="4"></td>').text(text);
		$tr.append($td);

		$tbody.append($tr);
	}

	function renderFromRowsHtml(rowsHtml) {
		rowsHtml = String(rowsHtml || '');
		if (!rowsHtml.trim()) {
			$tbody.empty();
			showEmptyRow();
			return;
		}
		$tbody.html(rowsHtml);
	}

	function applyFilterToDom() {
		const showFavOnly = (currentFilter === 'fav');

		clearEmptyRows();

		const $rows = $tbody.find('tr').not('.f02-empty');

		$rows.each(function(){
			const $tr = $(this);

			if (!showFavOnly) {
				$tr.show();
				return;
			}

			const id = String($tr.data('id') || '');
			const item = state.items.find(it => String(it.id) === id);
			const isFav = !!(item && item.is_fav);
			$tr.toggle(isFav);
		});

		if (showFavOnly) {
			const anyVisible = $rows.filter(function(){ return $(this).is(':visible'); }).length > 0;
			if (!anyVisible) {
				showEmptyRow(t('empty_fav', 'お気に入りのタイトル案がありません。'));
			}
		} else {
			if ($rows.length === 0) {
				showEmptyRow();
			}
		}
	}

	$tbody.on('click', '.f02-draft', function(){
		if (isProcessing) return;

		const $tr = $(this).closest('tr');
		const id = String($tr.data('id') || '');
		const title = String($tr.find('.f02-title').val() || '').trim();
		const postType = String($(this).data('post-type') || $pt.val() || 'post');

		if (!id) return;
		if (!title) return alert(t('title_empty', 'タイトルが空です。'));

		setUILock(true);

		$.post(ajaxurl, {
			action: 'r_llm_seo_create_ai_draft_f02',
			nonce: nonce,
			id: id,
			title: title,
			post_type: postType
		}).done(function(res){
			if (!res?.success) {
				handleAjaxError('draft', res, { status: 200, responseJSON: res });
				return;
			}
			loadSaved();
		}).fail(function(xhr){
			handleAjaxError('draft-fail', null, xhr);
		}).always(function(){
			if (window.rllmRefreshQuota) window.rllmRefreshQuota();
			setUILock(false);
		});
	});

	$tbody.on('click', '.f02-fav', function(){
		if (isProcessing) return;

		const $tr = $(this).closest('tr');
		const id = String($tr.data('id') || '');
		if (!id) return;

		const item = state.items.find(it => String(it.id) === id);
		const next = !(item && item.is_fav);

		setUILock(true);

		$.post(ajaxurl, {
			action: 'r_llm_seo_f02_toggle_fav',
			nonce: nonce,
			id: id,
			is_fav: next ? 1 : 0
		}).done(function(res){
			if (!res?.success) {
				handleAjaxError('fav', res, { status: 200, responseJSON: res });
				return;
			}
			loadSaved();
		}).fail(function(xhr){
			handleAjaxError('fav-fail', null, xhr);
		}).always(function(){
			if (window.rllmRefreshQuota) window.rllmRefreshQuota();
			setUILock(false);
		});
	});

	$tbody.on('click', '.f02-del', function(){
		if (isProcessing) return;

		if (!confirm(t('confirm_delete', 'このタイトル案を削除します。よろしいですか？'))) return;

		const $tr = $(this).closest('tr');
		const id = String($tr.data('id') || '');
		if (!id) return;

		setUILock(true);

		$.post(ajaxurl, {
			action: 'r_llm_seo_f02_delete_item',
			nonce: nonce,
			id: id
		}).done(function(res){
			if (!res?.success) {
				handleAjaxError('delete', res, { status: 200, responseJSON: res });
				return;
			}
			loadSaved();
		}).fail(function(xhr){
			handleAjaxError('delete-fail', null, xhr);
		}).always(function(){
			if (window.rllmRefreshQuota) window.rllmRefreshQuota();
			setUILock(false);
		});
	});

	$filterAll.on('click', function(){
		if (isProcessing) return;
		currentFilter = 'all';
		applyFilterToDom();
	});

	$filterFav.on('click', function(){
		if (isProcessing) return;
		currentFilter = 'fav';
		applyFilterToDom();
	});

	$btnDelAll.on('click', function(){
		if (isProcessing) return;
		if (!confirm(t('confirm_delete_all', '保存済みのタイトル案をすべて削除します。よろしいですか？'))) return;

		setUILock(true);

		$.post(ajaxurl, {
			action: 'r_llm_seo_f02_delete_all',
			nonce: nonce
		}).done(function(res){
			if (!res?.success) {
				handleAjaxError('delete-all', res, { status: 200, responseJSON: res });
				return;
			}
			state.items = [];
			$tbody.empty();
			showEmptyRow();
		}).fail(function(xhr){
			handleAjaxError('delete-all-fail', null, xhr);
		}).always(function(){
			if (window.rllmRefreshQuota) window.rllmRefreshQuota();
			setUILock(false);
		});
	});

	function loadSaved() {
		const postType = String($pt.val() || 'post');

		$.post(ajaxurl, {
			action: 'r_llm_seo_f02_list_items',
			nonce: nonce,
			post_type: postType
		}).done(function(res){
			if (!res?.success) {
				console.warn('[F02] loadSaved failed', res);
				return;
			}

			const items = res.data?.items || [];
			state.items = Array.isArray(items) ? items : [];

			const rowsHtml = res.data?.rows_html || '';
			renderFromRowsHtml(rowsHtml);

			applyFilterToDom();

		}).fail(function(xhr){
			console.warn('[F02] loadSaved ajax fail', xhr?.status, xhr?.responseText);
		});
	}

	$pt.on('change', function(){
		if (isProcessing) return;
		loadSaved();
	});

	$btnGen.on('click', function(){
		if (isProcessing) return;

		if (!state.keywords.length) {
			alert(t('keyword_required', 'キーワードを1つ以上追加してください。'));
			return;
		}

		setUILock(true);
		$btnGen.text(t('generating', '生成中...'));

		$.ajax({
			type: 'POST',
			url: ajaxurl,
			dataType: 'json',
			timeout: 120000,
			data: {
				action: 'r_llm_seo_run_ai_title_generate_f02',
				nonce: nonce,
				max_length: 32,
				keywords: state.keywords,
				post_type: String($pt.val() || 'post')
			}
		})
		.done(function(res){
			if (!res?.success) {
				handleAjaxError('generate', res, { status: 200, responseJSON: res });
				return;
			}

			const items = res.data?.items || [];
			state.items = Array.isArray(items) ? items : [];

			const rowsHtml = res.data?.rows_html || '';
			renderFromRowsHtml(rowsHtml);

			applyFilterToDom();

			state.keywords = [];
			renderTags();
			$input.val('');
		})
		.fail(function(xhr){
			handleAjaxError('generate-fail', null, xhr);
		})
		.always(function(){
			if (window.rllmRefreshQuota) window.rllmRefreshQuota();

			setUILock(false);

			cooldownButton($btnGen, 3, t('generate_button', 'タイトル案生成'));
		});
	});

	loadSaved();
});