async function loadPlayerCards() {
  const grid = document.getElementById('playerGrid');
  if (!grid) return;

  grid.innerHTML = '<div class="pp-card"><h3>Ladataan pelaajia...</h3><p>Haetaan dataa Pesisportaalin API:sta.</p></div>';

  try {
    const res = await fetch('/pesisportaali/api/players.php', { cache: 'no-store' });
    const data = await res.json();

    if (!data.success || !Array.isArray(data.players)) {
      throw new Error('Pelaajadata puuttuu');
    }

    applyTheme(data.club?.theme || {});
    renderPlayers(data.players);
  } catch (err) {
    grid.innerHTML = '<div class="pp-card"><h3>Virhe</h3><p>Pelaajia ei saatu ladattua.</p></div>';
    console.error(err);
  }
}

function applyTheme(theme) {
  const root = document.documentElement;

  if (theme.primary) root.style.setProperty('--pp-primary', theme.primary);
  if (theme.background) root.style.setProperty('--pp-bg', theme.background);
  if (theme.surface) root.style.setProperty('--pp-surface', theme.surface);
  if (theme.surface_2) root.style.setProperty('--pp-surface-2', theme.surface_2);
  if (theme.text) root.style.setProperty('--pp-text', theme.text);
  if (theme.muted) root.style.setProperty('--pp-muted', theme.muted);
}

function renderPlayers(players) {
  const grid = document.getElementById('playerGrid');
  if (!grid) return;

  grid.innerHTML = '';

  players.forEach(player => {
    const sponsorName = player.sponsor?.name || 'Ei kummiyritystä';
    const initials = player.initials || getInitials(player.name);

    const card = document.createElement('article');
    card.className = 'pp-player-card';
    card.innerHTML = `
      <div class="pp-player-photo">${player.image ? `<img src="${escapeAttr(player.image)}" alt="">` : escapeHtml(initials)}</div>
      <div class="pp-player-body">
        <div class="pp-player-name">${escapeHtml(player.name || '')}</div>
        <div class="pp-sponsor">${escapeHtml(sponsorName)}</div>
        <div class="pp-open">Katso pelaajaprofiili →</div>
      </div>
    `;

    card.addEventListener('click', () => openPlayerModal(player));
    grid.appendChild(card);
  });
}

function openPlayerModal(player) {
  const modal = document.getElementById('playerModal');
  const modalName = document.getElementById('modalName');
  const modalSponsor = document.getElementById('modalSponsor');
  const modalInitials = document.getElementById('modalInitials');
  const profileMeta = document.getElementById('modalProfileMeta');

  if (!modal) return;

  modalName.textContent = player.name || '';
  modalSponsor.textContent = player.sponsor?.name || 'Ei kummiyritystä';
  modalInitials.textContent = player.initials || getInitials(player.name);

  const age = player.profile?.age ? `${player.profile.age} vuotta` : '';
  const team = player.profile?.team || '';

  profileMeta.innerHTML = `
    ${escapeHtml(team)}<br>
    ${escapeHtml(age)}<br>
    Pelaajaprofiili
  `;

  renderAccordionStats(player.stats || {});
  modal.classList.add('is-open');
}

function renderAccordionStats(stats) {
  renderStatBlock('statsSeries', stats.series || {});
  renderStatBlock('statsSeason', stats.season || {});
  renderStatBlock('statsCareer', stats.career || {});
}

function renderStatBlock(id, rows) {
  const el = document.getElementById(id);
  if (!el) return;

  el.innerHTML = '';

  Object.entries(rows).forEach(([label, value]) => {
    const row = document.createElement('div');
    row.className = 'pp-stat-row';
    row.innerHTML = `<span>${escapeHtml(label)}</span><strong>${escapeHtml(String(value))}</strong>`;
    el.appendChild(row);
  });
}

function getInitials(name) {
  return String(name || '')
    .split(' ')
    .filter(Boolean)
    .map(part => part[0])
    .join('')
    .substring(0, 2)
    .toUpperCase();
}

function escapeHtml(value) {
  return String(value ?? '').replace(/[&<>"']/g, c => ({
    '&': '&amp;',
    '<': '&lt;',
    '>': '&gt;',
    '"': '&quot;',
    "'": '&#039;'
  }[c]));
}

function escapeAttr(value) {
  return escapeHtml(value);
}

function setupModalAndAccordion() {
  const modal = document.getElementById('playerModal');
  const modalClose = document.getElementById('modalClose');

  if (modalClose && modal) {
    modalClose.addEventListener('click', () => modal.classList.remove('is-open'));
    modal.addEventListener('click', e => {
      if (e.target === modal) modal.classList.remove('is-open');
    });
  }

  document.querySelectorAll('.pp-acc-btn').forEach(btn => {
    btn.addEventListener('click', () => {
      const content = btn.nextElementSibling;
      const isOpen = content.classList.contains('is-open');

      document.querySelectorAll('.pp-acc-btn').forEach(b => b.classList.remove('is-active'));
      document.querySelectorAll('.pp-acc-content').forEach(c => c.classList.remove('is-open'));

      if (!isOpen) {
        btn.classList.add('is-active');
        content.classList.add('is-open');
      }
    });
  });
}

document.addEventListener('DOMContentLoaded', () => {
  setupModalAndAccordion();
  loadPlayerCards();
});
