const selectedState={device:null};
const runtimeLogs=document.getElementById?.('logs');
let collectedErrors=[];
function now(){return new Date().toLocaleTimeString();}
function appendLog(message){const box=document.getElementById('systemLog');if(!box)return;box.innerText+=`${box.innerText?'\n':''}[${now()}] ${message}`;box.scrollTop=box.scrollHeight;}
function appendRuntimeLog(message){const box=document.getElementById('logs');if(!box)return;box.innerText+=`${box.innerText?'\n':''}[${now()}] ${message}`;box.scrollTop=box.scrollHeight;collectErrors(message);}
function collectErrors(message){if(/error|failed|exception|fatal|❌/i.test(message)){if(!collectedErrors.includes(message)){collectedErrors.push(message);}renderErrors();}}
function renderErrors(){const box=document.getElementById('errorsBox');const count=document.getElementById('errorCount');if(!box||!count)return;box.innerText=collectedErrors.length?collectedErrors.join('\n'):'Здесь появятся ошибки из Flutter, Gradle, ADB, API и stderr.';count.innerText=collectedErrors.length?`Ошибок: ${collectedErrors.length}`:'Ошибок пока нет';}
function clearRuntimeOutput(){const box=document.getElementById('logs');if(box)box.innerText='';collectedErrors=[];renderErrors();}
async function workspaceApi(url,payload={},method='POST'){appendLog(`API запрос: ${url}`);const response=await fetch(url,{method,headers:{'Content-Type':'application/json'},body:method==='GET'?undefined:JSON.stringify(payload)});return await response.json();}
function getWorkspacePath(){return document.getElementById('workspacePath')?.value?.trim()||'';}
function getSelectedDevice(){return selectedState.device;}
function selectDevice(serial){selectedState.device=serial;document.querySelectorAll('.device-card').forEach(card=>card.classList.toggle('selected',card.dataset.serial===serial));appendLog(`📱 Выбрано устройство: ${serial}`);}
function setStatus(message,state='idle'){const el=document.getElementById('runtimeStatus');if(el)el.innerText=message;const dot=document.getElementById('runtimeStatusDot');if(dot)dot.className=`status-dot ${state}`;}
async function loadDevices(){const data=await workspaceApi('/api/android/devices');const container=document.getElementById('devices');if(!container)return;const devices=data.devices||[];container.innerHTML=devices.map(device=>`
`;}).join('');}
async function loadApkArtifacts(verbose=true){const workspace=getWorkspacePath();const box=document.getElementById('apkArtifactsList');if(!workspace){if(box)box.innerHTML='
Сначала выбери проект.
';return;}const data=await workspaceApi(`/api/android/apks?workspace=${encodeURIComponent(workspace)}`,{},'GET');renderApkArtifacts(data.apks||[],data.directory||'');}
async function runRuntimeScenario(type){appendLog(`▶ Runtime scenario: ${type}`);}
async function installLatestApk(){appendLog('▶ Install latest APK');}
async function restartCurrentApp(){appendLog('▶ Restart app');}
async function stopRuntimeCommand(){appendLog('🛑 Runtime stop requested');}
function copyErrorsForAI(){navigator.clipboard.writeText(collectedErrors.join('\n'));appendLog('Ошибки скопированы');}
function clearErrors(){collectedErrors=[];renderErrors();appendLog('Ошибки очищены');}
function openAddProjectModal(){document.getElementById('addProjectModal').style.display='flex';}
function closeAddProjectModal(){document.getElementById('addProjectModal').style.display='none';}
function openEditProjectModal(){document.getElementById('editProjectModal').style.display='flex';}
function closeEditProjectModal(){document.getElementById('editProjectModal').style.display='none';}
function toggleAuthFields(){}
function toggleOtaFields(){}
async function syncPubspecVersion(){appendLog('📦 Читаю pubspec.yaml');}
async function saveProjectSettings(){appendLog('✅ Настройки проекта сохранены');closeEditProjectModal();}
async function analyzeProject(){appendLog('📦 Анализ проекта');}
window.addEventListener('load',()=>{appendLog('DevConsole runtime initialized...');loadDevices();loadProjects();loadApkArtifacts(false);setStatus('DevConsole workspace runtime готов','done');});