<%
  const matchId = match.api_fixture_id || match.id;
  const rawStatus = String(`${match.status || ''} ${match.status_short || ''}`).toLowerCase();
  const rawStatusShort = String(match.status_short || '').toLowerCase();
  const statusTokens = rawStatus.split(/\s+/).filter(Boolean);
  const matchFilterDay = (() => {
    const kickoffDate = match.kickoff_at ? new Date(match.kickoff_at) : null;
    if (!kickoffDate || Number.isNaN(kickoffDate.getTime())) return '';
    const parts = new Intl.DateTimeFormat('en-CA', {
      timeZone: 'Europe/Paris',
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      hour12: false
    }).formatToParts(kickoffDate).reduce((acc, part) => {
      if (part.type !== 'literal') acc[part.type] = part.value;
      return acc;
    }, {});
    const localDateIso = `${parts.year}-${parts.month}-${parts.day}`;
    const localHour = Number(parts.hour === '24' ? 0 : parts.hour);
    if (Number.isFinite(localHour) && localHour < 6) {
      const previousDay = new Date(`${localDateIso}T12:00:00Z`);
      previousDay.setUTCDate(previousDay.getUTCDate() - 1);
      return previousDay.toISOString().slice(0, 10);
    }
    return localDateIso;
  })();
  const hasScore = match.score_home !== null && match.score_home !== undefined && match.score_away !== null && match.score_away !== undefined;
  const homeScore = hasScore ? Number(match.score_home) : null;
  const awayScore = hasScore ? Number(match.score_away) : null;
  const isHalftime = rawStatusShort === 'ht' || statusTokens.includes('ht') || rawStatus.includes('mi-temps') || rawStatus.includes('halftime');
  const isLive = match.is_live || match.isLive || rawStatus.includes('live') || rawStatus.includes('direct') || ['1h', '2h', 'ht', 'et', 'p'].some((token) => rawStatusShort === token || statusTokens.includes(token));
  const isFinished = match.is_finished || match.isFinished || ['ft', 'aet', 'pen', 'terminé', 'termine', 'finished'].some((token) => rawStatusShort === token || statusTokens.includes(token));
  const homeWon = isFinished && hasScore && homeScore > awayScore;
  const drawWon = isFinished && hasScore && homeScore === awayScore;
  const awayWon = isFinished && hasScore && awayScore > homeScore;
  const liveElapsedRaw = match.status_elapsed ?? match.elapsed ?? match.minute ?? null;
  const liveExtraRaw = match.status_extra ?? match.extra ?? match.added_time ?? match.addedTime ?? null;
  const liveElapsedValue = Number(liveElapsedRaw);
  const liveExtraValue = Number(liveExtraRaw);
  const liveElapsed = Number.isFinite(liveElapsedValue) ? Math.max(0, liveElapsedValue) : null;
  const liveExtra = Number.isFinite(liveExtraValue) ? Math.max(0, liveExtraValue) : 0;
  const statusLabel = isHalftime ? 'MT' : (isLive ? `${liveElapsed !== null ? liveElapsed : 0}'` : (isFinished ? 'FT' : formatTime(match.kickoff_at)));
  const analysisHref = matchId ? `/matchs/${matchId}/analyse` : '/matchs';
  const odds = match.odds_1x2 || null;
  const favoriteCandidates = [match.api_fixture_id, match.fixture_id, match.favorite_external_id, match.id]
    .map((value) => String(value || '').trim())
    .filter(Boolean);
  const favoriteExternalId = favoriteCandidates[0] || '';
  const favoriteSet = typeof favoriteMatchIds !== 'undefined' && favoriteMatchIds ? favoriteMatchIds : null;
  const isFavorite = Boolean(match.is_favorite) || Boolean(favoriteSet && favoriteCandidates.some((candidate) => favoriteSet.has(candidate)));
%>

<a
  class="app-match-row <%= odds ? 'has-odds' : '' %> <%= isLive ? 'is-live' : '' %> <%= isFinished ? 'is-finished' : '' %>"
  href="<%= analysisHref %>"
  data-match-row
  data-match-status="<%= isLive ? 'live' : (isFinished ? 'finished' : 'upcoming') %>"
  data-match-day="<%= matchFilterDay %>"
  data-match-search="<%= `${match.home_team || ''} ${match.away_team || ''} ${match.competition_name || ''}`.toLowerCase() %>"
>
  <span class="app-match-status">
    <% if (isHalftime) { %>
      <span class="app-match-live-time"><%= statusLabel %></span>
    <% } else if (isLive && liveExtra > 0) { %>
      <span class="app-match-live-time has-extra"><b><%= liveElapsed !== null ? liveElapsed : 0 %>'</b><em>+<%= String(liveExtra).padStart(2, '0') %></em></span>
    <% } else if (isLive) { %>
      <span class="app-match-live-time"><%= statusLabel %></span>
    <% } else { %>
      <%= statusLabel %>
    <% } %>
  </span>
  <span class="app-match-teams">
    <span class="app-match-team <%= homeWon ? 'is-winner' : '' %>">
      <span class="app-team-flag">
        <% if (match.home_logo) { %>
          <img src="<%= match.home_logo %>" alt="">
        <% } else { %>
          <em><%= initials(match.home_team) %></em>
        <% } %>
      </span>
      <strong><%= match.home_team || 'Domicile' %></strong>
    </span>
    <span class="app-match-team <%= awayWon ? 'is-winner' : '' %>">
      <span class="app-team-flag">
        <% if (match.away_logo) { %>
          <img src="<%= match.away_logo %>" alt="">
        <% } else { %>
          <em><%= initials(match.away_team) %></em>
        <% } %>
      </span>
      <strong><%= match.away_team || 'Extérieur' %></strong>
    </span>
  </span>
  <% if (odds) { %>
    <span class="app-match-odds" data-match-odds>
      <em><small>1</small><strong class="<%= homeWon ? 'is-winning-odd-value' : '' %>"><%= odds.home ? Number(odds.home).toFixed(2) : '-' %></strong></em>
      <em><small>X</small><strong class="<%= drawWon ? 'is-winning-odd-value' : '' %>"><%= odds.draw ? Number(odds.draw).toFixed(2) : '-' %></strong></em>
      <em><small>2</small><strong class="<%= awayWon ? 'is-winning-odd-value' : '' %>"><%= odds.away ? Number(odds.away).toFixed(2) : '-' %></strong></em>
    </span>
  <% } %>
  <span class="app-match-score <%= hasScore ? '' : 'is-empty' %>">
    <% if (hasScore) { %>
      <strong><%= match.score_home %></strong>
      <strong><%= match.score_away %></strong>
    <% } %>
  </span>
  <span
    class="app-match-star <%= isFavorite ? 'is-favorite' : '' %>"
    role="button"
    tabindex="0"
    aria-label="<%= isFavorite ? 'Retirer des favoris' : 'Ajouter aux favoris' %>"
    aria-pressed="<%= isFavorite ? 'true' : 'false' %>"
    data-favorite-toggle
    data-favorite-url="/favoris/match/toggle"
    data-favorite-type="match"
    data-favorite-id="<%= favoriteExternalId %>"
    data-favorite-match-id="<%= match.id || '' %>"
    data-favorite-api-fixture-id="<%= match.api_fixture_id || match.fixture_id || '' %>"
    data-favorite-label="<%= `${match.home_team || 'Domicile'} - ${match.away_team || 'Extérieur'}` %>"
    data-favorite-competition-name="<%= match.competition_name || '' %>"
    data-favorite-country="<%= match.country || '' %>"
    data-favorite-kickoff-at="<%= match.kickoff_at || '' %>"
    data-favorite-status="<%= match.status || '' %>"
    data-favorite-status-short="<%= match.status_short || '' %>"
    data-favorite-status-elapsed="<%= match.status_elapsed ?? '' %>"
    data-favorite-status-extra="<%= match.status_extra ?? '' %>"
    data-favorite-home-team="<%= match.home_team || '' %>"
    data-favorite-away-team="<%= match.away_team || '' %>"
    data-favorite-home-logo="<%= match.home_logo || '' %>"
    data-favorite-away-logo="<%= match.away_logo || '' %>"
    data-favorite-score-home="<%= match.score_home ?? '' %>"
    data-favorite-score-away="<%= match.score_away ?? '' %>"
    data-favorite-is-live="<%= isLive ? 'true' : 'false' %>"
    data-favorite-is-finished="<%= isFinished ? 'true' : 'false' %>"
  ><%= isFavorite ? '★' : '☆' %></span>
</a>
