/* Customer Cloud Gallery admin scripts */
(function ($) {
	'use strict';

	$(function () {
		if (typeof ccgalAdmin === 'undefined') return;

		// ── Gegenseitiges Ausgrauen der zwei Ordner-Felder ──────────────────
		function updateFolderState() {
			var driveVal   = $('#ccgal_drive_folder_id').val().trim();
			var dropboxVal = $('#ccgal_dropbox_folder_id').val().trim();
			var driveRow   = $('#ccgal-folder-row-drive');
			var dropboxRow = $('#ccgal-folder-row-dropbox');

			if ( driveVal && !dropboxVal ) {
				// Drive aktiv → Dropbox ausgrauen
				dropboxRow.css('opacity', '0.45');
				$('#ccgal_dropbox_folder_id').prop('disabled', true);
				driveRow.css('opacity', '1');
				$('#ccgal_drive_folder_id').prop('disabled', false);
			} else if ( dropboxVal && !driveVal ) {
				// Dropbox aktiv → Drive ausgrauen
				driveRow.css('opacity', '0.45');
				$('#ccgal_drive_folder_id').prop('disabled', true);
				dropboxRow.css('opacity', '1');
				$('#ccgal_dropbox_folder_id').prop('disabled', false);
			} else {
				// Beide leer → beide aktiv (Connection-Status bleibt via PHP-disabled)
				driveRow.css('opacity',   ccgalAdmin.driveConnected   ? '1' : '0.45');
				dropboxRow.css('opacity', ccgalAdmin.dropboxConnected ? '1' : '0.45');
				if ( ccgalAdmin.driveConnected )   $('#ccgal_drive_folder_id').prop('disabled', false);
				if ( ccgalAdmin.dropboxConnected ) $('#ccgal_dropbox_folder_id').prop('disabled', false);
			}
		}

		$('.ccgal-folder-input').on('input', function () {
			updateFolderState();
		});

		// ── Ordner-Validierung ───────────────────────────────────────────────
		var timers = {};

		function validate($input, provider) {
			var val = ($input.val() || '').trim();
			var $td = $input.closest('td');
			var statusId = 'ccgal_folder_status_' + provider;
			var $status = $('#' + statusId);
			if (!$status.length) {
				$status = $('<p id="' + statusId + '" class="description" style="margin-top:4px;min-height:1.4em;"></p>');
				$input.closest('div').after($status);
			}

			if (!val) { $status.html(''); return; }

			$status.html('<span style="color:#888;">' + ccgalAdmin.i18n.checking + '</span>');

			$.post(ajaxurl, {
				action:   'ccgal_validate_folder',
				nonce:    ccgalAdmin.validateNonce,
				folder:   val,
				provider: provider,
			})
			.done(function (r) {
				if (r && r.success) {
					$input.val(r.data.folder_id);
					$status.html(
						'<span style="color:#1a7e3a;">&#10003; ' +
						$('<span/>').text(r.data.name).html() +
						'</span>'
					);
				} else {
					var msg = (r && r.data && r.data.message) ? r.data.message : ccgalAdmin.i18n.error;
					$status.html('<span style="color:#b00020;">&#10007; ' + $('<span/>').text(msg).html() + '</span>');
				}
			})
			.fail(function () {
				$status.html('<span style="color:#b00020;">' + ccgalAdmin.i18n.error + '</span>');
			});
		}

		$('.ccgal-check-folder').on('click', function () {
			var provider = $(this).data('provider');
			var $input   = $(this).closest('div').find('.ccgal-folder-input');

			if ( $input.prop('disabled') ) {
				// Feld ist ausgegraut weil der andere Anbieter aktiv ist
				var otherProvider = provider === 'google_drive' ? 'dropbox' : 'google_drive';
				var statusId = 'ccgal_folder_status_' + provider;
				var $status  = $('#' + statusId);
				if (!$status.length) {
					$status = $('<p id="' + statusId + '" class="description" style="margin-top:4px;min-height:1.4em;"></p>');
					$input.closest('div').after($status);
				}
				var otherLabel = provider === 'google_drive' ? 'Dropbox' : 'Google Drive';
				var tpl = (window.ccgalAdmin && ccgalAdmin.i18n && ccgalAdmin.i18n.clearOther) || 'Clear the %s field first (✕), then enter here.';
				$status.html('<span style="color:#888;">' + tpl.replace('%s', otherLabel) + '</span>');
				return;
			}

			validate($input, provider);
		});

		$('.ccgal-folder-input').on('input', function () {
			var provider = $(this).data('provider');
			var $input   = $(this);
			updateClearButton($input);
			clearTimeout(timers[provider]);
			timers[provider] = setTimeout(function () { validate($input, provider); }, 700);
		});

		// ── Clear-Button (dynamisch ein-/ausblenden) ─────────────────────────
		function updateClearButton($input) {
			var id       = $input.attr('id');
			var $row     = $input.closest('[id^="ccgal-folder-row-"]');
			var $existing = $row.find('.ccgal-clear-folder');
			if ($input.val().trim()) {
				if (!$existing.length) {
					var $btn = $('<button type="button" class="button ccgal-clear-folder">✕</button>');
					$btn.attr('data-target', id);
					$input.after($btn);
				}
			} else {
				$existing.remove();
			}
		}

		$(document).on('click', '.ccgal-clear-folder', function () {
			var target   = $(this).data('target');
			var provider = $('#' + target).data('provider');
			$('#' + target).val('');
			$('#ccgal_folder_status_' + provider).html('');
			$(this).remove();
			updateFolderState();
		});

		// ── Initialzustand setzen ────────────────────────────────────────────
		$('.ccgal-folder-input').each(function () {
			updateClearButton($(this));
		});
		updateFolderState();

		// Validierung beim Laden wenn Felder bereits befüllt
		$('.ccgal-folder-input').each(function () {
			var $input   = $(this);
			var provider = $input.data('provider');
			if ($input.val().trim() && !$input.prop('disabled')) {
				validate($input, provider);
			}
		});
	});

}(jQuery));
