<%@ page contentType="text/html; charset=UTF-8"%>
<%@ include file="/WEB-INF/jspf/taglibs.jsp"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>

<style>
.getolt-container {
	padding: 10px;
}
.getolt-error {
	color: #dc3545;
	padding: 20px;
	text-align: center;
	font-size: 14px;
}
.getolt-info {
	color: #6c757d;
	padding: 20px;
	text-align: center;
	font-size: 14px;
}
.onu-card {
	border: 1px solid #ddd;
	border-radius: 4px;
	margin-bottom: 15px;
	background: #fff;
}
.onu-header {
	background: #f8f9fa;
	padding: 10px 15px;
	border-bottom: 1px solid #ddd;
	display: flex;
	justify-content: space-between;
	align-items: center;
}
.onu-header-left {
	display: flex;
	flex-direction: column;
	gap: 2px;
}
.onu-header .mac {
	font-family: monospace;
	font-weight: bold;
	font-size: 14px;
}
.onu-header-left .onu-update-time {
	font-size: 11px;
	color: #6c757d;
}
.onu-header-right {
	display: flex;
	align-items: center;
	gap: 12px;
}
.onu-update-time {
	font-size: 11px;
	color: #6c757d;
	cursor: help;
}
.onu-status {
	padding: 3px 10px;
	border-radius: 12px;
	font-size: 12px;
	font-weight: bold;
}
.onu-status.online {
	background: #d4edda;
	color: #155724;
}
.onu-status.offline {
	background: #f8d7da;
	color: #721c24;
}
.onu-body {
	padding: 15px;
}
.onu-row {
	display: flex;
	flex-wrap: wrap;
	margin: 0 -10px;
}
.onu-col {
	flex: 0 0 50%;
	padding: 0 10px;
	margin-bottom: 10px;
}
.onu-col.full {
	flex: 0 0 100%;
}
.onu-label {
	font-size: 11px;
	color: #6c757d;
	margin-bottom: 2px;
}
.onu-value {
	font-size: 13px;
	font-weight: 500;
}
.signal-good {
	color: #28a745;
}
.signal-medium {
	color: #e6a000;
}
.signal-poor {
	color: #dc3545;
}
.signal-overexposed {
	color: #fd7e14;
}
.macs-list {
	font-family: monospace;
	font-size: 12px;
	max-height: 100px;
	overflow-y: auto;
	background: #f8f9fa;
	padding: 8px;
	border-radius: 4px;
}
.macs-list .mac-item {
	margin-bottom: 2px;
}
.neighbors-table {
	width: 100%;
	font-size: 12px;
	border-collapse: collapse;
}
.neighbors-table th,
.neighbors-table td {
	padding: 6px 8px;
	text-align: left;
	border-bottom: 1px solid #eee;
}
.neighbors-table th {
	background: #f8f9fa;
	font-weight: 600;
}
.neighbors-table .mac {
	font-family: monospace;
}
.contract-info {
	background: #e7f1ff;
	padding: 8px 12px;
	border-radius: 4px;
	margin-bottom: 15px;
	font-size: 13px;
}
.contract-info span {
	margin-right: 20px;
}
.neighbors-table .target-row {
	background: #e9ecef;
	font-weight: 600;
}
.neighbors-table .target-row td {
	border-bottom: 2px solid #6c757d;
}
/* Signal-based row highlighting for neighbors */
.neighbors-table .signal-row-poor {
	background: #f8d7da;
}
.neighbors-table .signal-row-medium {
	background: #fff3cd;
}
.neighbors-table .signal-row-overexposed {
	background: #ffe5d0;
}
/* Refresh button styles */
.btn-refresh {
	background: #007bff;
	color: #fff;
	border: none;
	padding: 5px 12px;
	border-radius: 4px;
	font-size: 12px;
	cursor: pointer;
	transition: background 0.2s;
}
.btn-refresh:hover {
	background: #0056b3;
}
.btn-refresh:disabled {
	background: #6c757d;
	cursor: not-allowed;
}
.btn-refresh .btn-port-num {
	background: rgba(255,255,255,0.3);
	padding: 2px 6px;
	border-radius: 3px;
	font-weight: bold;
	margin-left: 4px;
	display: inline-block;
	vertical-align: middle;
	line-height: 1;
}
/* Refresh status bar */
.refresh-status-bar {
	background: #e7f1ff;
	padding: 10px 15px;
	border-radius: 0 0 4px 4px;
	display: none;
	align-items: center;
	gap: 10px;
	border-top: 1px solid #b8daff;
}
.refresh-status-bar.active {
	display: flex;
}
.refresh-status-bar .spinner {
	width: 16px;
	height: 16px;
	border: 2px solid #007bff;
	border-top-color: transparent;
	border-radius: 50%;
	animation: spin 1s linear infinite;
}
@keyframes spin {
	to { transform: rotate(360deg); }
}
.refresh-status-bar .status-text {
	flex: 1;
	font-size: 13px;
	color: #004085;
}
.refresh-status-bar.success {
	background: #d4edda;
	border-top-color: #c3e6cb;
}
.refresh-status-bar.success .status-text {
	color: #155724;
}
.refresh-status-bar.error {
	background: #f8d7da;
	border-top-color: #f5c6cb;
}
.refresh-status-bar.error .status-text {
	color: #721c24;
}
/* Reboot button styles */
.btn-reboot {
	background: #dc3545;
	color: #fff;
	border: none;
	padding: 5px 12px;
	border-radius: 4px;
	font-size: 12px;
	cursor: pointer;
	transition: background 0.2s;
}
.btn-reboot:hover:not(:disabled) {
	background: #c82333;
}
.btn-reboot:disabled {
	background: #6c757d;
	cursor: not-allowed;
}
.btn-reboot.cooldown {
	background: #adb5bd;
	color: #495057;
	min-width: 120px;
}
/* Activation form styles */
.activation-section {
	background: #f8f9fa;
	border: 1px solid #dee2e6;
	border-radius: 4px;
	padding: 15px;
	margin-bottom: 15px;
}
.activation-section h4 {
	margin: 0 0 10px 0;
	font-size: 14px;
	font-weight: 600;
	color: #495057;
}
.activation-form {
	display: flex;
	gap: 10px;
	align-items: flex-end;
	flex-wrap: wrap;
}
.activation-form .form-group {
	flex: 1;
	min-width: 200px;
}
.activation-form label {
	display: block;
	font-size: 12px;
	color: #6c757d;
	margin-bottom: 4px;
}
.activation-form input[type="text"] {
	width: 100%;
	padding: 8px 12px;
	border: 1px solid #ced4da;
	border-radius: 4px;
	font-family: monospace;
	font-size: 14px;
	text-transform: uppercase;
}
.activation-form input[type="text"]:focus {
	border-color: #80bdff;
	outline: none;
	box-shadow: 0 0 0 0.2rem rgba(0,123,255,.25);
}
.activation-form input[type="text"].is-invalid {
	border-color: #dc3545;
}
.btn-activate {
	background: #28a745;
	color: #fff;
	border: none;
	padding: 8px 20px;
	border-radius: 4px;
	font-size: 14px;
	cursor: pointer;
	transition: background 0.2s;
	white-space: nowrap;
}
.btn-activate:hover:not(:disabled) {
	background: #218838;
}
.btn-activate:disabled {
	background: #6c757d;
	cursor: not-allowed;
}
.activation-status {
	width: 100%;
	padding: 10px;
	border-radius: 4px;
	font-size: 13px;
	margin-top: 10px;
	display: none;
}
.activation-status.active {
	display: block;
}
.activation-status.success {
	background: #d4edda;
	color: #155724;
	border: 1px solid #c3e6cb;
}
.activation-status.error {
	background: #f8d7da;
	color: #721c24;
	border: 1px solid #f5c6cb;
}
.activation-status.processing {
	background: #e7f1ff;
	color: #004085;
	border: 1px solid #b8daff;
}
/* Service selection modal */
.service-modal-overlay {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background: rgba(0,0,0,0.5);
	display: none;
	justify-content: center;
	align-items: center;
	z-index: 10000;
}
.service-modal-overlay.active {
	display: flex;
}
.service-modal {
	background: #fff;
	border-radius: 8px;
	width: 90%;
	max-width: 500px;
	max-height: 80vh;
	overflow: hidden;
	box-shadow: 0 4px 20px rgba(0,0,0,0.3);
}
.service-modal-header {
	background: #f8f9fa;
	padding: 15px 20px;
	border-bottom: 1px solid #dee2e6;
	display: flex;
	justify-content: space-between;
	align-items: center;
}
.service-modal-header h3 {
	margin: 0;
	font-size: 16px;
}
.service-modal-close {
	background: none;
	border: none;
	font-size: 24px;
	cursor: pointer;
	color: #6c757d;
	line-height: 1;
}
.service-modal-body {
	padding: 20px;
	max-height: 60vh;
	overflow-y: auto;
}
.service-list {
	list-style: none;
	padding: 0;
	margin: 0;
}
.service-list li {
	padding: 12px;
	border: 1px solid #dee2e6;
	border-radius: 4px;
	margin-bottom: 8px;
	cursor: pointer;
	transition: all 0.2s;
}
.service-list li:hover {
	background: #e9ecef;
	border-color: #adb5bd;
}
.service-list li:last-child {
	margin-bottom: 0;
}
.service-list .service-title {
	font-weight: 500;
	margin-bottom: 4px;
}
.service-list .service-mac {
	font-family: monospace;
	font-size: 12px;
	color: #6c757d;
}
</style>

<div class="getolt-container">
	<%-- Error message --%>
	<c:if test="${not empty frd.error}">
		<div class="getolt-error">${frd.error}</div>
	</c:if>

	<%-- Search result --%>
	<c:if test="${not empty frd.searchResult}">
		<%-- Contract info header --%>
		<div class="contract-info">
			<span><strong>Договор:</strong> ${frd.contractNumber}</span>
			<span><strong>CID:</strong> ${frd.cid}</span>
			<span><strong>Оператор:</strong> ${frd.operator}</span>
		</div>

		<%-- Activation form (requires permission) --%>
		<c:if test="${ctxUser.checkPerm('/user/plugin/getolt/getolt:activateOnu')}">
			<div class="activation-section">
				<h4>Активация / Замена ONU</h4>
				<div class="activation-form" id="activation-form">
					<div class="form-group">
						<label for="new-mac-input">MAC-адрес новой ONU</label>
						<input type="text" id="new-mac-input"
							   placeholder="XX:XX:XX:XX:XX:XX"
							   maxlength="17"
							   data-process-id="${form.param.processId}"
							   onkeyup="formatMacInput(this)"
							   onpaste="handleMacPaste(event, this)">
					</div>
					<button type="button" class="btn-activate" id="btn-activate"
							onclick="activateOnu()">
						Активировать
					</button>
				</div>
				<div class="activation-status" id="activation-status"></div>
			</div>

			<%-- Service selection modal --%>
			<div class="service-modal-overlay" id="service-modal">
				<div class="service-modal">
					<div class="service-modal-header">
						<h3>Выберите услугу</h3>
						<button type="button" class="service-modal-close" onclick="closeServiceModal()">&times;</button>
					</div>
					<div class="service-modal-body">
						<p>У договора несколько интернет-услуг. Выберите услугу для замены MAC:</p>
						<ul class="service-list" id="service-list"></ul>
					</div>
				</div>
			</div>
		</c:if>

		<c:choose>
			<c:when test="${frd.searchResult.success and frd.searchResult.hasOnus()}">
				<%-- Loop through ONUs --%>
				<c:forEach var="onu" items="${frd.searchResult.onus}">
					<div class="onu-card">
						<div class="onu-header">
							<div class="onu-header-left">
								<span class="mac">${onu.mac}</span>
								<c:if test="${not empty onu.lastUpdate}">
									<span class="onu-update-time" title="${onu.lastUpdateFormatted}">
										Обновлено: ${onu.lastUpdateAgo}
									</span>
								</c:if>
							</div>
							<div class="onu-header-right">
								<span class="onu-status ${onu.online ? 'online' : 'offline'}">
									${onu.online ? 'ONLINE' : 'OFFLINE'}
								</span>
								<c:if test="${ctxUser.checkPerm('/user/plugin/getolt/getolt:refreshPort')}">
									<c:if test="${not empty onu.oltIp and onu.port > 0}">
										<c:set var="refreshKey" value="${fn:replace(onu.oltIp, '.', '_')}_${onu.port}" />
										<button type="button" class="btn-refresh"
												id="btn-refresh-${refreshKey}"
												data-olt-ip="${onu.oltIp}"
												data-port="${onu.port}"
												data-process-id="${form.param.processId}"
												data-refresh-key="${refreshKey}"
												onclick="startPortRefresh(this)">
											Обновить порт <span class="btn-port-num">${onu.port}</span>
										</button>
									</c:if>
								</c:if>
								<c:if test="${ctxUser.checkPerm('/user/plugin/getolt/getolt:rebootOnu')}">
									<c:if test="${not empty onu.oltId and onu.port > 0 and onu.onuId > 0}">
										<c:set var="rebootKey" value="${onu.oltId}_${onu.port}_${onu.onuId}" />
										<button type="button" class="btn-reboot"
												id="btn-reboot-${rebootKey}"
												data-olt-id="${onu.oltId}"
												data-port="${onu.port}"
												data-onu-id="${onu.onuId}"
												data-mac="${onu.mac}"
												data-process-id="${form.param.processId}"
												data-reboot-key="${rebootKey}"
												onclick="startOnuReboot(this)">
											Перезагрузить ONU
										</button>
									</c:if>
								</c:if>
							</div>
						</div>
						<c:if test="${not empty onu.oltIp and onu.port > 0}">
							<c:set var="refreshKey" value="${fn:replace(onu.oltIp, '.', '_')}_${onu.port}" />
							<div class="refresh-status-bar" id="status-bar-${refreshKey}" style="display:none;">
								<div class="spinner"></div>
								<span class="status-text">Обновление порта...</span>
							</div>
						</c:if>
						<div class="onu-body">
							<div class="onu-row">
								<div class="onu-col">
									<div class="onu-label">OLT IP</div>
									<div class="onu-value">${onu.oltIp}</div>
								</div>
								<div class="onu-col">
									<div class="onu-label">Порт / ONU ID</div>
									<div class="onu-value">${onu.port} / ${onu.onuId}</div>
								</div>
							</div>

							<div class="onu-row">
								<div class="onu-col">
									<div class="onu-label">Сигнал RX</div>
									<div class="onu-value">
										<c:if test="${not empty onu.rxSignal}">
											<span class="${onu.getQualityClass(onu.rxQuality)}">
												${onu.rxSignal} dBm
											</span>
										</c:if>
										<c:if test="${empty onu.rxSignal}">-</c:if>
									</div>
								</div>
								<div class="onu-col">
									<div class="onu-label">Сигнал TX</div>
									<div class="onu-value">
										<c:if test="${not empty onu.txSignal}">
											<span class="${onu.getQualityClass(onu.txQuality)}">
												${onu.txSignal} dBm
											</span>
										</c:if>
										<c:if test="${empty onu.txSignal}">-</c:if>
									</div>
								</div>
							</div>

							<div class="onu-row">
								<div class="onu-col">
									<div class="onu-label">Дистанция</div>
									<div class="onu-value">
										<c:if test="${not empty onu.distance}">${onu.distance} м</c:if>
										<c:if test="${empty onu.distance}">-</c:if>
									</div>
								</div>
								<div class="onu-col">
									<div class="onu-label">Температура</div>
									<div class="onu-value">
										<c:if test="${not empty onu.temperature}">${onu.temperature} °C</c:if>
										<c:if test="${empty onu.temperature}">-</c:if>
									</div>
								</div>
							</div>

							<div class="onu-row">
								<div class="onu-col">
									<div class="onu-label">Напряжение</div>
									<div class="onu-value">
										<c:if test="${not empty onu.voltage}">${onu.voltage} V</c:if>
										<c:if test="${empty onu.voltage}">-</c:if>
									</div>
								</div>
								<div class="onu-col">
									<div class="onu-label">Статус</div>
									<div class="onu-value">${onu.status}</div>
								</div>
							</div>

							<%-- MACs behind ONU --%>
							<c:if test="${not empty onu.macsBehind}">
								<div class="onu-row">
									<div class="onu-col full">
										<div class="onu-label">MAC за ONU (${onu.macsBehind.size()})</div>
										<div class="macs-list">
											<c:forEach var="mac" items="${onu.macsBehind}">
												<div class="mac-item">${mac}</div>
											</c:forEach>
										</div>
									</div>
								</div>
							</c:if>

							<%-- Port neighbors --%>
							<c:if test="${not empty onu.neighbors}">
								<div class="onu-row">
									<div class="onu-col full">
										<div class="onu-label">Соседи по порту</div>
										<table class="neighbors-table">
											<thead>
												<tr>
													<th>MAC</th>
													<th>ONU ID</th>
													<th>RX (dBm)</th>
													<th>Статус</th>
													<th>Договор</th>
													<th>Обновлено</th>
												</tr>
											</thead>
											<tbody>
												<c:forEach var="neighbor" items="${onu.neighbors}">
													<tr class="${neighbor.contractNumber eq frd.contractNumber ? 'target-row' : neighbor.rowClass}">
														<td class="mac">${neighbor.mac}</td>
														<td>${neighbor.onuId}</td>
														<td><c:if test="${not empty neighbor.rxOptical}">${neighbor.rxOptical}</c:if><c:if test="${empty neighbor.rxOptical}">-</c:if></td>
														<td>${neighbor.status}</td>
														<td>${neighbor.contractNumber}</td>
														<td class="update-time" title="${neighbor.lastUpdateFormatted}"><c:if test="${not empty neighbor.lastUpdateAgo}">${neighbor.lastUpdateAgo}</c:if><c:if test="${empty neighbor.lastUpdateAgo}">-</c:if></td>
													</tr>
												</c:forEach>
											</tbody>
										</table>
									</div>
								</div>
							</c:if>
						</div>
					</div>
				</c:forEach>
			</c:when>
			<c:otherwise>
				<div class="getolt-info">${frd.searchResult.errorMessage}</div>
			</c:otherwise>
		</c:choose>
	</c:if>
</div>

<script>
(function() {
	var refreshPollingIntervals = {};
	var REBOOT_COOLDOWN = 5 * 60 * 1000; // 5 minutes in ms
	var rebootTimers = {};

	// Initialize reboot buttons on page load
	function initRebootButtons() {
		var buttons = document.querySelectorAll('.btn-reboot');
		buttons.forEach(function(btn) {
			checkRebootCooldown(btn);
		});
	}

	// Check and apply cooldown for a reboot button
	function checkRebootCooldown(btn) {
		var key = btn.getAttribute('data-reboot-key');
		var storageKey = 'getolt_reboot_' + key;
		var lastReboot = localStorage.getItem(storageKey);

		if (lastReboot) {
			var lastTime = parseInt(lastReboot, 10);
			var now = Date.now();
			var elapsed = now - lastTime;
			var remaining = REBOOT_COOLDOWN - elapsed;

			if (remaining > 0) {
				setRebootCooldown(btn, remaining);
			} else {
				localStorage.removeItem(storageKey);
			}
		}
	}

	// Set button to cooldown state
	function setRebootCooldown(btn, remainingMs) {
		var key = btn.getAttribute('data-reboot-key');
		btn.disabled = true;
		btn.classList.add('cooldown');
		updateRebootTooltip(btn, remainingMs);

		// Clear existing timer
		if (rebootTimers[key]) {
			clearInterval(rebootTimers[key]);
		}

		// Update every second
		rebootTimers[key] = setInterval(function() {
			remainingMs -= 1000;
			if (remainingMs <= 0) {
				clearInterval(rebootTimers[key]);
				delete rebootTimers[key];
				btn.disabled = false;
				btn.classList.remove('cooldown');
				btn.textContent = 'Перезагрузить ONU';
				btn.title = '';
				localStorage.removeItem('getolt_reboot_' + key);
			} else {
				updateRebootTooltip(btn, remainingMs);
			}
		}, 1000);
	}

	// Update button text and tooltip with remaining time
	function updateRebootTooltip(btn, remainingMs) {
		var mins = Math.floor(remainingMs / 60000);
		var secs = Math.floor((remainingMs % 60000) / 1000);
		var timeStr = mins + ':' + (secs < 10 ? '0' : '') + secs;
		btn.textContent = 'Ожидание ' + timeStr;
		btn.title = 'Повторная перезагрузка возможна через ' + mins + ' мин. ' + secs + ' сек.';
	}

	window.startOnuReboot = function(btn) {
		var oltId = btn.getAttribute('data-olt-id');
		var port = btn.getAttribute('data-port');
		var onuId = btn.getAttribute('data-onu-id');
		var mac = btn.getAttribute('data-mac') || '';
		var processId = btn.getAttribute('data-process-id') || '';
		var key = btn.getAttribute('data-reboot-key');

		if (!confirm('Вы уверены, что хотите перезагрузить ONU ' + port + ':' + onuId + '?')) {
			return;
		}

		btn.disabled = true;
		btn.textContent = 'Перезагрузка...';
		console.log('GetOLT: Starting reboot for oltId', oltId, 'port', port, 'onuId', onuId, 'processId', processId);

		var url = '/user/plugin/getolt/getolt.do?method=rebootOnu&oltId=' + oltId + '&port=' + port + '&onuId=' + onuId;
		if (processId) url += '&processId=' + processId;
		if (mac) url += '&mac=' + encodeURIComponent(mac);
		$$.ajax.post(url, {})
			.done(function(response) {
				console.log('GetOLT: Reboot response', response);
				var result = response.data && response.data.data ? response.data.data : response.data;
				console.log('GetOLT: reboot result =', result);
				if (response.status === 'ok' && result && result.success) {
					// Save reboot time to localStorage
					localStorage.setItem('getolt_reboot_' + key, Date.now().toString());

					btn.textContent = 'Перезагружена!';
					btn.style.background = '#28a745';
					setTimeout(function() {
						btn.style.background = '';
						// Start cooldown
						setRebootCooldown(btn, REBOOT_COOLDOWN);
					}, 2000);
				} else {
					var msg = (result && result.message) ? result.message : (response.message || 'Ошибка перезагрузки');
					console.log('GetOLT: Reboot error', msg);

					// Check if rate limited - extract remaining time from message
					if (msg.indexOf('Подождите') !== -1) {
						// Parse "Подождите X мин. Y сек." from message
						var match = msg.match(/(\d+)\s*мин\.\s*(\d+)\s*сек/);
						if (match) {
							var mins = parseInt(match[1], 10);
							var secs = parseInt(match[2], 10);
							var remainingMs = (mins * 60 + secs) * 1000;
							localStorage.setItem('getolt_reboot_' + key, (Date.now() - REBOOT_COOLDOWN + remainingMs).toString());
							setRebootCooldown(btn, remainingMs);
						} else {
							alert('Ошибка: ' + msg);
							btn.disabled = false;
							btn.textContent = 'Перезагрузить ONU';
						}
					} else {
						alert('Ошибка: ' + msg);
						btn.disabled = false;
						btn.textContent = 'Перезагрузить ONU';
					}
				}
			})
			.fail(function(xhr, status, error) {
				console.log('GetOLT: Reboot AJAX fail', status, error);
				alert('Ошибка соединения с сервером');
				btn.disabled = false;
				btn.textContent = 'Перезагрузить ONU';
			});
	};

	// Initialize on DOM ready
	if (document.readyState === 'loading') {
		document.addEventListener('DOMContentLoaded', initRebootButtons);
	} else {
		initRebootButtons();
	}

	window.startPortRefresh = function(btn) {
		var oltIp = btn.getAttribute('data-olt-ip');
		var port = btn.getAttribute('data-port');
		var processId = btn.getAttribute('data-process-id') || '';
		var key = btn.getAttribute('data-refresh-key');
		var statusBar = document.getElementById('status-bar-' + key);

		if (!statusBar) return;

		btn.disabled = true;
		statusBar.style.display = 'flex';
		statusBar.className = 'refresh-status-bar active';
		statusBar.querySelector('.status-text').textContent = 'Запуск обновления...';
		console.log('GetOLT: Starting refresh for', oltIp, 'port', port, 'key', key, 'processId', processId);

		var url = '/user/plugin/getolt/getolt.do?method=refreshPort&oltIp=' + encodeURIComponent(oltIp) + '&portNumber=' + port;
		if (processId) url += '&processId=' + processId;
		$$.ajax.post(url, {})
			.done(function(response) {
				console.log('GetOLT: Response', response);
				// BGERP returns {status: 'ok', data: {data: {...}}} format
				var result = response.data && response.data.data ? response.data.data : response.data;
				console.log('GetOLT: result =', result);
				if (response.status === 'ok' && result && result.success) {
					statusBar.querySelector('.status-text').textContent = 'Обновление завершено!';
					statusBar.className = 'refresh-status-bar active success';
					statusBar.querySelector('.spinner').style.display = 'none';
					setTimeout(function() { reloadTab(btn); }, 1500);
				} else {
					var msg = (result && result.message) ? result.message : (response.message || 'Ошибка запуска');
					console.log('GetOLT: Error', msg);
					showError(btn, statusBar, msg);
				}
			})
			.fail(function(xhr, status, error) {
				console.log('GetOLT: AJAX fail', status, error);
				showError(btn, statusBar, 'Ошибка соединения с сервером');
			});
	};

	function startPolling(oltIp, port, btn, statusBar, key) {

		if (refreshPollingIntervals[key]) {
			clearInterval(refreshPollingIntervals[key]);
		}

		refreshPollingIntervals[key] = setInterval(function() {
			$$.ajax.post('/user/plugin/getolt/getolt.do?method=refreshStatus&oltIp=' + encodeURIComponent(oltIp), {})
				.done(function(response) {
					console.log('GetOLT: Status response', response);
					if (response.status === 'ok' && response.data) {
						var status = response.data.status;
						if (status === 'completed' || status === 'idle') {
							stopPolling(key);
							statusBar.style.display = 'flex';
							statusBar.className = 'refresh-status-bar active success';
							statusBar.querySelector('.spinner').style.display = 'none';
							statusBar.querySelector('.status-text').textContent = 'Обновление завершено!';
							setTimeout(function() { reloadTab(btn); }, 1500);
						} else {
							statusBar.querySelector('.status-text').textContent = 'Обновление в процессе...';
						}
					}
				})
				.fail(function() {
					// Continue polling on network errors
				});
		}, 3000);
	}

	function stopPolling(key) {
		if (refreshPollingIntervals[key]) {
			clearInterval(refreshPollingIntervals[key]);
			delete refreshPollingIntervals[key];
		}
	}

	function showError(btn, statusBar, message) {
		btn.disabled = false;
		statusBar.style.display = 'flex';
		statusBar.className = 'refresh-status-bar active error';
		statusBar.querySelector('.spinner').style.display = 'none';
		statusBar.querySelector('.status-text').textContent = message;
		setTimeout(function() {
			statusBar.style.display = 'none';
			statusBar.className = 'refresh-status-bar';
			statusBar.querySelector('.spinner').style.display = '';
		}, 5000);
	}

	function reloadTab(btn) {
		var tabContent = $(btn).closest('.ui-tabs-panel');
		if (tabContent.length) {
			var tabs = tabContent.closest('.ui-tabs');
			var tabIndex = tabs.find('.ui-tabs-panel').index(tabContent);
			var tabLink = tabs.find('.ui-tabs-nav li').eq(tabIndex).find('a');
			if (tabLink.length && tabLink.attr('href')) {
				$$.ajax.load(tabLink.attr('href'), tabContent);
			}
		}
	}

	// ========== ONU Activation Functions ==========

	var pendingMac = '';  // Store MAC for multi-service selection

	// Check for cyrillic letters that look like latin (A, B, C, E)
	function hasCyrillicLookalikes(mac) {
		return /[\u0410\u0412\u0421\u0415\u0430\u0432\u0441\u0435]/.test(mac);
	}

	// Format MAC address input with colons
	window.formatMacInput = function(input, e) {
		var cursorPos = input.selectionStart;
		var oldValue = input.value;

		// Check for cyrillic lookalikes and warn
		if (hasCyrillicLookalikes(oldValue)) {
			input.classList.add('is-invalid');
			var status = document.getElementById('activation-status');
			if (status) {
				status.textContent = 'Кириллица! Переключите раскладку на EN';
				status.className = 'activation-status active error';
			}
		} else {
			input.classList.remove('is-invalid');
			var status = document.getElementById('activation-status');
			if (status && status.textContent.indexOf('Кириллица') !== -1) {
				status.className = 'activation-status';
			}
		}

		// Extract only hex digits
		var hex = oldValue.replace(/[^0-9A-Fa-f]/g, '').toUpperCase().substring(0, 12);

		// Format with colons
		var formatted = '';
		for (var i = 0; i < hex.length; i++) {
			if (i > 0 && i % 2 === 0) {
				formatted += ':';
			}
			formatted += hex[i];
		}

		// Only update if changed
		if (input.value !== formatted) {
			input.value = formatted;

			// Adjust cursor position
			var newPos = cursorPos;
			// Count colons before cursor in old vs new
			var oldColons = (oldValue.substring(0, cursorPos).match(/:/g) || []).length;
			var newColons = (formatted.substring(0, Math.min(cursorPos, formatted.length)).match(/:/g) || []).length;
			newPos += (newColons - oldColons);

			// If we just typed a char that caused a colon to be added, move past it
			if (formatted.length > oldValue.length && formatted[cursorPos] === ':') {
				newPos++;
			}

			input.setSelectionRange(newPos, newPos);
		}
	};

	// Handle paste event for MAC address
	window.handleMacPaste = function(event, input) {
		event.preventDefault();
		var pasted = (event.clipboardData || window.clipboardData).getData('text');
		// Clean and format pasted MAC
		var clean = pasted.replace(/[^0-9A-Fa-f]/g, '').toUpperCase().substring(0, 12);
		var formatted = '';
		for (var i = 0; i < clean.length; i++) {
			if (i > 0 && i % 2 === 0) {
				formatted += ':';
			}
			formatted += clean[i];
		}
		input.value = formatted;
	};

	// Validate MAC format - accepts various formats and normalizes
	function isValidMac(mac) {
		// Remove all separators (colons, dashes, dots, spaces)
		var clean = mac.replace(/[:\-.\s]/g, '');
		// Check for exactly 12 hex digits (rejects cyrillic lookalikes)
		return /^[0-9A-Fa-f]{12}$/.test(clean);
	}

	// Normalize MAC to XX:XX:XX:XX:XX:XX format
	function normalizeMac(mac) {
		var clean = mac.replace(/[^0-9A-Fa-f]/g, '').toUpperCase();
		if (clean.length !== 12) return mac;
		return clean.match(/.{2}/g).join(':');
	}

	// Show activation status
	function showActivationStatus(message, type) {
		var status = document.getElementById('activation-status');
		status.textContent = message;
		status.className = 'activation-status active ' + type;
	}

	// Hide activation status
	function hideActivationStatus() {
		var status = document.getElementById('activation-status');
		status.className = 'activation-status';
	}

	// Main activation function
	window.activateOnu = function(serviceId) {
		var input = document.getElementById('new-mac-input');
		var btn = document.getElementById('btn-activate');
		var mac = input.value.trim();

		// If serviceId provided, use pending MAC
		if (serviceId) {
			mac = pendingMac;
		}

		// Check for cyrillic lookalikes first (common mistake with RU keyboard)
		if (hasCyrillicLookalikes(mac)) {
			input.classList.add('is-invalid');
			showActivationStatus('MAC содержит кириллицу. Переключите на английскую раскладку.', 'error');
			return;
		}

		// Validate MAC
		if (!isValidMac(mac)) {
			input.classList.add('is-invalid');
			showActivationStatus('Невалидный формат MAC. Используйте XX:XX:XX:XX:XX:XX', 'error');
			return;
		}
		input.classList.remove('is-invalid');

		// Normalize MAC to standard format for API
		mac = normalizeMac(mac);

		var processId = input.getAttribute('data-process-id');
		if (!processId) {
			showActivationStatus('Не найден ID процесса', 'error');
			return;
		}

		// Disable button and show processing
		btn.disabled = true;
		btn.textContent = 'Обработка...';
		showActivationStatus('Отправка запроса...', 'processing');

		// Build URL
		var url = '/user/plugin/getolt/getolt.do?method=activateOnu&processId=' + processId +
				  '&newMac=' + encodeURIComponent(mac);
		if (serviceId) {
			url += '&serviceId=' + serviceId;
		}

		console.log('GetOLT: Activating ONU', url);

		$$.ajax.post(url, {})
			.done(function(response) {
				console.log('GetOLT: Activation response', response);
				var result = response.data && response.data.data ? response.data.data : response.data;

				if (response.status === 'ok' && result && result.success) {
					// Success
					var msg = 'MAC обновлён: ' + (result.oldMac || '-') + ' -> ' + result.newMac;
					if (result.sessionDropped) {
						msg += '\nСессия сброшена.';
					}
					showActivationStatus(msg, 'success');
					input.value = '';
					pendingMac = '';
					closeServiceModal();

					// Reload tab after delay
					setTimeout(function() {
						reloadTab(btn);
					}, 2000);

				} else if (result && result.status === 'MULTIPLE_SERVICES') {
					// Multiple services - show selection modal
					pendingMac = mac;
					showServiceModal(result.services);
					hideActivationStatus();

				} else {
					// Error
					var errorMsg = (result && result.message) ? result.message : (response.message || 'Ошибка активации');
					showActivationStatus(errorMsg, 'error');
				}

				btn.disabled = false;
				btn.textContent = 'Активировать';
			})
			.fail(function(xhr, status, error) {
				console.log('GetOLT: Activation AJAX fail', status, error);
				showActivationStatus('Ошибка соединения с сервером', 'error');
				btn.disabled = false;
				btn.textContent = 'Активировать';
			});
	};

	// Show service selection modal
	function showServiceModal(services) {
		var modal = document.getElementById('service-modal');
		var list = document.getElementById('service-list');

		// Clear and populate list
		list.innerHTML = '';
		services.forEach(function(svc) {
			var li = document.createElement('li');
			li.setAttribute('data-service-id', svc.serviceId);
			li.onclick = function() {
				selectService(svc.serviceId);
			};

			var title = document.createElement('div');
			title.className = 'service-title';
			title.textContent = svc.displayTitle || svc.login || ('Услуга #' + svc.serviceId);
			li.appendChild(title);

			if (svc.mac) {
				var macDiv = document.createElement('div');
				macDiv.className = 'service-mac';
				macDiv.textContent = 'Текущий MAC: ' + svc.mac;
				li.appendChild(macDiv);
			}

			list.appendChild(li);
		});

		modal.classList.add('active');
	}

	// Close service selection modal
	window.closeServiceModal = function() {
		var modal = document.getElementById('service-modal');
		modal.classList.remove('active');
	};

	// Select service and activate
	function selectService(serviceId) {
		closeServiceModal();
		activateOnu(serviceId);
	}

	// Close modal on overlay click
	document.addEventListener('click', function(e) {
		if (e.target.id === 'service-modal') {
			closeServiceModal();
		}
	});

	// Close modal on Escape key
	document.addEventListener('keydown', function(e) {
		if (e.key === 'Escape') {
			closeServiceModal();
		}
	});
})();
</script>
