const balanceEl = document.getElementById('balance');
const usernameEl = document.getElementById('username');
const gridEl = document.getElementById('license-grid');
const refreshBtn = document.getElementById('refresh');
const checkBtn = document.getElementById('check-licenses');
const checkPurchasesBtn = document.getElementById('check-purchases');
const resultPanel = document.getElementById('result-panel');
const resultEl = document.getElementById('result');
const authPanel = document.getElementById('auth-panel');
const shopPanel = document.getElementById('shop-panel');
const authError = document.getElementById('auth-error');
const authTitle = document.getElementById('auth-title');
const loginForm = document.getElementById('login-form');
const registerForm = document.getElementById('register-form');
const toggleAuth = document.getElementById('toggle-auth');
const toggleHint = document.getElementById('toggle-hint');
const userInfo = document.getElementById('user-info');
const guestInfo = document.getElementById('guest-info');
const logoutBtn = document.getElementById('logout');
const resultEmpty = document.getElementById('result-empty');
let currentBalance = 0;

function showResult(payload, variant = 'neutral') {
  resultPanel.style.display = 'block';
  if (resultEmpty) {
    resultEmpty.style.display = 'none';
  }
  resultEl.innerHTML = '';
  resultEl.classList.remove('result-alert');
  if (variant === 'error') {
    resultEl.classList.add('result-alert');
  }

  if (typeof payload === 'string') {
    const text = document.createElement('p');
    text.textContent = payload;
    resultEl.appendChild(text);
    return;
  }

  if (Array.isArray(payload)) {
    if (payload.length === 0) {
      const empty = document.createElement('p');
      empty.textContent = 'Пока нет лицензий.';
      resultEl.appendChild(empty);
      return;
    }
    const list = document.createElement('div');
    list.className = 'result-list';
    payload.forEach((item) => {
      const card = document.createElement('div');
      card.className = 'result-card';
      const title = document.createElement('h3');
      title.textContent = item.name || item.id || 'Лицензия';
      card.appendChild(title);
      if (item.license_id || item.id) {
        const meta = document.createElement('p');
        meta.className = 'result-meta';
        meta.textContent = `ID: ${item.license_id || item.id}`;
        card.appendChild(meta);
      }
      if (item.amount) {
        const price = document.createElement('p');
        price.className = 'result-meta';
        price.textContent = `Сумма: ${item.amount} ₽`;
        card.appendChild(price);
      }
      if (item.status) {
        const status = document.createElement('p');
        status.className = `result-status status-${item.status}`;
        status.textContent = `Статус: ${item.status}`;
        card.appendChild(status);
      }
      if (item.flag) {
        const flag = document.createElement('p');
        flag.className = 'result-flag';
        flag.textContent = item.flag;
        card.appendChild(flag);
      }
      list.appendChild(card);
    });
    resultEl.appendChild(list);
    return;
  }

  const block = document.createElement('div');
  block.className = 'result-block';
  Object.entries(payload).forEach(([key, value]) => {
    const row = document.createElement('div');
    row.className = 'result-row';
    const k = document.createElement('span');
    k.className = 'result-key';
    k.textContent = key;
    const v = document.createElement('span');
    v.className = 'result-value';
    v.textContent = typeof value === 'string' ? value : JSON.stringify(value);
    row.appendChild(k);
    row.appendChild(v);
    block.appendChild(row);
  });
  resultEl.appendChild(block);
}

function setAuthError(message) {
  if (!message) {
    authError.style.display = 'none';
    authError.textContent = '';
    return;
  }
  authError.textContent = message;
  authError.style.display = 'block';
}

function showShop(user) {
  authPanel.style.display = 'none';
  shopPanel.style.display = 'block';
  userInfo.style.display = 'flex';
  guestInfo.style.display = 'none';
  usernameEl.textContent = user.username;
  balanceEl.textContent = user.balance;
  if (resultEmpty) {
    resultEmpty.style.display = 'block';
  }
  resultPanel.style.display = 'none';
  setAuthError('');
}

function showAuth() {
  authPanel.style.display = 'block';
  shopPanel.style.display = 'none';
  userInfo.style.display = 'none';
  guestInfo.style.display = 'flex';
  resultPanel.style.display = 'none';
  if (resultEmpty) {
    resultEmpty.style.display = 'block';
  }
}

async function fetchMe() {
  const res = await fetch('/api/me');
  if (!res.ok) {
    return null;
  }
  return res.json();
}

async function loadBalance() {
  const res = await fetch('/api/balance');
  if (!res.ok) {
    showAuth();
    return;
  }
  const data = await res.json();
  currentBalance = Number(data.balance) || 0;
  balanceEl.textContent = data.balance;
}

function licenseCard(license) {
  const card = document.createElement('div');
  card.className = 'feature-card';
  const mode = Math.random() < 0.5 ? 'json' : 'xml';

  const title = document.createElement('h3');
  title.textContent = license.name;

  const badge = document.createElement('span');
  badge.className = `license-badge license-${mode}`;
  badge.textContent = mode.toUpperCase();

  const price = document.createElement('p');
  price.textContent = `Цена: ${license.price} ₽`;

  const btn = document.createElement('button');
  btn.className = 'btn btn-primary';
  btn.textContent = 'Купить';
  btn.addEventListener('click', async () => {
    await loadBalance();
    if (Number.isFinite(currentBalance) && currentBalance < license.price) {
      showResult('Недостаточно средств для покупки этой лицензии.', 'error');
      return;
    }
    const endpoint = mode === 'xml' ? '/api/purchase-xml' : '/api/purchase';
    const options = { method: 'POST', headers: {}, body: '' };
    if (mode === 'xml') {
      options.headers['Content-Type'] = 'application/xml';
      options.body = `<purchase><license_id>${license.id}</license_id><amount>${license.price}</amount></purchase>`;
    } else {
      options.headers['Content-Type'] = 'application/json';
      options.body = JSON.stringify({ license_id: license.id, amount: license.price });
    }
    const res = await fetch(endpoint, options);
    const data = await res.json();
    showResult(data);
    await loadBalance();
  });

  const header = document.createElement('div');
  header.className = 'license-header';
  header.appendChild(title);
  header.appendChild(badge);
  card.appendChild(header);
  card.appendChild(price);
  card.appendChild(btn);

  return card;
}

async function loadLicenses() {
  const res = await fetch('/api/licenses');
  const data = await res.json();

  gridEl.innerHTML = '';

  const visible = data.filter((license) => !license.hidden);
  if (visible.length === 0) {
    const empty = document.createElement('div');
    empty.className = 'feature-card';
    empty.innerHTML = '<h3>Нет доступных лицензий</h3><p>Попробуйте позже.</p>';
    gridEl.appendChild(empty);
    return;
  }

  visible.forEach((license) => {
    gridEl.appendChild(licenseCard(license));
  });
}

refreshBtn.addEventListener('click', async () => {
  await loadBalance();
});

checkBtn.addEventListener('click', async () => {
  const res = await fetch('/api/my-licenses');
  if (!res.ok) {
    showAuth();
    return;
  }
  const data = await res.json();
  showResult(data);
});

checkPurchasesBtn.addEventListener('click', async () => {
  const res = await fetch('/api/purchases');
  if (!res.ok) {
    showAuth();
    return;
  }
  const data = await res.json();
  showResult(data);
});

toggleAuth.addEventListener('click', (event) => {
  event.preventDefault();
  const loginVisible = loginForm.style.display !== 'none';
  loginForm.style.display = loginVisible ? 'none' : 'flex';
  registerForm.style.display = loginVisible ? 'flex' : 'none';
  authTitle.textContent = loginVisible ? 'Регистрация' : 'Вход';
  toggleHint.textContent = loginVisible ? 'Уже есть аккаунт?' : 'Нет аккаунта?';
  toggleAuth.textContent = loginVisible ? 'Войти' : 'Регистрация';
  setAuthError('');
});

loginForm.addEventListener('submit', async (event) => {
  event.preventDefault();
  setAuthError('');
  const payload = {
    username: document.getElementById('login-username').value.trim(),
    password: document.getElementById('login-password').value.trim()
  };
  const res = await fetch('/api/login', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(payload)
  });
  if (!res.ok) {
    setAuthError('Неверный логин или пароль.');
    return;
  }
  const me = await fetchMe();
  if (me) {
    showShop(me);
    await loadLicenses();
  }
});

registerForm.addEventListener('submit', async (event) => {
  event.preventDefault();
  setAuthError('');
  const payload = {
    username: document.getElementById('register-username').value.trim(),
    password: document.getElementById('register-password').value.trim()
  };
  const res = await fetch('/api/register', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(payload)
  });
  if (!res.ok) {
    setAuthError('Имя пользователя уже занято.');
    return;
  }
  const me = await fetchMe();
  if (me) {
    showShop(me);
    await loadLicenses();
  }
});

logoutBtn.addEventListener('click', async () => {
  await fetch('/api/logout', { method: 'POST' });
  showAuth();
});

(async () => {
  const me = await fetchMe();
  if (me) {
    showShop(me);
    await loadLicenses();
  } else {
    showAuth();
  }
})();
