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

  function statusLabel(status) {
    if (status === 'live') return 'Käynnissä';
    if (status === 'finished') return 'Päättynyt';
    if (status === 'canceled') return 'Peruttu';
    return 'Tulossa';
  }

  function statusClass(status) {
    if (status === 'live') return 'pp-status-live';
    if (status === 'finished') return 'pp-status-finished';
    if (status === 'canceled') return 'pp-status-canceled';
    return 'pp-status-scheduled';
  }

  function logo(team) {
    if (!team?.logo) {
      return '<span class="pp-team-logo pp-team-logo-empty"></span>';
    }

    return `<span class="pp-team-logo-wrap"><img class="pp-team-logo" src="${esc(team.logo)}" alt=""></span>`;
  }

  function mapsUrl(match) {
    const apiUrl =
      match?.stadium?.maps_url ||
      match?.stadium?.google_maps_url ||
      match?.stadium?.map_url ||
      '';

    if (apiUrl) {
      return apiUrl;
    }

    const query = [
      match?.stadium?.name,
      match?.stadium?.address,
      match?.stadium?.city
    ].filter(Boolean).join(', ');

    return query
      ? `https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(query)}`
      : '';
  }

  function renderPeriods(match) {
    const periods = Array.isArray(match?.score?.periods)
      ? match.score.periods
      : [];

    if (!periods.length) return '';

    return `
      <div class="pp-period-scores">
        ${periods.map((period, index) => `
          <div class="pp-period-score">
            <span>${index + 1}. jakso</span>
            <strong>${esc(period.home)}–${esc(period.away)}</strong>
          </div>
        `).join('')}
      </div>
    `;
  }

  function renderBottom(match) {
    if (match.status === 'live') {
      return `
        <div class="pp-live-message">
          <span class="pp-live-dot"></span>
          Ottelu käynnissä
        </div>
      `;
    }

    if (match.status === 'finished') {
      const setResult =
        match?.score?.sets ||
        match?.score?.result_string ||
        match?.result ||
        '';

      return `
        <div class="pp-finished-result">
          ${setResult ? `<div class="pp-result">${esc(setResult)}</div>` : ''}
          ${renderPeriods(match)}
        </div>
      `;
    }

    if (match.status === 'canceled') {
      return '<div class="pp-bottom-message">Ottelu peruttu</div>';
    }

    return `
      <div class="pp-bottom-message">
        Ottelu alkaa${match.time ? ` klo ${esc(match.time)}` : ''}
      </div>
    `;
  }

  async function loadGames(root) {
    const club = root.dataset.seura || 'mailajuniorit';
    const title = root.dataset.title || 'Mailajunioreiden ottelut tänään';
    const kicker = root.dataset.kicker || 'Tänään kentällä';

    root.innerHTML =
      '<div class="pp-games-loading">Ladataan päivän otteluita...</div>';

    try {
      const apiUrl =
        `https://wwwdesign.fi/pesisportaali/api/paivan-pelit.php` +
        `?seura=${encodeURIComponent(club)}`;

      const response = await fetch(apiUrl, { cache: 'no-store' });
      const data = await response.json();

      if (!response.ok || !data.success) {
        throw new Error(data.error || 'Otteludatan haku epäonnistui');
      }

      root.style.setProperty(
        '--pp-primary',
        data.club?.color || '#f58220'
      );

      const matches = Array.isArray(data.matches) ? data.matches : [];

      let html = `
        <div class="pp-games-head">
          <div class="pp-games-title-wrap">
            <div class="pp-games-kicker">${esc(kicker)}</div>
            <h2 class="pp-games-title">${esc(title)}</h2>
          </div>
        </div>
      `;

      if (!matches.length) {
        root.innerHTML =
          html +
          '<div class="pp-games-empty">Ei Mailajunioreiden otteluita tänään.</div>';
        return;
      }

      html += '<div class="pp-games-list">';

      matches.forEach(match => {
        const series =
          match.series ||
          match.series_full ||
          'Sarjatieto puuttuu';

        const phase =
          match.phase ||
          match.series_name ||
          'Lohkotieto puuttuu';

        const stadium =
          match?.stadium?.name ||
          match.stadium_text ||
          'Kenttätieto puuttuu';

        const mapLink = mapsUrl(match);

        const homeAway = match.club_side === 'home' ? 'KOTI' : 'VIERAS';
        const homeAwayClass =
          match.club_side === 'home'
            ? 'pp-homeaway-home'
            : 'pp-homeaway-away';

        const stadiumHtml = mapLink
          ? `
            <a class="pp-info-value pp-stadium-link"
               href="${esc(mapLink)}"
               target="_blank"
               rel="noopener noreferrer">
              ${esc(stadium)}
            </a>
          `
          : `<div class="pp-info-value">${esc(stadium)}</div>`;

        html += `
          <article class="pp-game-card">
            <div class="pp-game-top">
              <div class="pp-game-day ${homeAwayClass}">
                ${homeAway}
              </div>

              <span class="pp-status-pill ${statusClass(match.status)}">
                ${esc(statusLabel(match.status))}
              </span>
            </div>

            <div class="pp-game-time">${esc(match.time || '')}</div>

            <div class="pp-teams">
              <div class="pp-team-row">
                ${logo(match.home)}
                <div class="pp-team-name">${esc(match.home?.name || '')}</div>
              </div>

              <div class="pp-vs">vs</div>

              <div class="pp-team-row">
                ${logo(match.away)}
                <div class="pp-team-name">${esc(match.away?.name || '')}</div>
              </div>
            </div>

            <div class="pp-game-meta">
              <div class="pp-info">
                <div class="pp-info-block">
                  <div class="pp-info-label">Sarja</div>
                  <div class="pp-info-value">${esc(series)}</div>
                </div>

                <div class="pp-info-block">
                  <div class="pp-info-label">Lohko</div>
                  <div class="pp-info-value">${esc(phase)}</div>
                </div>

                <div class="pp-info-block">
                  <div class="pp-info-label">Kenttä</div>
                  ${stadiumHtml}
                </div>
              </div>
            </div>

            <div class="pp-game-bottom">
              ${renderBottom(match)}
            </div>
          </article>
        `;
      });

      html += '</div>';
      root.innerHTML = html;
    } catch (error) {
      console.error(error);
      root.innerHTML =
        '<div class="pp-games-error">Päivän otteluita ei saatu ladattua.</div>';
    }
  }

  document.addEventListener('DOMContentLoaded', function () {
    document
      .querySelectorAll('[data-pesis-paivan-pelit]')
      .forEach(loadGames);
  });
})();
