/* Version 2.1 – Stadiongrafiken und detaillierter Spielbericht */
(() => {
  const FACILITY_IMAGES = {
    vip: 'vip.png',
    business: 'business.png',
    parking: 'parking.png',
    fanshop: 'fanshop.png',
    gastro: 'gastro.png',
    museum: 'museum.png',
    solar: 'solar.png',
    floodlights: 'floodlights.png',
    training: 'training.png',
    academy: 'academy.png'
  };

  const FACILITY_EFFECTS = {
    vip: 'Höhere VIP- und Business-Einnahmen',
    business: 'Mehr Firmenkunden und Hospitality-Umsatz',
    parking: 'Bessere Erreichbarkeit und höhere Auslastung',
    fanshop: 'Mehr Fanartikelverkäufe pro Woche',
    gastro: 'Mehr Gastronomieumsatz an Heimspieltagen',
    museum: 'Wöchentliche Einnahmen und stärkere Fanbindung',
    solar: 'Reduziert laufende Energiekosten',
    floodlights: 'Verbessert Atmosphäre und TV-Einnahmen',
    training: 'Beschleunigt die Spielerentwicklung',
    academy: 'Verbessert Jugendspieler und Nachwuchsgewinnung'
  };

  function ensureReportState() {
    if (!state) return;
    state.matchReports ||= [];
  }

  function initLiveReport() {
    if (!liveMatch) return;
    ensureReportState();
    const user = liveUserClub();
    const startingFitness = {};
    user.squad.forEach(player => { startingFitness[player.id] = player.fitness; });
    liveMatch.reportData = {
      startingXI: [...liveMatch.userXI],
      startingFitness,
      playerStats: {},
      substitutions: [],
      formationStart: liveMatch.formation,
      tacticStart: liveMatch.tactic,
      aggressionStart: liveMatch.aggression
    };
    liveMatch.userXI.forEach(id => {
      liveMatch.reportData.playerStats[id] = { started: true, entered: 0, left: 90, goals: 0, shots: 0, chances: 0, cards: 0, keyActions: 0 };
    });
  }

  function statFor(playerId) {
    if (!liveMatch?.reportData || !playerId) return null;
    return liveMatch.reportData.playerStats[playerId] ||= { started: false, entered: liveMatch.minute || 0, left: 90, goals: 0, shots: 0, chances: 0, cards: 0, keyActions: 0 };
  }

  const originalStartLiveMatch = startLiveMatch;
  startLiveMatch = function (...args) {
    originalStartLiveMatch(...args);
    initLiveReport();
  };

  const originalAddLiveEvent = addLiveEvent;
  addLiveEvent = function (minute, type, text, clubId = null, playerId = null) {
    originalAddLiveEvent(minute, type, text, clubId, playerId);
    if (!liveMatch?.reportData || clubId !== state.userClubId || !playerId) return;
    const stat = statFor(playerId);
    if (!stat) return;
    if (type === 'goal') { stat.goals += 1; stat.shots += 1; stat.keyActions += 2; }
    if (type === 'chance') { stat.shots += 1; stat.chances += 1; stat.keyActions += 1; }
    if (type === 'corner') stat.keyActions += 1;
    if (type === 'yellow') stat.cards += 1;
    if (type === 'red') stat.cards += 2;
  };

  const originalSubstituteLive = substituteLive;
  substituteLive = function (outId, inId) {
    if (liveMatch?.reportData) {
      const outStat = statFor(outId);
      const inStat = statFor(inId);
      if (outStat) outStat.left = liveMatch.minute;
      if (inStat) { inStat.started = false; inStat.entered = liveMatch.minute; inStat.left = 90; }
      liveMatch.reportData.substitutions.push({ outId, inId, minute: liveMatch.minute });
    }
    originalSubstituteLive(outId, inId);
  };

  function calculatePlayerReport(player, stat, won, drew, position) {
    const minutes = Math.max(1, (stat?.left ?? 90) - (stat?.entered ?? 0));
    const basePerformance = (player.rating - 65) / 35;
    const resultBonus = won ? 0.32 : drew ? 0.08 : -0.22;
    const goalBonus = (stat?.goals || 0) * 1.15;
    const chanceBonus = (stat?.chances || 0) * 0.16;
    const keyBonus = (stat?.keyActions || 0) * 0.08;
    const cardPenalty = (stat?.cards || 0) * 0.24;
    const minutesFactor = Math.min(1, minutes / 75);
    let rating = 6.05 + basePerformance * 0.55 + resultBonus + goalBonus + chanceBonus + keyBonus - cardPenalty + (Math.random() - 0.5) * 0.55;
    if (position === 'TW') rating += Math.random() * 0.35;
    if (minutes < 20) rating = 6.0 + (rating - 6.0) * 0.45;
    rating = clamp(rating, 4.2, 9.8);

    const passBase = position === 'TW' ? 70 : ['IV', 'RV', 'LV', 'DM'].includes(position) ? 79 : ['ZM', 'RA', 'LA'].includes(position) ? 82 : 73;
    const passPct = clamp(Math.round(passBase + (player.passing || player.rating) / 10 + rand(-7, 7)), 55, 96);
    const passes = Math.max(4, Math.round(minutes * (position === 'ZM' || position === 'DM' ? 0.72 : position === 'ST' ? 0.32 : 0.53)));
    const duels = Math.max(1, Math.round(minutes * (['IV', 'RV', 'LV', 'DM'].includes(position) ? 0.13 : 0.08)));
    const duelsWon = clamp(Math.round(duels * (0.42 + (player.tackling || player.rating) / 220 + rand(-8, 8) / 100)), 0, duels);
    const fitnessBefore = liveMatch.reportData.startingFitness[player.id] ?? player.fitness;
    const fitnessLoss = Math.max(0, fitnessBefore - player.fitness);

    return {
      id: player.id,
      name: player.name,
      position,
      minutes,
      rating: Number(rating.toFixed(1)),
      goals: stat?.goals || 0,
      shots: stat?.shots || 0,
      passPct,
      passes,
      duelsWon,
      duels,
      cards: stat?.cards || 0,
      fitnessLoss,
      substitute: !(stat?.started)
    };
  }

  function buildMatchReport() {
    if (!liveMatch?.reportData) return null;
    const user = liveUserClub();
    const userGoals = liveMatch.userHome ? liveMatch.homeGoals : liveMatch.awayGoals;
    const opponentGoals = liveMatch.userHome ? liveMatch.awayGoals : liveMatch.homeGoals;
    const won = userGoals > opponentGoals;
    const drew = userGoals === opponentGoals;
    const ids = [...new Set([
      ...liveMatch.reportData.startingXI,
      ...liveMatch.reportData.substitutions.map(s => s.inId)
    ])];
    const players = ids.map(id => {
      const player = user.squad.find(p => p.id === id);
      return player ? calculatePlayerReport(player, liveMatch.reportData.playerStats[id], won, drew, player.position) : null;
    }).filter(Boolean).sort((a, b) => b.rating - a.rating);
    const manOfMatch = players[0] || null;
    const userShots = players.reduce((sum, p) => sum + p.shots, 0) + rand(2, 6);
    const opponentShots = Math.max(3, Math.round(userShots * (liveMatch.userHome ? liveMatch.awayPower / liveMatch.homePower : liveMatch.homePower / liveMatch.awayPower) + rand(-2, 3)));
    const possession = clamp(Math.round(50 + ((liveMatch.userHome ? liveMatch.homePower - liveMatch.awayPower : liveMatch.awayPower - liveMatch.homePower) * 0.55) + rand(-5, 5)), 31, 69);
    const report = {
      id: uid(),
      season: state.season,
      week: state.week,
      homeId: liveMatch.home.id,
      awayId: liveMatch.away.id,
      home: liveMatch.home.name,
      away: liveMatch.away.name,
      score: `${liveMatch.homeGoals}:${liveMatch.awayGoals}`,
      userGoals,
      opponentGoals,
      formationStart: liveMatch.reportData.formationStart,
      formationEnd: liveMatch.formation,
      tacticStart: liveMatch.reportData.tacticStart,
      tacticEnd: liveMatch.tactic,
      aggression: liveMatch.aggression,
      players,
      manOfMatch,
      stats: {
        possession,
        shots: userShots,
        opponentShots,
        shotsOnTarget: Math.max(userGoals, Math.round(userShots * 0.43)),
        opponentShotsOnTarget: Math.max(opponentGoals, Math.round(opponentShots * 0.4)),
        corners: liveMatch.events.filter(e => e.type === 'corner' && e.clubId === user.id).length,
        opponentCorners: liveMatch.events.filter(e => e.type === 'corner' && e.clubId !== user.id).length,
        cards: liveMatch.userHome ? liveMatch.yellowHome + liveMatch.redHome : liveMatch.yellowAway + liveMatch.redAway,
        opponentCards: liveMatch.userHome ? liveMatch.yellowAway + liveMatch.redAway : liveMatch.yellowHome + liveMatch.redHome
      },
      finance: { ...liveMatch.finance }
    };
    return report;
  }

  function reportRow(player, isBest) {
    const cardText = player.cards >= 2 ? '🟥' : player.cards === 1 ? '🟨' : '–';
    return `<tr class="${isBest ? 'report-best-player' : ''}">
      <td>${isBest ? '⭐ ' : ''}${esc(player.name)}${player.substitute ? ' <small>(E)</small>' : ''}</td>
      <td>${player.position}</td>
      <td>${player.minutes}'</td>
      <td><b class="rating rating-${Math.floor(player.rating)}">${player.rating.toFixed(1)}</b></td>
      <td>${player.goals || '–'}</td>
      <td>${player.shots}</td>
      <td>${player.passes} (${player.passPct}%)</td>
      <td>${player.duelsWon}/${player.duels}</td>
      <td>${cardText}</td>
      <td>−${player.fitnessLoss}</td>
    </tr>`;
  }

  function matchReportHtml() {
    const report = liveMatch?.completedReport;
    if (!report) return `<div class="card"><h2>Spielbericht konnte nicht erstellt werden</h2><button id="continueAfterMatch" class="primary">Weiter</button></div>`;
    const home = getClub(report.homeId);
    const away = getClub(report.awayId);
    const resultText = report.userGoals > report.opponentGoals ? 'Sieg' : report.userGoals === report.opponentGoals ? 'Unentschieden' : 'Niederlage';
    return `<section class="match-report-page">
      <div class="card report-hero">
        <div>${clubCrest(home, 'large')}<b>${esc(report.home)}</b></div>
        <div><span class="viz-badge">SPIELBERICHT</span><div class="report-score">${esc(report.score)}</div><small>${resultText} · Saison ${report.season}, Spielwoche ${report.week}</small></div>
        <div>${clubCrest(away, 'large')}<b>${esc(report.away)}</b></div>
      </div>
      <div class="grid cols-4 report-metrics">
        <div class="metric-card"><span>Ballbesitz</span><div class="viz-stat-value">${report.stats.possession}%</div></div>
        <div class="metric-card"><span>Schüsse</span><div class="viz-stat-value">${report.stats.shots}:${report.stats.opponentShots}</div></div>
        <div class="metric-card"><span>Auf das Tor</span><div class="viz-stat-value">${report.stats.shotsOnTarget}:${report.stats.opponentShotsOnTarget}</div></div>
        <div class="metric-card"><span>Ecken</span><div class="viz-stat-value">${report.stats.corners}:${report.stats.opponentCorners}</div></div>
      </div>
      <div class="grid cols-3 report-summary-grid">
        <div class="card"><h2>Traineranalyse</h2><p><b>Formation:</b> ${report.formationStart}${report.formationStart !== report.formationEnd ? ` → ${report.formationEnd}` : ''}</p><p><b>Taktik:</b> ${esc(report.tacticStart)} → ${esc(report.tacticEnd)}</p><p><b>Zweikämpfe:</b> ${esc(report.aggression)}</p><p>${report.userGoals > report.opponentGoals ? 'Die Mannschaft setzte die Vorgaben insgesamt erfolgreich um.' : report.userGoals === report.opponentGoals ? 'Das Spiel war ausgeglichen; kleine Anpassungen hätten den Ausschlag geben können.' : 'Die Mannschaft konnte ihre Chancen nicht konsequent genug nutzen.'}</p></div>
        <div class="card report-motm"><h2>Spieler des Spiels</h2>${report.manOfMatch ? `<div class="motm-rating">${report.manOfMatch.rating.toFixed(1)}</div><b>${esc(report.manOfMatch.name)}</b><p>${report.manOfMatch.goals ? `${report.manOfMatch.goals} Tor(e), ` : ''}${report.manOfMatch.passPct}% Passquote</p>` : '<p>–</p>'}</div>
        <div class="card"><h2>Spieltagsfinanzen</h2><p>Einnahmen: <b class="good">${money(report.finance.totalIncome || 0)}</b></p><p>Kosten: <b class="bad">− ${money(report.finance.matchCosts || 0)}</b></p><p>Saldo: <b class="${report.finance.netIncome >= 0 ? 'good' : 'bad'}">${money(report.finance.netIncome || 0)}</b></p></div>
      </div>
      <div class="card report-table-card"><h2>Spielerbewertungen</h2><div class="table-scroll"><table><thead><tr><th>Spieler</th><th>Pos</th><th>Min.</th><th>Note</th><th>Tore</th><th>Schüsse</th><th>Pässe</th><th>Zweikämpfe</th><th>Karten</th><th>Fitness</th></tr></thead><tbody>${report.players.map((p, i) => reportRow(p, i === 0)).join('')}</tbody></table></div></div>
      <div class="card report-finance-detail"><h2>Finanzabschluss</h2>${financeBreakdownHtml(report.finance)}<button id="continueAfterMatch" class="primary big">Spielbericht schließen & weiter</button></div>
    </section>`;
  }

  const originalFinishLiveMatch = finishLiveMatch;
  finishLiveMatch = function (...args) {
    if (!liveMatch || liveMatch.finished) return originalFinishLiveMatch(...args);
    originalFinishLiveMatch(...args);
    const report = buildMatchReport();
    if (report && liveMatch) {
      liveMatch.completedReport = report;
      state.matchReports.unshift(report);
      state.matchReports = state.matchReports.slice(0, 30);
      save();
      view = 'live';
      render();
    }
  };

  const originalLiveView = liveView;
  liveView = function () {
    if (liveMatch?.finished && liveMatch.completedReport) return matchReportHtml();
    return originalLiveView();
  };

  v20Stadium = function () {
    ensureV20State();
    const club = getUserClub();
    const stadium = club.stadium;
    const facilities = state.v20.facilities;
    const expectedAttendance = Math.round(stadium.capacity * 0.72);
    const expectedGastro = Math.round(expectedAttendance * (9.5 + (facilities.gastro || 0) * 2));
    return `<section class="stadium-upgrade-page">
      <div class="grid cols-2 stadium-overview-grid">
        <div class="card stadium-main-card"><img src="assets/stadium-upgrades/stadium-overview.png" alt="Stadion und Vereinsgelände" class="stadium-upgrade-main"><div class="stadium-overlay"><h2>${esc(stadium.name)}</h2><p>${stadium.capacity.toLocaleString('de-DE')} Plätze · Zustand ${stadium.condition}%</p></div></div>
        <div class="card"><h2>Stadionkennzahlen</h2><p>Erwartete Zuschauer: <b>${expectedAttendance.toLocaleString('de-DE')}</b></p><p>Erwarteter Gastroverkauf: <b>${money(expectedGastro)}</b></p><p>Ticketpreis: <b>${money(stadium.ticketPrice)}</b></p><label>Ticketpreis<input id="ticketPrice" type="range" min="10" max="100" value="${stadium.ticketPrice}"><span id="ticketPriceLabel"> ${money(stadium.ticketPrice)}</span></label><hr><p>Kapazitätsausbau um 5.000 Plätze: <b>${money(12000000)}</b></p><button id="upgradeStadium">Kapazität ausbauen</button></div>
      </div>
      <div class="card"><h2>Stadion- und Vereinsausbau</h2><div class="stadium-facility-gallery">${Object.entries(V20_FACILITIES).map(([key, name]) => {
        const level = facilities[key] || 0;
        const cost = (level + 1) * 1500000;
        return `<article class="stadium-facility-card"><img src="assets/stadium-upgrades/${FACILITY_IMAGES[key]}" alt="${esc(name)}"><div class="facility-card-body"><h3>${esc(name)}</h3><div class="facility-level">Stufe ${level}/5</div><p>${FACILITY_EFFECTS[key]}</p><b>${level >= 5 ? 'Voll ausgebaut' : money(cost)}</b><button data-facility="${key}" ${level >= 5 ? 'disabled' : ''}>${level >= 5 ? 'Maximalstufe' : 'Ausbauen'}</button></div></article>`;
      }).join('')}</div></div>
    </section>`;
  };

  const originalEnsureV20State = ensureV20State;
  ensureV20State = function () {
    originalEnsureV20State();
    ensureReportState();
  };

  const originalRender = render;
  render = function () {
    originalRender();
    if (state) $('#seasonLabel').textContent = `Saison ${state.season} · Woche ${state.week} · ${state.league.country} · ${state.league.name} · Version 2.1`;
  };
})();
