/* Football Manager Retro v4.8 - Animierte Spielszenen */
(() => {
  const VIDEO_BASE = 'videos/';
  let sceneOpen = false;
  let sceneSeq = 0;

  const sceneLabels = {
    '90mingoal.mp4':'Tor in der Schlussphase',
    'classicgoal.mp4':'Tor',
    'headergoal.mp4':'Kopfballtor',
    'freekickgoal.mp4':'Freistoßtor',
    'penaltygoal.mp4':'Elfmetertor',
    'defongoal.mp4':'Eigentor',
    'countergoal.mp4':'Kontertor',
    'conternogoal.mp4':'Konter - Torwart hält',
    'bigsave.mp4':'Starke Parade',
    'lastminutesave.mp4':'Parade in der Schlussphase',
    'penaltymiss.mp4':'Elfmeter vergeben',
    'bigchance.mp4':'Großchance',
    'cornerchance.mp4':'Gefährliche Ecke',
    'redcard.mp4':'Rote Karte',
    'yellowcard.mp4':'Gelbe Karte',
    'foul.mp4':'Foulspiel'
  };

  function escScene(v){
    return String(v == null ? '' : v).replace(/[&<>\"']/g, ch => ({'&':'&amp;','<':'&lt;','>':'&gt;','\"':'&quot;',"'":'&#039;'}[ch]));
  }

  function recentText(){
    if(typeof liveMatch === 'undefined' || !liveMatch || !Array.isArray(liveMatch.events)) return '';
    return liveMatch.events.slice(0,5).map(e=>String(e.text||'')).join(' ').toLowerCase();
  }

  function chooseScene(minute,type,text){
    const t=String(text||'').toLowerCase();
    const recent=recentText();
    if(type==='owngoal' || t.includes('eigentor')) return 'defongoal.mp4';
    if(type==='goal'){
      if(t.includes('elfmeter') || t.includes('elfmeterpunkt')) return 'penaltygoal.mp4';
      if(t.includes('freistoß') || t.includes('freistoss')) return 'freekickgoal.mp4';
      if(t.includes('köpf') || t.includes('kopfball')) return 'headergoal.mp4';
      if(t.includes('konter') || recent.includes('konter')) return 'countergoal.mp4';
      if(Number(minute)>=88) return '90mingoal.mp4';
      return 'classicgoal.mp4';
    }
    if(type==='save'){
      if(t.includes('elfmeter') || recent.includes('elfmeter')) return 'penaltymiss.mp4';
      if(recent.includes('konter')) return 'conternogoal.mp4';
      if(Number(minute)>=85) return 'lastminutesave.mp4';
      return Math.random()<0.48 ? 'bigsave.mp4' : null;
    }
    if(type==='chance') return Math.random()<0.20 ? 'bigchance.mp4' : null;
    if(type==='corner') return Math.random()<0.18 ? 'cornerchance.mp4' : null;
    if(type==='red') return 'redcard.mp4';
    if(type==='yellow') return Math.random()<0.18 ? 'yellowcard.mp4' : null;
    if(type==='foul') return Math.random()<0.22 ? 'foul.mp4' : null;
    return null;
  }

  function sceneComment(file,minute,text){
    const label=sceneLabels[file]||'Spielszene';
    const suffix=Number(minute)>=88?' in einer dramatischen Schlussphase':'';
    if(file==='conternogoal.mp4') return `🎬 ${label}: Schneller Gegenstoß${suffix}, doch der Torwart bleibt Sieger.`;
    if(file==='defongoal.mp4') return `🎬 ${label}: Unglückliche Abwehraktion - der Ball landet im eigenen Tor.`;
    if(file==='90mingoal.mp4') return `🎬 ${label}: Was für ein Moment - der Treffer fällt praktisch mit dem Schlusspfiff!`;
    if(file==='freekickgoal.mp4') return `🎬 ${label}: Der Standard sitzt perfekt.`;
    if(file==='headergoal.mp4') return `🎬 ${label}: Flanke, Kopfball, Tor - stark ausgeführt.`;
    if(file==='penaltygoal.mp4') return `🎬 ${label}: Der Schütze behält die Nerven.`;
    if(file==='penaltymiss.mp4') return `🎬 ${label}: Riesenchance vom Punkt, aber kein Tor.`;
    if(file==='redcard.mp4') return `🎬 ${label}: Die Partie bekommt eine neue Dynamik.`;
    return `🎬 ${label}: ${String(text||'Die Szene wird in der Wiederholung gezeigt.').replace(/^TOR[^!]*!\s*/i,'')}`;
  }

  function removeSceneOverlay(){
    document.querySelectorAll('.match-scene-overlay').forEach(el=>el.remove());
  }

  function showGoalCelebration(done){
    removeSceneOverlay();
    const overlay=document.createElement('div');
    overlay.className='match-scene-overlay goal-celebration-overlay';
    overlay.innerHTML=`<div class="goal-celebration-card"><img src="assets/match-scenes/toooor.png" alt="TOOOOOR!"/><div class="goal-celebration-score">${typeof liveMatch!=='undefined'&&liveMatch?`${liveMatch.homeGoals} : ${liveMatch.awayGoals}`:''}</div></div>`;
    document.body.appendChild(overlay);
    window.setTimeout(()=>{overlay.remove(); if(done)done();},1650);
  }

  function showScene(file,minute,type,text,clubId,playerId,emitEvent){
    if(sceneOpen || typeof liveMatch==='undefined' || !liveMatch) {
      if(typeof emitEvent==='function') emitEvent();
      return;
    }
    sceneOpen=true;
    const thisSeq=++sceneSeq;
    const wasPaused=!!liveMatch.paused;
    liveMatch.paused=true;

    const overlay=document.createElement('div');
    overlay.className='match-scene-overlay spoiler-free-scene';
    overlay.innerHTML=`
      <div class="match-scene-modal spoiler-free-modal" role="dialog" aria-modal="true" aria-label="Live-Spielszene">
        <button class="match-scene-close spoiler-free-close" type="button" aria-label="Szene überspringen">×</button>
        <video class="match-scene-video spoiler-free-video" src="${VIDEO_BASE+encodeURIComponent(file)}" autoplay playsinline controls preload="auto" aria-label="Animierte Live-Spielszene"></video>
        <div class="match-scene-loading spoiler-free-loading" aria-live="polite"><span class="scene-spinner"></span></div>
      </div>`;
    document.body.appendChild(overlay);

    const video=overlay.querySelector('video');
    const loading=overlay.querySelector('.match-scene-loading');
    let closed=false;
    let emitted=false;

    const revealEvent=()=>{
      if(emitted) return;
      emitted=true;
      if(typeof emitEvent==='function') emitEvent();
    };

    const resumeMatch=()=>{
      sceneOpen=false;
      if(typeof liveMatch!=='undefined' && liveMatch && !liveMatch.finished && !wasPaused) liveMatch.paused=false;
    };

    const finish=()=>{
      if(closed || thisSeq!==sceneSeq) return;
      closed=true;
      const isGoal=type==='goal'||type==='owngoal';
      overlay.remove();

      // Erst NACH der Szene erfährt der Spieler, was passiert ist.
      revealEvent();

      if(isGoal) showGoalCelebration(resumeMatch);
      else resumeMatch();
    };

    overlay.querySelector('.match-scene-close').onclick=finish;
    video.onloadeddata=()=>{
      if(loading) loading.hidden=true;
      video.play().catch(()=>{});
    };
    video.onended=finish;
    video.onerror=()=>{
      // Fehlende Videos sind optional: Ereignis normal anzeigen und weiterspielen.
      if(closed || thisSeq!==sceneSeq) return;
      closed=true;
      overlay.remove();
      revealEvent();
      if(type==='goal'||type==='owngoal') showGoalCelebration(resumeMatch);
      else resumeMatch();
    };
  }

  // Hook: Bei einer Video-Szene wird das eigentliche Ereignis bis zum Videoende zurückgehalten.
  // So verraten weder Live-Ticker noch Popup vorab, ob Tor, Parade, Karte usw. folgt.
  if(typeof addLiveEvent==='function'){
    const baseAddLiveEvent=addLiveEvent;
    addLiveEvent=function(minute,type,text,clubId=null,playerId=null){
      if(typeof liveMatch==='undefined'||!liveMatch||liveMatch.finished||sceneOpen){
        baseAddLiveEvent(minute,type,text,clubId,playerId);
        return;
      }

      const file=chooseScene(minute,type,text);
      if(!file){
        baseAddLiveEvent(minute,type,text,clubId,playerId);
        return;
      }

      let emitted=false;
      const emitAfterScene=()=>{
        if(emitted) return;
        emitted=true;
        baseAddLiveEvent(minute,type,text,clubId,playerId);
        baseAddLiveEvent(minute,'scene',sceneComment(file,minute,text),clubId,playerId);
      };

      window.setTimeout(()=>showScene(file,minute,type,text,clubId,playerId,emitAfterScene),30);
    };
  }

  // Very rare own goal so the corresponding animation can naturally occur.
  if(typeof processLiveMinute==='function'){
    const baseProcessLiveMinute=processLiveMinute;
    processLiveMinute=function(){
      if(typeof liveMatch!=='undefined' && liveMatch && liveMatch.minute>4 && liveMatch.minute<90 && Math.random()<0.00042){
        const ownTeam=Math.random()<0.5?liveMatch.home:liveMatch.away;
        const defenders=(ownTeam.squad||[]).filter(p=>['IV','LV','RV','ABW'].includes(p.position));
        const p=defenders[Math.floor(Math.random()*Math.max(1,defenders.length))]||ownTeam.squad?.[0];
        if(ownTeam.id===liveMatch.home.id) liveMatch.awayGoals++; else liveMatch.homeGoals++;
        addLiveEvent(liveMatch.minute,'owngoal',`Eigentor! ${p?.name||'Ein Verteidiger'} lenkt den Ball unglücklich ins eigene Netz.`,ownTeam.id,p?.id);
        return;
      }
      return baseProcessLiveMinute();
    };
  }

  window.FMMatchScenes={showScene,chooseScene,sceneLabels,videoBase:VIDEO_BASE};
})();
