import { registerServerOnSolana } from '../../js/services/shine-user-pda-service.js';
import {
  $,
  buildKeyBundleFromForm,
  clearGenMessage,
  clearStatus,
  openDevnetTopup,
  deriveKeyBundleFromPassword,
  fillKeyFields,
  parseLoginList,
  refreshDeviceBalance,
  setGenMessage,
  setStatus,
  setupPasswordEye,
  updateSolAddress,
  validateLoginOrThrow,
  wireDeviceAddressPreview,
} from './server-ui-shared.js';

const fieldMap = {
  masterSecret: 'masterSecret',
  rootPub: 'rootPub',
  rootPriv: 'rootPriv',
  bchPub: 'bchPub',
  bchPriv: 'bchPriv',
  devPub: 'devPub',
  devPriv: 'devPriv',
  solBox: 'solBox',
  solAdr: 'solAdr',
};

setupPasswordEye($('btnEye'), $('password'));
wireDeviceAddressPreview(fieldMap);
$('password').value = '';

$('btnTopupDevnet').addEventListener('click', () => {
  try {
    openDevnetTopup($('devPub').value);
  } catch (error) {
    setStatus($('status'), error?.message || String(error), 'error');
  }
});

$('btnRefreshBalance').addEventListener('click', async () => {
  try {
    $('btnRefreshBalance').disabled = true;
    await refreshDeviceBalance({
      endpoint: $('endpoint').value,
      deviceAddress: $('devPub').value,
      targetNode: $('deviceBalance'),
    });
  } catch (error) {
    setStatus($('status'), error?.message || String(error), 'error');
  } finally {
    $('btnRefreshBalance').disabled = false;
  }
});

$('btnGen').addEventListener('click', async () => {
  clearGenMessage($('genMsg'));
  clearStatus($('status'));
  $('btnGen').disabled = true;
  try {
    const login = validateLoginOrThrow($('login').value);
    const password = $('password').value;
    const { masterSecret32, keyBundle } = await deriveKeyBundleFromPassword({
      login,
      password,
    });
    fillKeyFields(fieldMap, keyBundle, masterSecret32);
    updateSolAddress(fieldMap);
    $('deviceBalance').textContent = 'Теперь можно проверить баланс device-аккаунта.';
    setGenMessage($('genMsg'), 'Ключи и master secret сгенерированы из логина и пароля. Транзакцию оплатит device-ключ.', 'ok');
  } catch (error) {
    setGenMessage($('genMsg'), error?.message || String(error), 'err');
  } finally {
    $('btnGen').disabled = false;
  }
});

$('btnCreate').addEventListener('click', async () => {
  clearStatus($('status'));
  clearGenMessage($('genMsg'));
  $('btnCreate').disabled = true;
  try {
    const login = validateLoginOrThrow($('login').value);
    const endpoint = String($('endpoint').value || '').trim();
    if (!endpoint) throw new Error('Укажите Solana endpoint');
    const serverAddress = String($('serverAddress').value || '').trim();
    if (!serverAddress) throw new Error('Укажите адрес сервера');

    setStatus($('status'), 'Проверка и сборка keyBundle...', 'info');
    const { keyBundle, normalized } = await buildKeyBundleFromForm(fieldMap);
    $('rootPub').value = normalized.rootPubB58;
    $('rootPriv').value = normalized.rootPrivB58;
    $('bchPub').value = normalized.bchPubB58;
    $('bchPriv').value = normalized.bchPrivB58;
    $('devPub').value = normalized.devPubB58;
    $('devPriv').value = normalized.devPrivB58;
    updateSolAddress(fieldMap);

    setStatus($('status'), 'Отправка create_user_pda в Solana...', 'info');
    const result = await registerServerOnSolana({
      login,
      keyBundle,
      serverAddress,
      syncServers: parseLoginList($('syncServers').value),
      accessServers: parseLoginList($('accessServers').value),
      solanaEndpoint: endpoint,
    });

    setStatus(
      $('status'),
      `✓ Сервер зарегистрирован!\n\nЛогин: ${login}\nPDA: ${result.pdaAddress}\nBlockchain: ${result.blockchainName}\nТранзакция: ${result.signature}`,
      'success',
    );
  } catch (error) {
    setStatus($('status'), error?.message || String(error), 'error');
  } finally {
    $('btnCreate').disabled = false;
  }
});

document.body.dataset.ready = '1';
