<%- include('../partials/head', { title, bodyClass: 'app-page app-screen-page matches-app-page' }) %>
<%- include('../partials/app-header') %>

<%
  const picker = typeof dateWindow !== 'undefined' && dateWindow ? dateWindow : null;
  const meta = typeof matchesMeta !== 'undefined' && matchesMeta ? matchesMeta : {};
  const selectedDate = picker ? picker.selectedDate : meta.date;
  const oddsEnabled = typeof includeOdds !== 'undefined' && includeOdds;
  const dateHref = (dateIso) => `/matchs?date=${dateIso}${oddsEnabled ? '&odds=1' : ''}`;
  const oddsHref = (() => {
    const params = [];
    if (selectedDate) params.push(`date=${encodeURIComponent(selectedDate)}`);
    if (!oddsEnabled) params.push('odds=1');
    return `/matchs${params.length ? `?${params.join('&')}` : ''}`;
  })();
  const selectedIndex = picker && picker.dates ? picker.dates.findIndex((dateItem) => dateItem.iso === picker.selectedDate) : -1;
  const prevDate = picker && picker.dates && selectedIndex > 0 ? picker.dates[selectedIndex - 1] : null;
  const nextDate = picker && picker.dates && selectedIndex >= 0 && selectedIndex < picker.dates.length - 1 ? picker.dates[selectedIndex + 1] : null;
  const competitions = (Array.isArray(matches) ? matches : []).reduce((groups, match) => {
    const key = match.competition_name || 'Compétition';
    if (!groups[key]) groups[key] = [];
    groups[key].push(match);
    return groups;
  }, {});
  const competitionSections = Object.keys(competitions).map((competitionName) => {
    const rows = competitions[competitionName];
    const countrySource = rows.find((match) => match.country || match.competition_country || match.league_country || match.country_name) || {};
    return {
      name: competitionName,
      country: countrySource.country || countrySource.competition_country || countrySource.league_country || countrySource.country_name || 'Monde',
      matches: rows
    };
  });
  const desktopFeaturedMatch = (typeof desktopFeaturedPreview !== 'undefined' && desktopFeaturedPreview) || (Array.isArray(matches) ? matches : []).find((match) => {
    const status = String(`${match.status || ''} ${match.status_short || ''}`).toLowerCase();
    const statusShort = String(match.status_short || '').toLowerCase();
    return !(match.is_finished || match.isFinished || ['ft', 'aet', 'pen', 'terminé', 'termine', 'finished'].some((token) => statusShort === token || status.includes(token)));
  }) || (Array.isArray(matches) ? matches[0] : null);
  const desktopCarouselMatches = (typeof desktopPreviewMatches !== 'undefined' && Array.isArray(desktopPreviewMatches) && desktopPreviewMatches.length)
    ? desktopPreviewMatches
    : (desktopFeaturedMatch ? [desktopFeaturedMatch] : []);
  const desktopFeaturedId = desktopFeaturedMatch ? (desktopFeaturedMatch.api_fixture_id || desktopFeaturedMatch.id) : null;
  const desktopFeaturedOdds = desktopFeaturedMatch ? (desktopFeaturedMatch.odds_1x2 || null) : null;
  const desktopVoteStatsMap = typeof desktopMatchVoteStatsById !== 'undefined' && desktopMatchVoteStatsById
    ? desktopMatchVoteStatsById
    : {};
  const desktopMatchKey = (match) => String(match && (match.api_fixture_id || match.fixture_id || match.id) || '').trim();
  const desktopVoteStats = typeof desktopMatchVoteStats !== 'undefined' && desktopMatchVoteStats
    ? desktopMatchVoteStats
    : { total: 0, selected: null, options: {} };
  const desktopVoteStatsForMatch = (match) => desktopVoteStatsMap[desktopMatchKey(match)] || (desktopMatchKey(match) === desktopMatchKey(desktopFeaturedMatch) ? desktopVoteStats : null) || { total: 0, selected: null, options: {} };
  const desktopVoteOption = (stats, choice) => (stats.options && stats.options[choice]) || { count: 0, percent: 0 };
  const desktopVoteLabel = (count) => `${Number(count || 0)} vote${Number(count || 0) > 1 ? 's' : ''}`;
  const desktopVotePercent = (value) => Math.max(0, Math.min(100, Math.round(Number(value || 0))));
  const liveCount = (Array.isArray(matches) ? matches : []).filter((match) => {
    const status = String(`${match.status || ''} ${match.status_short || ''}`).toLowerCase();
    const statusShort = String(match.status_short || '').toLowerCase();
    const statusTokens = status.split(/\s+/).filter(Boolean);
    return match.is_live || match.isLive || status.includes('live') || status.includes('direct') || ['1h', '2h', 'ht', 'et', 'p'].some((token) => statusShort === token || statusTokens.includes(token));
  }).length;
  const desktopVisibleRecommendations = Array.isArray(desktopNeoRecommendations) ? desktopNeoRecommendations : [];
  const desktopLockedRecommendations = Array.isArray(desktopNeoLockedRecommendations) ? desktopNeoLockedRecommendations : [];
  const desktopRecommendations = [
    ...desktopVisibleRecommendations.map((recommendation) => ({ ...recommendation, _desktopLocked: false })),
    ...desktopLockedRecommendations.map((recommendation) => ({ ...recommendation, _desktopLocked: true }))
  ].slice(0, 3);
  const splitMatchLabel = (label) => String(label || 'Match du jour').split(/\s+(?:vs|v|-|–)\s+/i).filter(Boolean);
%>

<main class="app-main app-screen matches-app favorites-app matches-favorites-render <%= oddsEnabled ? 'show-odds' : '' %>" data-auto-refresh="matches" data-refresh-interval="25000" data-matches-app data-selected-date="<%= selectedDate || '' %>">
  <div class="matches-desktop-left">
  <section class="matches-date-control" aria-label="Elegir la fecha de los partidos">
    <% if (prevDate) { %>
      <a href="<%= dateHref(prevDate.iso) %>" aria-label="Fecha anterior">‹</a>
    <% } else { %>
      <span aria-hidden="true">‹</span>
    <% } %>
    <button type="button" data-date-picker-toggle aria-expanded="false">
      <svg viewBox="0 0 24 24" aria-hidden="true"><rect x="5" y="4" width="14" height="16" rx="2"></rect><path d="M8 2v4M16 2v4M5 9h14"></path></svg>
      <strong><%= picker && picker.selected ? picker.selected.label : 'Hoy' %></strong>
      <em>⌄</em>
    </button>
    <% if (nextDate) { %>
      <a href="<%= dateHref(nextDate.iso) %>" aria-label="Fecha siguiente">›</a>
    <% } else { %>
      <span aria-hidden="true">›</span>
    <% } %>
    <% if (picker && Array.isArray(picker.dates) && picker.dates.length) { %>
      <div class="matches-date-menu" data-date-picker-menu hidden>
        <% picker.dates.forEach((dateItem) => { %>
          <a class="<%= dateItem.iso === selectedDate ? 'active' : '' %>" href="<%= dateHref(dateItem.iso) %>">
            <strong><%= dateItem.label %></strong>
            <span><%= formatDate(dateItem.iso) %></span>
          </a>
        <% }) %>
      </div>
    <% } %>
  </section>

  <section class="app-filter-row">
    <button type="button" class="active" data-match-filter="all">Todos</button>
    <button type="button" data-match-filter="upcoming">Próximo</button>
    <button type="button" data-match-filter="live">En vivo <strong class="matches-live-badge"><%= liveCount %></strong></button>
  </section>

  <section class="matches-search-row">
    <label>
      <svg viewBox="0 0 24 24" aria-hidden="true"><circle cx="11" cy="11" r="7"></circle><path d="m16 16 4 4"></path></svg>
      <input type="search" placeholder="Buscar" autocomplete="off" data-match-search>
    </label>
    <span>Cuotas</span>
    <a class="matches-odds-toggle <%= oddsEnabled ? 'active' : '' %>" href="<%= oddsHref %>" aria-label="Mostrar las cuotas"><i></i></a>
  </section>

  <a class="matches-advice-link" href="/recommendations">
    <span>✦</span>
    <strong>Consejos IA del día</strong>
    <em>›</em>
  </a>

  <section class="app-data-chip matches-data-chip">
    <span>MAJ</span>
    <strong><%= formatDateTime(meta.updatedAt) %></strong>
  </section>

  <% if (meta.source === 'api-error') { %>
    <section class="api-warning glass-panel">
      <h2>Matchs momentanément indisponibles</h2>
      <p><%= meta.message %></p>
    </section>
  <% } %>

  <% if (matches.length) { %>
    <section class="favorites-bucket matches-competition-bucket" data-matches-list>
      <% competitionSections.forEach((competition) => { %>
        <details class="favorites-competition" open data-competition-group>
          <summary>
            <span class="favorites-competition-icon" aria-hidden="true">
              <svg viewBox="0 0 24 24">
                <path d="M8 4h8v3a4 4 0 0 1-8 0z"></path>
                <path d="M8 6H5a3 3 0 0 0 3 3"></path>
                <path d="M16 6h3a3 3 0 0 1-3 3"></path>
                <path d="M12 11v4"></path>
                <path d="M9 20h6"></path>
                <path d="M10 15h4l1 5H9z"></path>
              </svg>
            </span>
            <span>
              <strong><%= competition.name %></strong>
              <small><%= competition.country %> · <%= competition.matches.length %> match<%= competition.matches.length > 1 ? 's' : '' %></small>
            </span>
            <em aria-hidden="true">⌄</em>
          </summary>
          <div class="favorites-match-list">
            <% competition.matches.forEach((match) => { %>
              <%- include('../partials/app-match-row', { match }) %>
            <% }) %>
          </div>
        </details>
      <% }) %>
    </section>
    <section class="app-empty-card matches-filter-empty is-filter-hidden" data-match-filter-empty hidden>
      <h2 data-match-filter-empty-title>Ningún partido que mostrar</h2>
      <p data-match-filter-empty-copy>Cambia el filtro o la fecha para ver los partidos disponibles.</p>
    </section>
  <% } else { %>
    <section class="app-empty-card">
      <h2>No encontramos ningún partido importante</h2>
      <p><%= meta.message ? meta.message : 'No hay ningún partido importante previsto en esta fecha dentro de las competiciones que sigue TopStats.' %></p>
      <a class="btn btn-primary" href="/matchs<%= selectedDate ? `?date=${selectedDate}` : '' %>">Actualizar</a>
    </section>
  <% } %>
  </div>

  <% if (desktopCarouselMatches.length) { %>
    <aside class="matches-desktop-panel" aria-label="Aperçu du match" data-desktop-match-panel>
      <div class="matches-desktop-carousel" data-desktop-carousel>
        <div class="matches-desktop-track" data-desktop-track>
          <% desktopCarouselMatches.forEach((carouselMatch, slideIndex) => {
            const carouselMatchId = carouselMatch.api_fixture_id || carouselMatch.fixture_id || carouselMatch.id;
            const carouselVoteStats = desktopVoteStatsForMatch(carouselMatch);
            const carouselOdds = carouselMatch.odds_1x2 || null;
            const carouselStatus = String(`${carouselMatch.status || ''} ${carouselMatch.status_short || ''}`).toLowerCase();
            const carouselStatusShort = String(carouselMatch.status_short || '').toLowerCase();
            const carouselTokens = carouselStatus.split(/\s+/).filter(Boolean);
            const carouselHasScore = carouselMatch.score_home !== null && carouselMatch.score_home !== undefined && carouselMatch.score_away !== null && carouselMatch.score_away !== undefined;
            const carouselFinished = carouselMatch.is_finished || carouselMatch.isFinished || ['ft', 'aet', 'pen', 'terminé', 'termine', 'finished'].some((token) => carouselStatusShort === token || carouselTokens.includes(token));
            const carouselLive = carouselMatch.is_live || carouselMatch.isLive || carouselStatus.includes('live') || carouselStatus.includes('direct') || ['1h', '2h', 'ht', 'et', 'p'].some((token) => carouselStatusShort === token || carouselTokens.includes(token));
            const carouselCenter = (carouselHasScore && (carouselFinished || carouselLive))
              ? `${carouselMatch.score_home} - ${carouselMatch.score_away}`
              : formatTime(carouselMatch.kickoff_at);
            const carouselSub = carouselFinished
              ? 'Terminé'
              : (carouselLive ? 'En directo' : (picker && picker.selected ? picker.selected.label : 'Hoy'));
            const carouselHref = carouselMatchId ? `/matchs/${carouselMatchId}/analyse` : '';
          %>
            <section
              class="matches-desktop-card matches-desktop-highlight <%= slideIndex === 0 ? 'is-active' : '' %>"
              data-desktop-match-slide
              data-desktop-detail-url="<%= carouselHref %>"
              data-slide-index="<%= slideIndex %>"
              role="button"
              tabindex="0"
              aria-label="Ouvrir l’analyse <%= carouselMatch.home_team || 'Domicile' %> contre <%= carouselMatch.away_team || 'Extérieur' %>"
            >
              <header>
                <span class="matches-desktop-competition-icon" aria-hidden="true">
                  <svg viewBox="0 0 24 24">
                    <path d="M8 4h8v3a4 4 0 0 1-8 0z"></path>
                    <path d="M8 6H5a3 3 0 0 0 3 3"></path>
                    <path d="M16 6h3a3 3 0 0 1-3 3"></path>
                    <path d="M12 11v4"></path>
                    <path d="M9 20h6"></path>
                    <path d="M10 15h4l1 5H9z"></path>
                  </svg>
                </span>
                <strong><%= carouselMatch.competition_name || 'Compétition' %></strong>
              </header>
              <div class="matches-desktop-fixture">
                <span>
                  <% if (carouselMatch.home_logo) { %>
                    <img src="<%= carouselMatch.home_logo %>" alt="">
                  <% } %>
                  <strong><%= carouselMatch.home_team || 'Domicile' %></strong>
                </span>
                <time>
                  <strong><%= carouselCenter %></strong>
                  <small><%= carouselSub %></small>
                </time>
                <span>
                  <% if (carouselMatch.away_logo) { %>
                    <img src="<%= carouselMatch.away_logo %>" alt="">
                  <% } %>
                  <strong><%= carouselMatch.away_team || 'Extérieur' %></strong>
                </span>
              </div>
              <% if (carouselOdds) { %>
                <div class="matches-desktop-odds">
                  <h2>Cuotas del partido</h2>
                  <% if (carouselOdds.bookmaker) { %>
                    <b><%= carouselOdds.bookmaker %></b>
                  <% } %>
                  <span><small>1</small><strong><%= carouselOdds.home ? Number(carouselOdds.home).toFixed(2) : '-' %></strong></span>
                  <span><small>X</small><strong><%= carouselOdds.draw ? Number(carouselOdds.draw).toFixed(2) : '-' %></strong></span>
                  <span><small>2</small><strong><%= carouselOdds.away ? Number(carouselOdds.away).toFixed(2) : '-' %></strong></span>
                </div>
              <% } %>

              <article class="matches-desktop-vote" data-match-vote data-match-id="<%= carouselMatch.id || carouselMatch.api_fixture_id || '' %>">
                <header>
                  <span aria-hidden="true">♕</span>
                  <strong>Votez pour le gagnant</strong>
                  <small data-vote-total><%= desktopVoteLabel(carouselVoteStats.total) %></small>
                </header>
                <div>
                  <% [
                    { choice: 'home', side: 'home', logo: carouselMatch.home_logo, label: carouselMatch.home_team },
                    { choice: 'draw', side: 'draw', logo: '', label: 'Nul' },
                    { choice: 'away', side: 'away', logo: carouselMatch.away_logo, label: carouselMatch.away_team }
                  ].forEach((item) => {
                    const option = desktopVoteOption(carouselVoteStats, item.choice);
                    const percent = desktopVotePercent(option.percent);
                  %>
                    <button class="matches-desktop-vote-option is-<%= item.side %> <%= carouselVoteStats.selected === item.choice ? 'is-selected' : '' %>" type="button" data-vote-choice="<%= item.choice %>" aria-label="Voter <%= item.label %>">
                      <i data-vote-fill style="height:<%= percent %>%"></i>
                      <small data-vote-count><%= desktopVoteLabel(option.count) %></small>
                      <% if (item.choice === 'draw') { %>
                        <b aria-hidden="true">×</b>
                      <% } else if (item.logo) { %>
                        <img src="<%= item.logo %>" alt="">
                      <% } else { %>
                        <b><%= initials(item.label) %></b>
                      <% } %>
                      <strong data-vote-percent><%= percent %>%</strong>
                    </button>
                  <% }) %>
                </div>
              </article>

              <button class="matches-desktop-open" type="button" data-desktop-open-detail>Ouvrir l’analyse</button>
            </section>
          <% }) %>
        </div>
        <% if (desktopCarouselMatches.length > 1) { %>
          <div class="matches-desktop-dots" aria-label="Matchs du jour">
            <% desktopCarouselMatches.forEach((match, dotIndex) => { %>
              <button type="button" class="<%= dotIndex === 0 ? 'is-active' : '' %>" data-desktop-carousel-dot="<%= dotIndex %>" aria-label="Voir le match <%= dotIndex + 1 %>"></button>
            <% }) %>
          </div>
        <% } %>
      </div>

      <% if (desktopRecommendations.length) { %>
        <section class="matches-desktop-recommendations recommendations-day-list" aria-label="Top avis IA TopStats">
          <header class="matches-desktop-recommendations-title">
            <span>Avis IA TopStats</span>
            <strong>Top 3 du jour</strong>
          </header>
          <% desktopRecommendations.forEach((recommendation) => { %>
            <%
              const recommendationLocked = Boolean(recommendation._desktopLocked);
              const analysisId = recommendation.api_fixture_id || recommendation.fixture_id || recommendation.match_id;
              const label = recommendation.match_label || 'Match du jour';
              const teams = splitMatchLabel(label);
              const homeName = recommendation.home_team || teams[0] || label;
              const awayName = recommendation.away_team || teams[1] || '';
              const recommendationSearch = `${homeName} ${awayName} ${recommendationLocked ? '' : (recommendation.title || '')} ${recommendation.market || ''} ${recommendation.bookmaker || ''}`.toLowerCase();
            %>
            <% if (recommendationLocked) { %>
              <article
                class="recommendations-day-card is-locked matches-desktop-recommendation-card"
                data-recommendation-card
                data-recommendation-search="<%= recommendationSearch %>"
                data-recommendation-probability="<%= Number(recommendation.estimated_probability || recommendation.confidence || 0) || 0 %>"
                data-recommendation-odds="<%= Number(recommendation.odds || 0) || 0 %>"
                data-recommendation-match="<%= `${homeName} ${awayName}`.toLowerCase() %>"
              >
                <div class="recommendations-day-match">
                  <span>
                    <% if (recommendation.home_logo) { %><img src="<%= recommendation.home_logo %>" alt=""><% } else { %><em><%= initials(homeName) %></em><% } %>
                    <% if (awayName) { %>
                      <% if (recommendation.away_logo) { %><img src="<%= recommendation.away_logo %>" alt=""><% } else { %><em><%= initials(awayName) %></em><% } %>
                    <% } %>
                  </span>
                  <strong><%= homeName %><% if (awayName) { %> - <%= awayName %><% } %></strong>
                </div>
                <div class="recommendations-day-locked-row">
                  <span aria-hidden="true">🔒</span>
                  <p>Signal TopStats PRO réservé</p>
                  <i aria-hidden="true">🔒</i>
                </div>
              </article>
            <% } else { %>
              <article
                class="recommendations-day-card matches-desktop-recommendation-card"
                data-recommendation-card
                data-recommendation-search="<%= recommendationSearch %>"
                data-recommendation-probability="<%= Number(recommendation.estimated_probability || recommendation.confidence || 0) || 0 %>"
                data-recommendation-odds="<%= Number(recommendation.odds || 0) || 0 %>"
                data-recommendation-match="<%= `${homeName} ${awayName}`.toLowerCase() %>"
              >
                <div class="recommendations-day-match">
                  <span>
                    <% if (recommendation.home_logo) { %><img src="<%= recommendation.home_logo %>" alt=""><% } else { %><em><%= initials(homeName) %></em><% } %>
                    <% if (awayName) { %>
                      <% if (recommendation.away_logo) { %><img src="<%= recommendation.away_logo %>" alt=""><% } else { %><em><%= initials(awayName) %></em><% } %>
                    <% } %>
                  </span>
                  <strong><%= homeName %><% if (awayName) { %> - <%= awayName %><% } %></strong>
                </div>
                <div class="recommendations-day-content">
                  <h2><%= recommendation.title %></h2>
                  <div class="recommendations-day-metrics">
                    <span>Proba <strong><%= recommendation.estimated_probability || recommendation.confidence || '-' %>%</strong></span>
                    <span>Cote <strong><%= recommendation.odds ? Number(recommendation.odds).toFixed(2) : '-' %></strong></span>
                    <% if (analysisId) { %>
                      <a class="recommendations-day-analysis" href="/matchs/<%= analysisId %>/analyse">Análisis</a>
                    <% } %>
                  </div>
                </div>
              </article>
            <% } %>
          <% }) %>
        </section>
      <% } %>

      <section class="matches-desktop-detail" data-desktop-detail hidden>
        <header>
          <button type="button" data-desktop-detail-close>‹ Volver a las vistas previas</button>
          <span data-desktop-detail-title>Análisis del partido</span>
        </header>
        <div class="matches-desktop-detail-content" data-desktop-detail-content></div>
      </section>
    </aside>
  <% } %>

  <%
    const promoSlots = Array.isArray(typeof matchesPromos !== 'undefined' ? matchesPromos : null)
      ? matchesPromos
      : ((typeof matchesPromo !== 'undefined' && matchesPromo) ? [matchesPromo] : []);
  %>
  <% if (promoSlots.length) { %>
    <section class="matches-promo-list" aria-label="Promotions">
      <% promoSlots.forEach((promo) => { %>
        <article class="matches-promo-slot">
          <a href="<%= promo.linkUrl %>" <%= promo.external ? 'target="_blank" rel="noopener noreferrer"' : '' %>>
            <img src="<%= promo.imageUrl %>" alt="<%= promo.alt %>" loading="lazy">
          </a>
        </article>
      <% }) %>
    </section>
  <% } %>
</main>

<% if (typeof showAffiliateCodePrompt !== 'undefined' && showAffiliateCodePrompt) { %>
  <section class="affiliate-code-prompt" data-affiliate-code-prompt data-endpoint="/affiliation/code-affilie" aria-modal="true" role="dialog" aria-labelledby="affiliate-code-prompt-title">
    <div class="affiliate-code-prompt-card">
      <div data-affiliate-code-question>
        <h2 id="affiliate-code-prompt-title">Avez-vous un code affilié ?</h2>
        <p>Si quelqu’un vous a invité sur TopStats, ajoutez son code maintenant. Sinon, vous pouvez fermer cette fenêtre.</p>
        <div class="affiliate-code-prompt-actions">
          <button type="button" class="affiliate-code-prompt-secondary" data-affiliate-code-no>Non</button>
          <button type="button" class="affiliate-code-prompt-primary" data-affiliate-code-yes>Oui</button>
        </div>
      </div>
      <form data-affiliate-code-form hidden>
        <label for="affiliate-code-prompt-input">Code affilié</label>
        <input id="affiliate-code-prompt-input" type="text" name="affiliate_code" placeholder="Ex : TOPSTATS-4721" autocomplete="off">
        <p class="affiliate-code-prompt-message" data-affiliate-code-message aria-live="polite"></p>
        <div class="affiliate-code-prompt-actions">
          <button type="button" class="affiliate-code-prompt-secondary" data-affiliate-code-cancel>Annuler</button>
          <button type="submit" class="affiliate-code-prompt-primary">Enregistrer</button>
        </div>
      </form>
    </div>
  </section>
<% } %>

<%- include('../partials/bottom-nav') %>
<%- include('../partials/footer') %>
