// FILE: _St/IG_StYellow/test_ext_account_queue_modifier_doubleclick_v307.js | ROLE: 수집계정 목록 Shift/Ctrl 더블클릭 열기 회귀
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');

function extractFunction(source, name) {
  const start = source.indexOf(`function ${name}(`);
  assert.ok(start >= 0, `${name} must exist`);
  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} closing brace not found`);
}

assert.ok(side.includes('el.addEventListener("dblclick", (event) => { teAutoPyOpenAccountQueueModifierDoubleClick(event, el); }, true);'));
assert.ok(html.includes('Shift+더블클릭=새창, Ctrl+더블클릭=새탭'));

const calls = { tabs: [], windows: [] };
const sandbox = {
  chrome: {
    tabs: { create(opts) { calls.tabs.push(opts); } },
    windows: { create(opts) { calls.windows.push(opts); } },
  },
  teAutoPyNormalizeAccountUsername(raw) {
    return String(raw || '').trim().replace(/^🗑️\s*/, '').replace(/^@+/, '').trim().toLowerCase();
  },
  teAutoPyAccountUrlFromUsername(raw) {
    const username = sandbox.teAutoPyNormalizeAccountUsername(raw);
    return username ? `https://www.instagram.com/${username}/` : '';
  },
};
vm.createContext(sandbox);
vm.runInContext(`${extractFunction(side, 'teAutoPyAccountQueueLineAtPosition')}; ${extractFunction(side, 'teAutoPyOpenAccountQueueModifierDoubleClick')};`, sandbox);

function event(mods = {}) {
  return {
    shiftKey: !!mods.shiftKey,
    ctrlKey: !!mods.ctrlKey,
    prevented: false,
    stopped: false,
    preventDefault() { this.prevented = true; },
    stopPropagation() { this.stopped = true; },
  };
}

const value = '@first_user\n@second.user\n@third_user';

// Ctrl + double click: clicked line opens in a new tab.
const ctrlEl = { value, selectionStart: value.indexOf('second.user') + 2, selectionEnd: value.indexOf('second.user') + 5, selectionDirection: 'none' };
const ctrlEvent = event({ ctrlKey: true });
assert.strictEqual(vm.runInContext('teAutoPyOpenAccountQueueModifierDoubleClick', sandbox)(ctrlEvent, ctrlEl), true);
assert.strictEqual(calls.tabs.length, 1);
assert.strictEqual(calls.tabs[0].url, 'https://www.instagram.com/second.user/');
assert.strictEqual(calls.tabs[0].active, true);
assert.strictEqual(calls.windows.length, 0);
assert.ok(ctrlEvent.prevented && ctrlEvent.stopped);

// Shift + double click: forward selection uses clicked end and opens in a new window.
const thirdStart = value.indexOf('@third_user');
const shiftEl = { value, selectionStart: 0, selectionEnd: thirdStart + 4, selectionDirection: 'forward' };
const shiftEvent = event({ shiftKey: true });
assert.strictEqual(vm.runInContext('teAutoPyOpenAccountQueueModifierDoubleClick', sandbox)(shiftEvent, shiftEl), true);
assert.strictEqual(calls.windows.length, 1);
assert.strictEqual(calls.windows[0].url, 'https://www.instagram.com/third_user/');
assert.strictEqual(calls.windows[0].type, 'normal');
assert.strictEqual(calls.tabs.length, 1);

// No modifier: preserve normal textarea double-click behavior.
const normalEvent = event();
assert.strictEqual(vm.runInContext('teAutoPyOpenAccountQueueModifierDoubleClick', sandbox)(normalEvent, ctrlEl), false);
assert.strictEqual(normalEvent.prevented, false);
assert.strictEqual(calls.tabs.length, 1);
assert.strictEqual(calls.windows.length, 1);

console.log('test_ext_account_queue_modifier_doubleclick_v307: OK');
