/**
 * This file is part of the SplendidBear Websites' projects.
 *
 * Copyright (c) 2026 @ www.splendidbear.org
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

import React from 'react';
import { createRoot } from 'react-dom/client';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { AvatarUpload, BattleDialog, ProfileCharts } from '@global-components';

const queryClient = new QueryClient();

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

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 (0 === list.querySelectorAll('.profile-game--hidden').length) {
      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', 0 < term.length);
    list.querySelectorAll('.profile-game').forEach(card => {
      const opp = card.querySelector('.profile-game__opponent')?.textContent.trim().toLowerCase() ?? '';
      card.classList.toggle('profile-game--filtered-out', 0 < term.length && !opp.includes(term));
    });
  });
}
