// FILE: _St/IG_StYellow/test_ext_side_simplify_account_open_v299.js | ROLE: Side 단순화·통계 제목·계정 목록 더블클릭 회귀
const assert = require('assert');
const fs = require('fs');
const path = require('path');
const vm = require('vm');

const root = __dirname;
const side = fs.readFileSync(path.join(root, 'side.js'), 'utf8');
const html = fs.readFileSync(path.join(root, 'side.html'), 'utf8');
const autoPy = fs.readFileSync(path.join(root, '..', 'Auto8700', 'auto_service8700_manager.py'), 'utf8');
const autoCfg = fs.readFileSync(path.join(root, '..', 'Auto8700', 'auto_service8700_manager.json'), 'utf8');
const manifest = JSON.parse(fs.readFileSync(path.join(root, 'manifest.json'), 'utf8'));

assert.strictEqual(manifest.version, '2.3.8.3020');
assert.strictEqual(manifest.version_name, '2.3.8.302');

for (const token of ['id="download_image_save"', '다운로드 방식 1 · 전체', '다운로드 방식 2 · 필터 결과', 'id="down_all_medias"', 'id="down_filtered_medias"', 'id="panel-auto8700-devtools"', '춤춤복사', 'Network 감시', 'body 저장']) {
  assert.ok(!html.includes(token), `removed Side UI remains: ${token}`);
}
assert.ok(html.includes('id="download_video_save"'));
assert.ok(html.includes('다운로드 방식 3 · Top sorted 자동'));

assert.ok(html.includes('#igblue_stats_sync_mode'));
assert.ok(/white-space:\s*nowrap/.test(html));
assert.ok(/word-break:\s*keep-all/.test(html));
assert.ok(html.includes('.igblue-stats-sync-detail'));
assert.ok(/white-space:\s*normal/.test(html));
assert.ok(html.indexOf('id="igblue_stats_sync_mode"') < html.indexOf('id="igblue_stats_sync_detail"'));

for (const token of ['function teAccountQueueLineAtPosition', 'function teOpenInstagramAccountFromQueue', 'function teBindAccountQueueDoubleClick', '`${account}을(를) ${label}에서 열까요?`', 'event.shiftKey ? "window" : event.ctrlKey ? "tab" : "current"', 'chrome.tabs.create({ url, active: true }', 'chrome.windows.create({ url, type: "normal", focused: true }', 'chrome.tabs.update(Number(tabId), { url, active: true }']) {
  assert.ok(side.includes(token), `account open token missing: ${token}`);
}
assert.ok(side.includes('const line = teAccountQueueLineAtPosition(textarea);'));
assert.ok(side.includes('const value = String(textarea && textarea.value || "");'));

// Live run queue must still come from the current textarea, not from SQLite persistence.
const entriesStart = side.indexOf('function teAutoPyAccountQueueEntries()');
const entriesEnd = side.indexOf('function teAutoPyRenderAccountQueueEntries', entriesStart);
assert.ok(entriesStart >= 0 && entriesEnd > entriesStart);
const entriesBody = side.slice(entriesStart, entriesEnd);
assert.ok(entriesBody.includes('document.getElementById("igblue_account_url_list")'));
assert.ok(entriesBody.includes('el ? String(el.value || "")'));
assert.ok(!entriesBody.includes('collection-accounts'));
assert.ok(side.includes('const urls = teAutoPyAccountQueueList();'));

// Heart marker/status system is retired without deleting base CDP tab selection.
for (const token of ['devtools_control_marker', 'control_marker', 'ensure_instagram_control_marker', 'marker_prefixes', 'mark_control_tab_titles', '❤️❤️', '❤️💛', '💛💛💛']) {
  assert.ok(!autoPy.includes(token), `retired Auto marker remains: ${token}`);
  assert.ok(!autoCfg.includes(token), `retired Auto config remains: ${token}`);
}
assert.ok(autoPy.includes('def choose_instagram_control_tab(cfg: dict) -> Optional[dict]:'));
assert.ok(autoPy.includes('AUTO8700_CDP_CONNECTION_STATE') && autoPy.includes('owner_target_id'));

function extractFunction(source, name) {
  const start = source.indexOf(`function ${name}(`);
  assert.ok(start >= 0, `${name} missing`);
  const open = source.indexOf('{', start);
  let depth = 0;
  for (let i = open; i < source.length; i += 1) {
    if (source[i] === '{') depth += 1;
    else if (source[i] === '}') {
      depth -= 1;
      if (depth === 0) return source.slice(start, i + 1);
    }
  }
  throw new Error(`${name} close missing`);
}
const sandbox = { String, Number, Math };
vm.createContext(sandbox);
vm.runInContext(`${extractFunction(side, 'teAccountQueueLineAtPosition')}; this.lineAt = teAccountQueueLineAtPosition;`, sandbox);
const textarea = { value: '@muzipsa_home\n@bodlelog\nplain_name', selectionStart: 18 };
assert.strictEqual(sandbox.lineAt(textarea), '@bodlelog');
textarea.selectionStart = 2;
assert.strictEqual(sandbox.lineAt(textarea), '@muzipsa_home');
textarea.selectionStart = textarea.value.length;
assert.strictEqual(sandbox.lineAt(textarea), 'plain_name');

console.log('OK test_ext_side_simplify_account_open_v300');
