(function () {
	const el = document.getElementById('r-llm-seo-quota-line');
	if (!el) return;

	const nonce =
		(window.r_llm_seo_vars && window.r_llm_seo_vars.nonce) ? window.r_llm_seo_vars.nonce :
		(window.RLLM_SEO && window.RLLM_SEO.nonce) ? window.RLLM_SEO.nonce :
		'';

	const ajaxUrl =
		(window.r_llm_seo_vars && window.r_llm_seo_vars.ajaxurl) ? window.r_llm_seo_vars.ajaxurl :
		(window.RLLM_SEO && window.RLLM_SEO.ajaxurl) ? window.RLLM_SEO.ajaxurl :
		(window.ajaxurl || '');

	if (!nonce || !ajaxUrl) return;

	let inFlight = false;
	let controller = null;

	async function pollQuota() {
		if (inFlight) return;

		// 背景タブでは無理に叩かない（任意）
		if (typeof document.hidden === 'boolean' && document.hidden) return;

		inFlight = true;

		// 前回が詰まってたら中断
		if (controller) {
			try { controller.abort(); } catch (e) {}
		}
		controller = (window.AbortController ? new AbortController() : null);

		try {
			const params = new URLSearchParams();
			params.set('action', 'r_llm_seo_quota_poll');
			params.set('nonce', nonce);

			const response = await fetch(ajaxUrl, {
				method: 'POST',
				headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
				body: params.toString(),
				credentials: 'same-origin',
				signal: controller ? controller.signal : undefined
			});

			if (!response.ok) return;

			const json = await response.json();

			const line = json && json.success === true && json.data && typeof json.data.line === 'string'
				? json.data.line
				: '';

			if (line !== '' && el.textContent !== line) {
				el.textContent = line;
			}

		} catch (e) {
			// abort は無視
		} finally {
			inFlight = false;
		}
	}

	// 外部（F01/F02/F03...）から呼べるようにする
	window.rllmRefreshQuota = function () {
		pollQuota();
	};

	pollQuota();
	setInterval(pollQuota, 60000);

	// タブ復帰時に即更新（任意）
	document.addEventListener('visibilitychange', function () {
		if (!document.hidden) pollQuota();
	});
})();