(function () {
  const API_BASE = document.querySelector('meta[name="omnl-api-base"]')?.getAttribute('content') || '/api/v1';
  const screenEl = document.getElementById('terminal-screen');
  const jsonEl = document.getElementById('json-out');
  const inpRef = document.getElementById('inp-settlement-ref');
  const inpOffice = document.getElementById('inp-office-id');
  const inpDate = document.getElementById('inp-value-date');
  const inpAmount = document.getElementById('inp-amount');
  const inpToken = document.getElementById('inp-token');
  const inpAlchemyAddr = document.getElementById('inp-alchemy-addr');

  let screenMode = 'black';

  const inpConnection = document.getElementById('inp-connection');
  const DEFAULT_CONNECTION = 'mk-albert-gate-limited';
  const DEFAULT_WALLET = '0xb3B416BdE671c256aAbFB56358baD91D46BB9c39';

  (function initFromQuery() {
    const p = new URLSearchParams(window.location.search);
    const conn = p.get('connectionId') || DEFAULT_CONNECTION;
    if (inpConnection) inpConnection.value = conn;
    const ref = p.get('settlementRef');
    if (ref) inpRef.value = ref;
  })();

  function qs() {
    const p = new URLSearchParams(window.location.search);
    const token = inpToken.value.trim() || p.get('access_token') || '';
    const q = new URLSearchParams({
      settlementRef: inpRef.value.trim(),
      officeId: String(inpOffice.value || '1'),
      valueDate: inpDate.value,
      amountUsd: inpAmount.value.trim(),
    });
    const conn = inpConnection && inpConnection.value ? inpConnection.value.trim() : '';
    if (conn) q.set('connectionId', conn);
    if (token) q.set('access_token', token);
    return q;
  }

  function authHeaders() {
    const token = inpToken.value.trim() || new URLSearchParams(window.location.search).get('access_token') || '';
    return token ? { Authorization: 'Bearer ' + token } : {};
  }

  async function apiGet(path, extra) {
    const q = qs();
    if (extra) {
      Object.entries(extra).forEach(function (kv) {
        q.set(kv[0], kv[1]);
      });
    }
    const res = await fetch(API_BASE + path + '?' + q.toString(), { headers: authHeaders() });
    const text = await res.text();
    let data;
    try {
      data = JSON.parse(text);
    } catch {
      data = { raw: text, status: res.status };
    }
    if (!res.ok) throw new Error(data.error || data.raw || res.statusText);
    return data;
  }

  async function apiPost(path, body) {
    const q = qs();
    const res = await fetch(API_BASE + path + '?' + q.toString(), {
      method: 'POST',
      headers: { 'Content-Type': 'application/json', ...authHeaders() },
      body: JSON.stringify(body),
    });
    const data = await res.json().catch(function () {
      return {};
    });
    if (!res.ok) throw new Error(data.error || res.statusText);
    return data;
  }

  function showJson(data) {
    jsonEl.textContent = JSON.stringify(data, null, 2);
  }

  function showScreen(text) {
    screenEl.textContent = text;
  }

  function setTheme(mode) {
    screenMode = mode === 'color' ? 'color' : 'black';
    document.body.classList.toggle('theme-black', screenMode === 'black');
    document.body.classList.toggle('theme-color', screenMode === 'color');
    document.getElementById('btn-mode-black').classList.toggle('active', screenMode === 'black');
    document.getElementById('btn-mode-color').classList.toggle('active', screenMode === 'color');
  }

  async function loadScreen(artifact) {
    const data = await apiGet('/omnl/terminal/screen', {
      mode: screenMode,
      artifact: artifact || 'package',
      format: 'json',
    });
    showScreen(data.text || '');
    showJson(data);
  }

  async function runCmd(cmd) {
    try {
      if (cmd === 'help') {
        showScreen(
          [
            'OMNL / HYBX SETTLEMENT TERMINAL — COMMANDS',
            '',
            '  status          — integration status',
            '  package         — full JSON package',
            '  pof             — proof of funds',
            '  debit-note      — debit note',
            '  remittance      — remittance advice',
            '  token-san       — tokenization sanitized copy',
            '  swift-copy      — conversion SWIFT copy',
            '  screen          — terminal screen (current theme)',
            '  alchemy balance — eth_getBalance via Alchemy',
            '',
            'Toggle Black/Green vs Gray/Black with toolbar buttons.',
          ].join('\n')
        );
        return;
      }
      if (cmd === 'status') {
        const q = qs();
        const token = q.get('access_token');
        const url = API_BASE + '/omnl/terminal/status' + (token ? '?access_token=' + encodeURIComponent(token) : '');
        const data = await fetch(url, { headers: authHeaders() }).then(function (r) {
          return r.json();
        });
        showJson(data);
        showScreen(JSON.stringify(data, null, 2));
        return;
      }
      if (cmd === 'package') {
        const data = await apiGet('/omnl/terminal/package');
        showJson(data);
        if (data.artifacts && data.artifacts.screens) {
          showScreen(data.artifacts.screens[screenMode] || '');
        }
        return;
      }
      if (cmd === 'pof') {
        const data = await apiGet('/omnl/terminal/proof-of-funds');
        showJson(data);
        await loadScreen('proof-of-funds');
        return;
      }
      if (cmd === 'debit') {
        const data = await apiGet('/omnl/terminal/debit-note');
        showJson(data);
        await loadScreen('debit-note');
        return;
      }
      if (cmd === 'remittance') {
        const data = await apiGet('/omnl/terminal/remittance-advice');
        showJson(data);
        await loadScreen('remittance-advice');
        return;
      }
      if (cmd === 'token') {
        const data = await apiGet('/omnl/terminal/tokenization-sanitized');
        showJson(data);
        await loadScreen('tokenization-sanitized');
        return;
      }
      if (cmd === 'swift') {
        const data = await apiGet('/omnl/terminal/conversion-swift-copy');
        showJson(data);
        await loadScreen('conversion-swift-copy');
        return;
      }
      if (cmd === 'screen') {
        await loadScreen('package');
        return;
      }
      if (cmd === 'alchemy-balance') {
        const addr = (inpAlchemyAddr.value || '').trim();
        if (!addr) throw new Error('Set Alchemy address first');
        const data = await apiPost('/omnl/terminal/alchemy/rpc', {
          network: 'eth-mainnet',
          method: 'eth_getBalance',
          params: [addr, 'latest'],
          connectionId: (inpConnection && inpConnection.value) || DEFAULT_CONNECTION,
        });
        showJson(data);
        showScreen('ALCHEMY eth_getBalance\nADDRESS: ' + addr + '\nRESULT: ' + data.result);
        return;
      }
    } catch (e) {
      showScreen('ERROR: ' + (e && e.message ? e.message : String(e)));
    }
  }

  document.getElementById('btn-mode-black').addEventListener('click', function () {
    setTheme('black');
    runCmd('screen');
  });
  document.getElementById('btn-mode-color').addEventListener('click', function () {
    setTheme('color');
    runCmd('screen');
  });
  document.getElementById('btn-refresh').addEventListener('click', function () {
    runCmd('screen');
  });
  document.querySelectorAll('[data-cmd]').forEach(function (btn) {
    btn.addEventListener('click', function () {
      runCmd(btn.getAttribute('data-cmd'));
    });
  });

  setTheme('black');
  runCmd('screen');
})();
