import React from 'react';
import { createRoot } from 'react-dom/client';
import ProfileCharts from './components/ProfileCharts';
import BattleDialog from './components/BattleDialog';
import AvatarUpload from './components/AvatarUpload';

const avatarRoot = document.getElementById('profile-avatar-root');
if (avatarRoot) {
  const { uploadUrl, thumbUrl, initials } = avatarRoot.dataset;
  createRoot(avatarRoot).render(
    <AvatarUpload
      uploadUrl={uploadUrl}
      initialThumbUrl={thumbUrl || null}
      initials={initials}
    />,
  );
}

const chartsRoot = document.getElementById('profile-charts-root');
if (chartsRoot) {
  createRoot(chartsRoot).render(
    <ProfileCharts chartData={JSON.parse(chartsRoot.dataset.chartData)} />,
  );
}

const battleRoot = document.getElementById('profile-battle-root');
if (battleRoot) {
  createRoot(battleRoot).render(
    <BattleDialog games={JSON.parse(battleRoot.dataset.games)} />,
  );
}

const list = document.querySelector('.profile-games');
const loadMoreBtn = document.querySelector('[data-load-more]');
if (list && loadMoreBtn) {
  const batchSize = parseInt(list.dataset.batchSize, 10) || 5;
  loadMoreBtn.addEventListener('click', () => {
    const hidden = list.querySelectorAll('.profile-game--hidden');
    Array.from(hidden).slice(0, batchSize).forEach((el) => el.classList.remove('profile-game--hidden'));
    if (list.querySelectorAll('.profile-game--hidden').length === 0) {
      loadMoreBtn.remove();
    }
  });
}

const filterInput = document.querySelector('[data-filter]');
if (list && filterInput) {
  filterInput.addEventListener('input', () => {
    const term = filterInput.value.trim().toLowerCase();
    list.classList.toggle('is-filtering', term.length > 0);
    list.querySelectorAll('.profile-game').forEach((card) => {
      const opp = card.querySelector('.profile-game__opponent')?.textContent.trim().toLowerCase() ?? '';
      card.classList.toggle('profile-game--filtered-out', term.length > 0 && !opp.includes(term));
    });
  });
}
