// ─── Football Logo SVG ───────────────────────────────────────
// ─── WingedLogo — Football mit blau/rot Splash-Trails (matching icon.svg) ─
function WingedLogo({ size = 120, accent = '#00f5ff' }) {
  // Container-Geometrie: Ball mittig, Splash-Trails seitlich
  const trailSpan = size * 1.3;
  const W = size + trailSpan * 2;
  const H = size * 1.5;
  const cy = H / 2;
  const ballCenterX = W / 2;

  const idGlow = `wgGl_${size}`;
  const idBlue = `wgBlue_${size}`;
  const idRed  = `wgRed_${size}`;

  // Anker-Punkte für Trails (am Ball-Rand)
  const leftAnchor  = ballCenterX - size * 0.35;
  const rightAnchor = ballCenterX + size * 0.35;

  return (
    <div style={{ position:'relative', width:W, height:H, display:'inline-block' }}>
      <style>{`
        @keyframes splashSwayL_${size} { 0%,100% { transform: translateX(0) rotate(-2deg); opacity:0.92 } 50% { transform: translateX(-3px) rotate(-4deg); opacity:1 } }
        @keyframes splashSwayR_${size} { 0%,100% { transform: translateX(0) rotate(2deg); opacity:0.92 } 50% { transform: translateX(3px) rotate(4deg); opacity:1 } }
        @keyframes splashDrop_${size} { 0%,100% { opacity:0.55; transform: translateY(0) } 50% { opacity:1; transform: translateY(-3px) } }
      `}</style>

      <svg width={W} height={H} viewBox={`0 0 ${W} ${H}`} style={{ position:'absolute', inset:0, zIndex:1, overflow:'visible' }}>
        <defs>
          {/* Blue Trail Gradient */}
          <linearGradient id={idBlue} x1="100%" y1="20%" x2="0%" y2="80%">
            <stop offset="0%"  stopColor="#5ee7ff" stopOpacity="1"/>
            <stop offset="40%" stopColor="#3aa8ff" stopOpacity="0.95"/>
            <stop offset="100%" stopColor="#0a4fff" stopOpacity="0"/>
          </linearGradient>
          {/* Red Trail Gradient */}
          <linearGradient id={idRed} x1="0%" y1="20%" x2="100%" y2="80%">
            <stop offset="0%"  stopColor="#ff8898" stopOpacity="1"/>
            <stop offset="40%" stopColor="#ff3a52" stopOpacity="0.95"/>
            <stop offset="100%" stopColor="#5a0011" stopOpacity="0"/>
          </linearGradient>
          <filter id={idGlow} x="-50%" y="-50%" width="200%" height="200%">
            <feGaussianBlur stdDeviation={size * 0.04} result="b"/>
            <feMerge><feMergeNode in="b"/><feMergeNode in="SourceGraphic"/></feMerge>
          </filter>
        </defs>

        {/* ═══ BLUE SPLASH TRAIL (left) ═══ */}
        <g style={{ transformOrigin:`${leftAnchor}px ${cy}px`, animation:`splashSwayL_${size} 2.4s ease-in-out infinite` }}>
          <g filter={`url(#${idGlow})`}>
            {/* Hauptstrom */}
            <path
              d={`M ${leftAnchor} ${cy - size*0.4} Q ${leftAnchor - trailSpan*0.5} ${cy - size*0.2}, ${leftAnchor - trailSpan*0.7} ${cy + size*0.1} Q ${leftAnchor - trailSpan*0.55} ${cy + size*0.4}, ${leftAnchor - size*0.2} ${cy + size*0.45}`}
              stroke={`url(#${idBlue})`} strokeWidth={size*0.13} fill="none" strokeLinecap="round" opacity="0.92"
            />
            {/* Mittlerer Strom */}
            <path
              d={`M ${leftAnchor - size*0.05} ${cy - size*0.45} Q ${leftAnchor - trailSpan*0.6} ${cy - size*0.05}, ${leftAnchor - trailSpan*0.6} ${cy + size*0.25}`}
              stroke="#3aa8ff" strokeWidth={size*0.07} fill="none" strokeLinecap="round" opacity="0.75"
            />
            {/* Inner Highlight */}
            <path
              d={`M ${leftAnchor - size*0.1} ${cy - size*0.5} Q ${leftAnchor - trailSpan*0.35} ${cy - size*0.25}, ${leftAnchor - trailSpan*0.4} ${cy}`}
              stroke="#5ee7ff" strokeWidth={size*0.035} fill="none" strokeLinecap="round" opacity="0.95"
            />
          </g>
          {/* Splash Drops */}
          <g style={{ animation:`splashDrop_${size} 2s ease-in-out infinite` }}>
            <circle cx={leftAnchor - trailSpan*0.85} cy={cy - size*0.05} r={size*0.04} fill="#5ee7ff"/>
            <circle cx={leftAnchor - trailSpan*0.95} cy={cy + size*0.25} r={size*0.025} fill="#3aa8ff"/>
            <circle cx={leftAnchor - trailSpan*0.6} cy={cy + size*0.55} r={size*0.03} fill="#5ee7ff"/>
            <circle cx={leftAnchor - trailSpan*0.4} cy={cy - size*0.6} r={size*0.022} fill="#5ee7ff"/>
            <circle cx={leftAnchor - trailSpan*0.78} cy={cy - size*0.4} r={size*0.018} fill="#3aa8ff"/>
          </g>
        </g>

        {/* ═══ RED SPLASH TRAIL (right) ═══ */}
        <g style={{ transformOrigin:`${rightAnchor}px ${cy}px`, animation:`splashSwayR_${size} 2.4s ease-in-out infinite 0.6s` }}>
          <g filter={`url(#${idGlow})`}>
            <path
              d={`M ${rightAnchor} ${cy - size*0.4} Q ${rightAnchor + trailSpan*0.5} ${cy - size*0.2}, ${rightAnchor + trailSpan*0.7} ${cy + size*0.1} Q ${rightAnchor + trailSpan*0.55} ${cy + size*0.4}, ${rightAnchor + size*0.2} ${cy + size*0.45}`}
              stroke={`url(#${idRed})`} strokeWidth={size*0.13} fill="none" strokeLinecap="round" opacity="0.92"
            />
            <path
              d={`M ${rightAnchor + size*0.05} ${cy - size*0.45} Q ${rightAnchor + trailSpan*0.6} ${cy - size*0.05}, ${rightAnchor + trailSpan*0.6} ${cy + size*0.25}`}
              stroke="#ff3a52" strokeWidth={size*0.07} fill="none" strokeLinecap="round" opacity="0.75"
            />
            <path
              d={`M ${rightAnchor + size*0.1} ${cy - size*0.5} Q ${rightAnchor + trailSpan*0.35} ${cy - size*0.25}, ${rightAnchor + trailSpan*0.4} ${cy}`}
              stroke="#ff8898" strokeWidth={size*0.035} fill="none" strokeLinecap="round" opacity="0.95"
            />
          </g>
          <g style={{ animation:`splashDrop_${size} 2s ease-in-out infinite 0.4s` }}>
            <circle cx={rightAnchor + trailSpan*0.85} cy={cy - size*0.05} r={size*0.04} fill="#ff8898"/>
            <circle cx={rightAnchor + trailSpan*0.95} cy={cy + size*0.25} r={size*0.025} fill="#ff3a52"/>
            <circle cx={rightAnchor + trailSpan*0.6} cy={cy + size*0.55} r={size*0.03} fill="#ff8898"/>
            <circle cx={rightAnchor + trailSpan*0.4} cy={cy - size*0.6} r={size*0.022} fill="#ff8898"/>
            <circle cx={rightAnchor + trailSpan*0.78} cy={cy - size*0.4} r={size*0.018} fill="#ff3a52"/>
          </g>
        </g>
      </svg>

      {/* Football zentriert über den Trails */}
      <div style={{ position:'absolute', left:'50%', top:'50%', transform:'translate(-50%,-50%)', zIndex:3 }}>
        <FootballLogo size={size} accent={accent}/>
      </div>
    </div>
  );
}

// ─── Copyright Footer (animiert) ──────────────────────────────
function CopyrightFooter({ accent = '#00f5ff', compact = false }) {
  return (
    <>
      <style>{`
        @keyframes copyShine { 0%,100% { background-position: 0% 50% } 50% { background-position: 100% 50% } }
        @keyframes copyPulse { 0%,100% { opacity: 0.55 } 50% { opacity: 0.9 } }
      `}</style>
      <div style={{
        textAlign:'center', padding: compact ? '8px 12px' : '16px 14px',
        fontSize: compact ? 8 : 9, letterSpacing:'.16em',
        fontFamily:'JetBrains Mono', fontWeight:600,
        animation:'copyPulse 3s ease-in-out infinite',
      }}>
        <span style={{
          background: `linear-gradient(90deg, ${accent}aa 0%, #ffd700 25%, #ff6b00 50%, #ffd700 75%, ${accent}aa 100%)`,
          backgroundSize: '300% 100%',
          WebkitBackgroundClip: 'text', backgroundClip: 'text',
          WebkitTextFillColor: 'transparent', color: 'transparent',
          animation: 'copyShine 6s ease-in-out infinite',
        }}>◆ CODE & DESIGN by Maurice Putinas ◆</span>
      </div>
    </>
  );
}

// Twemoji ⚽ — Twitter's Open-Source Emoji-Set, korrekt angeordnete Pentagons +
// Hexagons (anders als das Windows Segoe-Emoji oder das Custom-SVG vorher).
// CDN-URL ist immutable → SW cached forever, kein Layout-Flash.
const TWEMOJI_BALL = 'https://cdn.jsdelivr.net/gh/twitter/twemoji@14.0.2/assets/svg/26bd.svg';

function FootballLogo({ size = 36, accent = '#00f5ff' }) {
  return (
    <img
      src={TWEMOJI_BALL}
      alt="Fußball"
      width={size}
      height={size}
      draggable={false}
      style={{
        display:'inline-block',
        flexShrink:0,
        animation:'floatBall 3.5s ease-in-out infinite',
        filter:`drop-shadow(0 ${size*.06}px ${size*.12}px rgba(0,0,0,0.55)) drop-shadow(0 0 ${size*.25}px ${accent}66)`,
        userSelect:'none',
        pointerEvents:'none',
      }}
    />
  );
}

// ─── Language Switcher ────────────────────────────────────────
function LangSwitcher({ onLangChange }) {
  const [lang, setLangState] = useState(() => localStorage.getItem('fussball_lang') || 'de');
  const langs = [{code:'de',label:'DE'},{code:'en',label:'EN'},{code:'tr',label:'TR'}];
  const handle = (code) => { setLang(code); setLangState(code); onLangChange(); };
  return (
    <div style={{display:'flex',gap:2,background:'rgba(255,255,255,0.05)',borderRadius:10,padding:'3px',border:'1px solid rgba(255,255,255,0.08)'}}>
      {langs.map(l=>(
        <button key={l.code} onClick={()=>handle(l.code)} style={{
          padding:'4px 7px',borderRadius:7,border:'none',cursor:'pointer',
          fontSize:10,fontFamily:'JetBrains Mono',fontWeight:800,letterSpacing:'.06em',
          background:lang===l.code?'rgba(0,245,255,0.2)':'transparent',
          color:lang===l.code?'#00f5ff':'rgba(255,255,255,0.38)',
          boxShadow:lang===l.code?'0 0 10px rgba(0,245,255,0.25)':'none',
          transition:'all .2s',
        }}>{l.label}</button>
      ))}
    </div>
  );
}

// ─── Odds Comparison Modal ────────────────────────────────────
function OddsComparisonModal({ match, onClose }) {
  const bk = match.bookmakerOdds || {};
  const books = [
    {name:'Tipico',key:'tipico',color:'#e30614'},
    {name:'Bet365',key:'bet365',color:'#00a651'},
    {name:'Bwin',  key:'bwin',  color:'#5b7fc7'},
    {name:'Unibet',key:'unibet',color:'#147b45'},
  ];
  const allHome = books.map(b => bk[b.key]?.home || match.odds.home);
  const allAway = books.map(b => bk[b.key]?.away || match.odds.away);
  const bestHome = Math.max(...allHome), bestAway = Math.max(...allAway);
  return (
    <div style={{position:'absolute',inset:0,background:'rgba(4,6,8,0.92)',backdropFilter:'blur(20px)',zIndex:200,display:'flex',flexDirection:'column',padding:'20px 16px',justifyContent:'center'}} onClick={onClose}>
      <NeonCard color="#ffa500" tilt={false} style={{width:'100%'}} onClick={e=>e.stopPropagation()}>
        <div style={{padding:'16px 16px 0'}}>
          <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',marginBottom:12}}>
            <div>
              <div style={{fontSize:8,color:'rgba(255,255,255,0.35)',fontFamily:'JetBrains Mono',letterSpacing:'.14em',marginBottom:3}}>QUOTEN-VERGLEICH</div>
              <div style={{fontSize:14,fontWeight:700,fontFamily:'Space Grotesk',color:'rgba(255,255,255,0.9)'}}>{match.home} vs {match.away}</div>
            </div>
            <NeonButton color="#ff0050" onClick={onClose} size="sm">✕</NeonButton>
          </div>
          <div style={{display:'grid',gridTemplateColumns:'76px 1fr 1fr 1fr',gap:5,marginBottom:10}}>
            <div/>
            {['1 HEIM','X UNENT','2 AUSW'].map(h=><div key={h} style={{textAlign:'center',fontSize:8,color:'rgba(255,255,255,0.3)',fontFamily:'JetBrains Mono',letterSpacing:'.06em'}}>{h}</div>)}
          </div>
          {books.map(b=>{
            const o=bk[b.key]||match.odds;
            return (
              <div key={b.key} style={{display:'grid',gridTemplateColumns:'76px 1fr 1fr 1fr',gap:5,marginBottom:8,alignItems:'center'}}>
                <div style={{display:'flex',alignItems:'center',gap:5}}>
                  <div style={{width:7,height:7,borderRadius:'50%',background:b.color,boxShadow:`0 0 6px ${b.color}`,flexShrink:0}}/>
                  <span style={{fontSize:10,fontFamily:'Space Grotesk',fontWeight:600,color:'rgba(255,255,255,0.7)'}}>{b.name}</span>
                </div>
                {[o.home,o.draw,o.away].map((v,i)=>{
                  const isBest=(i===0&&v===bestHome)||(i===2&&v===bestAway);
                  return (
                    <div key={i} style={{textAlign:'center',padding:'7px 4px',borderRadius:10,background:isBest?'rgba(0,255,136,0.1)':'rgba(255,255,255,0.04)',border:`1px solid ${isBest?'rgba(0,255,136,0.4)':'rgba(255,255,255,0.08)'}`}}>
                      <div style={{fontSize:14,fontWeight:800,fontFamily:'JetBrains Mono',color:isBest?'#00ff88':'#ffa500',textShadow:isBest?'0 0 12px rgba(0,255,136,0.5)':'none'}}>{(v||0).toFixed(2)}</div>
                      {isBest&&<div style={{fontSize:6,color:'#00ff88',fontFamily:'JetBrains Mono',letterSpacing:'.1em'}}>BEST</div>}
                    </div>
                  );
                })}
              </div>
            );
          })}
          <div style={{margin:'10px 0 16px',padding:'8px 10px',background:'rgba(0,255,136,0.05)',border:'1px solid rgba(0,255,136,0.15)',borderRadius:10}}>
            <span style={{fontSize:10,color:'rgba(255,255,255,0.5)',fontFamily:'Inter'}}>💡 Best Heim: <strong style={{color:'#00ff88'}}>{bestHome.toFixed(2)}</strong> · Best Ausw.: <strong style={{color:'#00ff88'}}>{bestAway.toFixed(2)}</strong></span>
          </div>
        </div>
      </NeonCard>
    </div>
  );
}

// ─── H2H Modal ────────────────────────────────────────────────
function H2HModal({ match, onClose }) {
  const [, force] = useState(0);
  // Beim Öffnen H2H-Daten ziehen falls noch nicht enriched
  useEffect(() => {
    if (!match) return;
    if (match.h2hData?.results?.length) return;
    if (window.h2hAgent) {
      window.h2hAgent.enrich(match).then(() => force(t=>t+1));
    }
  }, [match?.id]);
  const h2h = match.h2hData || {};
  const results = h2h.results || [];
  const noData = match.h2hData && (h2h.status === 'no_data' || h2h.status === 'no_espn_id') && results.length === 0;
  const loading = !match.h2hData;
  const homeW = results.filter(r=>{const g=r.score.split('-');return parseInt(g[0])>parseInt(g[1]);}).length;
  const draws  = results.filter(r=>{const g=r.score.split('-');return g[0]===g[1];}).length;
  const awayW  = results.length-homeW-draws;
  return (
    <div style={{position:'absolute',inset:0,background:'rgba(4,6,8,0.92)',backdropFilter:'blur(20px)',zIndex:200,display:'flex',flexDirection:'column',padding:'20px 16px',justifyContent:'center'}} onClick={onClose}>
      <NeonCard color="#a855f7" tilt={false} style={{width:'100%'}} onClick={e=>e.stopPropagation()}>
        <div style={{padding:'16px 16px 0'}}>
          <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',marginBottom:12}}>
            <div>
              <div style={{fontSize:8,color:'rgba(255,255,255,0.35)',fontFamily:'JetBrains Mono',letterSpacing:'.14em',marginBottom:3}}>HEAD TO HEAD</div>
              <div style={{fontSize:14,fontWeight:700,fontFamily:'Space Grotesk',color:'rgba(255,255,255,0.9)'}}>{match.home} vs {match.away}</div>
            </div>
            <NeonButton color="#ff0050" onClick={onClose} size="sm">✕</NeonButton>
          </div>
          {/* Bar distribution */}
          <div style={{display:'flex',gap:4,marginBottom:14,height:60}}>
            {[{label:match.home.split(' ')[0],val:homeW,c:'#00ff88'},{label:'Draw',val:draws,c:'rgba(255,255,255,0.3)'},{label:match.away.split(' ')[0],val:awayW,c:'#ff0050'}].map(w=>(
              <div key={w.label} style={{flex:Math.max(w.val,0.5),background:`${w.c}15`,border:`1px solid ${w.c}30`,borderRadius:12,display:'flex',flexDirection:'column',alignItems:'center',justifyContent:'center',padding:'6px 4px'}}>
                <div style={{fontSize:20,fontWeight:800,fontFamily:'JetBrains Mono',color:w.c,textShadow:`0 0 12px ${w.c}`}}>{w.val}</div>
                <div style={{fontSize:8,color:'rgba(255,255,255,0.4)',fontFamily:'JetBrains Mono',overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap',width:'100%',textAlign:'center'}}>{w.label}</div>
              </div>
            ))}
          </div>
          {/* Stats */}
          <div style={{display:'grid',gridTemplateColumns:'1fr 1fr 1fr',gap:6,marginBottom:12}}>
            {[{l:'BTTS',v:`${h2h.bttsCount||0}/${results.length}`,c:'#ff0080'},{l:'O2.5',v:`${h2h.overCount||0}/${results.length}`,c:'#a855f7'},{l:'Ø TORE',v:results.length>0?(((h2h.homeGoals||0)+(h2h.awayGoals||0))/results.length).toFixed(1):'0',c:'#ffa500'}].map(s=>(
              <StatHex key={s.l} label={s.l} value={s.v} color={s.c} />
            ))}
          </div>
          <div style={{fontSize:8,color:'rgba(255,255,255,0.25)',fontFamily:'JetBrains Mono',letterSpacing:'.12em',marginBottom:8}}>LETZTE DUELLE</div>
          {loading && <div style={{textAlign:'center',padding:'14px 0',fontSize:11,color:'rgba(255,255,255,0.4)',fontFamily:'Inter'}}>⏳ Lade Begegnungen…</div>}
          {!loading && noData && <div style={{textAlign:'center',padding:'14px 0',fontSize:11,color:'rgba(255,255,255,0.4)',fontFamily:'Inter'}}>Keine vergangenen Begegnungen verfügbar</div>}
          {results.map((r,i)=>{
            const g=r.score.split('-');const hw=parseInt(g[0])>parseInt(g[1]);const dw=g[0]===g[1];
            const c=hw?'#00ff88':dw?'rgba(255,255,255,0.4)':'#ff0050';
            return (
              <div key={i} style={{display:'flex',alignItems:'center',gap:10,padding:'8px 10px',background:'rgba(255,255,255,0.03)',borderRadius:10,border:`1px solid rgba(255,255,255,0.06)`,marginBottom:5}}>
                <LiveDot color={c} size={6}/>
                <div style={{flex:1}}>
                  <div style={{fontSize:11,fontFamily:'Space Grotesk',fontWeight:600,color:'rgba(255,255,255,0.8)'}}>{r.home} vs {r.away}</div>
                  <div style={{fontSize:8,color:'rgba(255,255,255,0.3)',fontFamily:'JetBrains Mono'}}>{r.date} · {r.competition}</div>
                </div>
                <div style={{fontSize:18,fontWeight:800,fontFamily:'JetBrains Mono',color:c,textShadow:`0 0 10px ${c}`}}>{r.score}</div>
              </div>
            );
          })}
          <div style={{height:16}}/>
        </div>
      </NeonCard>
    </div>
  );
}

// ─── Onboarding Screen ───────────────────────────────────────
function OnboardingScreen({ onDone, accent }) {
  const [phase, setPhase] = useState(0);
  // Animation läuft bis Phase 4, dann wartet die App auf Klick. KEIN Auto-Dismiss.
  useEffect(() => {
    const t = [
      setTimeout(() => setPhase(1), 300),
      setTimeout(() => setPhase(2), 900),
      setTimeout(() => setPhase(3), 1500),
      setTimeout(() => setPhase(4), 2100),
    ];
    return () => t.forEach(clearTimeout);
  }, []);

  const fade = (p, delay=0) => ({ opacity: phase >= p ? 1 : 0, transform: phase >= p ? 'translateY(0) scale(1)' : 'translateY(20px) scale(0.95)', transition: `all 0.7s ${delay}s cubic-bezier(0.23,1,0.36,1)` });

  return (
    <div style={{ position:'absolute', inset:0, zIndex:1000, background:'#040608', display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center', gap:0, overflow:'hidden' }}>
      {/* Aurora */}
      <div style={{ position:'absolute', inset:0, background:`conic-gradient(from 0deg at 50% 50%, transparent 0%, ${accent}18 30%, transparent 60%, #ff008012 80%, transparent 100%)`, animation:'auroraRotate 12s linear infinite', filter:'blur(50px)', opacity: phase >= 1 ? 1 : 0, transition:'opacity 1s' }} />
      <div style={{ position:'absolute', inset:0, background:`radial-gradient(ellipse 60% 60% at 50% 50%, ${accent}10, transparent)` }} />

      {/* Football mit Flügeln */}
      <div style={{ ...fade(1), marginBottom:28, position:'relative' }}>
        <div style={{ position:'absolute', inset:-30, borderRadius:'50%', background:`radial-gradient(circle, ${accent}30, transparent 70%)`, animation:'agentPulse 2s infinite' }} />
        <WingedLogo size={90} accent={accent}/>
      </div>

      {/* Title */}
      <div style={{ ...fade(2, .1), textAlign:'center', marginBottom:10 }}>
        <HoloText colors={[accent,'#00ff88','#ffffff',accent]} size={32} style={{ letterSpacing:'.04em', textAlign:'center' }}>FUSSBALL AI</HoloText>
      </div>

      {/* Subtitle */}
      <div style={{ ...fade(3, .1), display:'flex', flexDirection:'column', alignItems:'center', gap:8, marginBottom:36 }}>
        <div style={{ fontSize:12, color:'rgba(255,255,255,0.45)', fontFamily:'JetBrains Mono', letterSpacing:'.2em' }}>{currentLang==='tr'?'18 YAPAY ZEKA · CANLI VERİ · KELLY':currentLang==='en'?'18 AI MODELS · LIVE DATA · KELLY':'18 KI-MODELLE · LIVE DATEN · KELLY'}</div>
        <div style={{ display:'flex', gap:8 }}>
          {['🌦️ Open-Meteo','📺 ESPN','🏟️ OpenLigaDB'].map(s=>(
            <div key={s} style={{ fontSize:9, color:'rgba(255,255,255,0.3)', fontFamily:'JetBrains Mono', padding:'2px 8px', border:'1px solid rgba(255,255,255,0.08)', borderRadius:99, backdropFilter:'blur(8px)' }}>{s}</div>
          ))}
        </div>
      </div>

      {/* CTA */}
      <div style={fade(4, .1)}>
        <NeonButton color={accent} onClick={()=>{ onDone(); }} size="lg" style={{ minWidth:200, justifyContent:'center', fontSize:14 }}>
          ⚽ {currentLang==='tr' ? 'Şimdi başla' : currentLang==='en' ? 'Start now' : 'Jetzt starten'}
        </NeonButton>
      </div>

      {/* Skip */}
      <button onClick={()=>{ onDone(); }} style={{ position:'absolute', top:20, right:20, fontSize:10, color:'rgba(255,255,255,0.25)', background:'none', border:'none', cursor:'pointer', fontFamily:'JetBrains Mono' }}>{currentLang==='tr'?'ATLA':currentLang==='en'?'SKIP':'ÜBERSPRINGEN'}</button>

      {/* Copyright */}
      <div style={{ position:'absolute', bottom:60, left:0, right:0 }}>
        <CopyrightFooter accent={accent}/>
      </div>

      {/* Bottom dots */}
      <div style={{ position:'absolute', bottom:24, display:'flex', gap:6, ...fade(4,.2) }}>
        {[0,1,2,3].map(i=><div key={i} style={{ width:i===0?20:6, height:6, borderRadius:3, background:i===0?accent:'rgba(255,255,255,0.15)', transition:'all .3s' }}/>)}
      </div>
    </div>
  );
}

// ─── Smart Best Tip Calculator ───────────────────────────────
function getBestTip(match) {
  const lang = currentLang || 'de';
  const labels = {
    de: { home:'Heimsieg', draw:'Unentschieden', away:'Auswärts', btts:'Beide treffen', over:'Über 2.5 Tore', under:'Unter 2.5 Tore' },
    en: { home:'Home Win', draw:'Draw', away:'Away Win', btts:'Both Score', over:'Over 2.5', under:'Under 2.5' },
    tr: { home:'Ev Sahibi', draw:'Beraberlik', away:'Deplasman', btts:'KG Var', over:'2.5 Üst', under:'2.5 Alt' },
  }[lang] || { home:'Home', draw:'Draw', away:'Away', btts:'BTTS', over:'O2.5', under:'U2.5' };

  const homeWins = match.form.home.filter(f=>f==='W').length;
  const awayWins = match.form.away.filter(f=>f==='W').length;
  const xGDiff   = match.xG.home - match.xG.away;
  const sm = match.lineMovement?.sharpMoney || 'NEUTRAL';

  const options = [
    { type:'HOME',  label:labels.home,  sublabel:match.home,  odds:match.odds.home,      color:'#00ff88',
      score: (homeWins/5)*0.35 + Math.max(0,xGDiff/2)*0.3 + (sm==='HOME'?0.35:0) },
    { type:'DRAW',  label:labels.draw,  sublabel:'X',         odds:match.odds.draw,      color:'#a8edff',
      score: (1-Math.abs(xGDiff)/3)*0.3 + (sm==='DRAW'?0.4:0.05) + (match.h2h.includes('2D')||match.h2h.includes('3D')?0.2:0) },
    { type:'AWAY',  label:labels.away,  sublabel:match.away,  odds:match.odds.away,      color:'#ff5470',
      score: (awayWins/5)*0.35 + Math.max(0,-xGDiff/2)*0.3 + (sm==='AWAY'?0.35:0) },
    { type:'BTTS',  label:labels.btts,  sublabel:'GG',        odds:match.btts.yes,       color:'#ff0080',
      score: (match.btts.yes<1.85?0.6:0.3) + (match.avgGoals>2.6?0.3:0) + (xGDiff<0.8?0.1:0) },
    { type:'OVER',  label:labels.over,  sublabel:'O 2.5',     odds:match.overUnder.o25,  color:'#a855f7',
      score: (match.overUnder.o25<1.85?0.5:0.25) + (match.avgGoals>2.7?0.35:0) + (sm==='GOALS'?0.2:0) },
    { type:'UNDER', label:labels.under, sublabel:'U 2.5',     odds:match.overUnder.u25,  color:'#5ee7ff',
      score: (match.overUnder.u25<1.85?0.5:0.25) + (match.avgGoals<2.3?0.35:0) },
  ];

  const best = options.reduce((a,b) => a.score > b.score ? a : b);
  return { options, best };
}

// ─── Quick Pick Option Button ─────────────────────────────────
function QuickPickOption({ opt, isBest, match, agentResult, onAddToTicket }) {
  const sp = useSpringScale({ hoverScale:1.06, tapScale:0.93, stiffness:450, damping:22 });
  const implied = Math.round(100 / opt.odds);
  const c = isBest ? opt.color : 'rgba(255,255,255,0.35)';
  const isAIMatch = agentResult && (
    (opt.type==='HOME' && agentResult.recommendation==='HOME_WIN') ||
    (opt.type==='DRAW' && agentResult.recommendation==='DRAW') ||
    (opt.type==='AWAY' && agentResult.recommendation==='AWAY_WIN') ||
    (opt.type==='OVER' && agentResult.recommendation==='OVER_25') ||
    (opt.type==='UNDER'&& agentResult.recommendation==='UNDER_25') ||
    (opt.type==='BTTS' && agentResult.recommendation==='BTTS_YES')
  );

  return (
    <div onClick={() => onAddToTicket(match, {
      bet_label: `${opt.label}`, odds: opt.odds,
      risk: opt.odds < 1.75 ? 'SAFE' : opt.odds < 2.8 ? 'GOOD' : 'RISK',
      confidence: Math.round(opt.score * 80 + 45), recommendation: opt.type,
    })} {...sp} style={{
      ...sp.style, flexDirection:'column', alignItems:'center', justifyContent:'center',
      padding:'8px 4px', borderRadius:12, cursor:'pointer', position:'relative',
      background: isBest ? `linear-gradient(135deg,${opt.color}22,${opt.color}08)` : 'rgba(255,255,255,0.04)',
      border: `1px solid ${isBest ? opt.color+'55' : 'rgba(255,255,255,0.08)'}`,
      boxShadow: isBest ? `0 0 18px ${opt.color}20,inset 0 1px 0 ${opt.color}20` : 'none',
    }}>
      {/* Best badge */}
      {isBest && (
        <div style={{ position:'absolute', top:-6, left:'50%', transform:'translateX(-50%)', fontSize:7, background:opt.color, color:'#04060e', padding:'1px 6px', borderRadius:99, fontFamily:'JetBrains Mono', fontWeight:800, whiteSpace:'nowrap' }}>BEST</div>
      )}
      {/* AI badge */}
      {isAIMatch && !isBest && (
        <div style={{ position:'absolute', top:-6, left:'50%', transform:'translateX(-50%)', fontSize:7, background:'#ffa500', color:'#04060e', padding:'1px 6px', borderRadius:99, fontFamily:'JetBrains Mono', fontWeight:800 }}>KI</div>
      )}
      <div style={{ fontSize:8, color:'rgba(255,255,255,0.4)', fontFamily:'JetBrains Mono', letterSpacing:'.04em', marginBottom:3, textAlign:'center' }}>{opt.sublabel}</div>
      <div style={{ fontSize:15, fontWeight:800, fontFamily:'JetBrains Mono', color:isBest?opt.color:'#ffa500', textShadow:isBest?`0 0 10px ${opt.color}80`:'' }}>{opt.odds.toFixed(2)}</div>
      <div style={{ fontSize:7, color:c, fontFamily:'JetBrains Mono', marginTop:2, opacity:0.8 }}>{implied}%</div>
      <div style={{ fontSize:8, fontFamily:'Inter', color:c, marginTop:2, textAlign:'center', lineHeight:1.2 }}>{opt.label}</div>
    </div>
  );
}

// ─── Match Card — COMPACT + VISUAL HIERARCHY ──────────────────
function MatchCard({ match, onAnalyse, onAddToTicket, agentResult, isTop, idx, onShowH2H, onShowOdds, espnScore }) {
  const [mode, setMode] = useState('closed'); // closed | quickpick | details
  const lc = match.leagueColor || '#00f5ff';
  const rc = agentResult ? getRiskColor(agentResult.risk) : lc;
  const wc = match.weather ? getWeatherImpactColor(match.weather.impact) : 'rgba(255,255,255,0.3)';
  const liveData = espnScore || (match.liveScore ? match : null);
  const hasAI = !!agentResult;
  const { options, best } = useMemo(() => getBestTip(match), [match.id]);
  const handleCardClick = () => setMode(m => m==='closed'?'quickpick':m==='quickpick'?'details':'closed');
  const exp = mode === 'details';
  const stats = [
    {l:'xG H',v:match.xG.home,c:'#00f5ff'},{l:'xG A',v:match.xG.away,c:'#00f5ff'},
    {l:'Ø TORE',v:match.avgGoals,c:'#00ff88'},{l:'POSS%',v:match.possession.home+'%',c:'#ffa500'},
    {l:'BTTS',v:match.btts.yes,c:'#ff0080'},{l:'O2.5',v:match.overUnder.o25,c:'#a855f7'},
  ];
  return (
    <div style={{marginBottom:8,animation:`fadeUp .4s ${idx*.05}s both ease`}}>
      <NeonCard color={isTop?'#00f5ff':lc} glow={isTop||hasAI}>

        {/* ── COLLAPSED: 3-Row Compact Layout ── */}
        <div onClick={handleCardClick} style={{padding:'9px 12px',cursor:'pointer'}}>

          {/* ROW 1: League meta — micro text */}
          <div style={{display:'flex',alignItems:'center',gap:4,marginBottom:6,overflow:'hidden'}}>
            <span style={{fontSize:11,flexShrink:0}}>{match.leagueFlag}</span>
            <span style={{fontSize:8,color:'rgba(255,255,255,0.32)',fontFamily:'JetBrains Mono',letterSpacing:'.06em',flexShrink:0}}>{match.leagueShort} · {match.time}</span>
            {match.importance && <HoloBadge color={lc} size="xs">{match.importance}</HoloBadge>}
            {isTop && <HoloBadge color="#00f5ff" size="xs" pulse>★</HoloBadge>}
            {match.weather && <span style={{fontSize:8,color:wc,fontFamily:'JetBrains Mono',flexShrink:0}}>{match.weather.label.split(' ')[1]}</span>}
            {liveData?.liveScore && <HoloBadge color="#00ff88" size="xs" pulse>{liveData.liveScore}</HoloBadge>}
            <div style={{marginLeft:'auto',fontSize:8,color:'rgba(255,255,255,0.15)',flexShrink:0}}>{mode==='closed'?'▼':mode==='quickpick'?'⚡':'▲'}</div>
          </div>

          {/* ROW 2: Teams inline — DOMINANT */}
          <div style={{display:'flex',alignItems:'baseline',gap:5,marginBottom:7}}>
            <span style={{fontSize:15,fontWeight:800,fontFamily:'Space Grotesk',color:'rgba(255,255,255,0.98)',letterSpacing:'-.02em',lineHeight:1,textShadow:isTop?`0 0 16px ${lc}99, 0 0 4px ${lc}55`:`0 0 8px rgba(255,255,255,0.18)`}}>{match.home}</span>
            <span style={{fontSize:8,color:'rgba(255,255,255,0.18)',fontFamily:'JetBrains Mono',flexShrink:0}}>vs</span>
            <span style={{fontSize:12,fontFamily:'Space Grotesk',color:'rgba(255,255,255,0.38)',fontWeight:500,overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap',flex:1}}>{match.away}</span>
          </div>

          {/* ROW 3: Odds + AI Bet (if present) */}
          <div style={{display:'flex',alignItems:'center',gap:5}}>
            {/* 3 Odds pills — bunte Glow-Effekte: 1=Cyan, X=Orange, 2=Pink */}
            {(() => {
              const o1 = match.odds.home, oX = match.odds.draw, o2 = match.odds.away;
              const minOdd = Math.min(o1, oX, o2);
              return [
                {l:'1',v:o1,c:'#00f5ff'},
                {l:'X',v:oX,c:'#ffa500'},
                {l:'2',v:o2,c:'#ff5470'},
              ].map(o => {
                const isFav = o.v === minOdd;
                return (
                  <div key={o.l} style={{
                    minWidth:38,textAlign:'center',padding:'4px 3px',borderRadius:9,
                    background:`linear-gradient(135deg, ${o.c}${isFav?'25':'10'}, ${o.c}05)`,
                    border:`1px solid ${o.c}${isFav?'88':'40'}`,
                    boxShadow:isFav
                      ? `0 0 14px ${o.c}77, 0 0 28px ${o.c}33, inset 0 0 8px ${o.c}22`
                      : `0 0 8px ${o.c}33`,
                    animation:isFav?`oddPulse_${o.l} 2s ease-in-out infinite`:'none',
                  }}>
                    <style>{`@keyframes oddPulse_${o.l}{0%,100%{box-shadow:0 0 14px ${o.c}77,0 0 28px ${o.c}33,inset 0 0 8px ${o.c}22}50%{box-shadow:0 0 22px ${o.c}aa,0 0 44px ${o.c}55,inset 0 0 12px ${o.c}33}}`}</style>
                    <div style={{fontSize:6,color:`${o.c}aa`,fontFamily:'JetBrains Mono',marginBottom:1,letterSpacing:'.1em'}}>{o.l}</div>
                    <div style={{fontSize:12,fontWeight:800,fontFamily:'JetBrains Mono',color:o.c,
                      textShadow:`0 0 12px ${o.c}ee, 0 0 24px ${o.c}88, 0 0 4px ${o.c}`}}>{o.v.toFixed(2)}</div>
                  </div>
                );
              });
            })()}

            {/* AI Bet — DOMINANT right side */}
            {hasAI ? (
              <div style={{flex:1,padding:'4px 8px',borderRadius:10,background:`linear-gradient(135deg,${rc}18,${rc}05)`,border:`1px solid ${rc}40`,backdropFilter:'blur(8px)',minWidth:0}}>
                <div style={{fontSize:9,fontWeight:700,color:rc,fontFamily:'Space Grotesk',overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap',textShadow:`0 0 8px ${rc}60`,marginBottom:1}}>👑 {agentResult.bet_label}</div>
                <div style={{display:'flex',alignItems:'center',gap:5}}>
                  <span style={{fontSize:14,fontWeight:800,fontFamily:'JetBrains Mono',color:'#ffa500',textShadow:'0 0 10px rgba(255,165,0,0.5)'}}>{formatOdds(agentResult.odds)}</span>
                  <span style={{fontSize:8,color:`${rc}cc`,fontFamily:'JetBrains Mono'}}>{agentResult.confidence}%</span>
                  <span style={{fontSize:8,color:rc,fontFamily:'JetBrains Mono',background:`${rc}15`,padding:'1px 5px',borderRadius:4}}>{agentResult.risk}</span>
                </div>
              </div>
            ) : (
              <div style={{flex:1,display:'flex',gap:4,justifyContent:'flex-end'}}>
                {[{l:'O2.5',v:match.overUnder.o25,c:'#a855f7'},{l:'BTTS',v:match.btts.yes,c:'#ff0080'}].map(p=>(
                  <div key={p.l} style={{padding:'4px 6px',background:'rgba(255,255,255,0.04)',borderRadius:8,border:'1px solid rgba(255,255,255,0.07)',textAlign:'center'}}>
                    <div style={{fontSize:6,color:'rgba(255,255,255,0.2)',fontFamily:'JetBrains Mono',marginBottom:1}}>{p.l}</div>
                    <div style={{fontSize:11,fontWeight:800,fontFamily:'JetBrains Mono',color:p.c,textShadow:`0 0 12px ${p.c}, 0 0 24px ${p.c}88, 0 0 3px ${p.c}`}}>{p.v}</div>
                  </div>
                ))}
              </div>
            )}
          </div>
        </div>

        {/* ── QUICKPICK PANEL: shown on first tap ── */}
        {mode === 'quickpick' && (
          <div style={{padding:'0 12px 11px',borderTop:'1px solid rgba(255,255,255,0.06)',animation:'fadeUp .22s ease'}}>
            <div style={{display:'flex',alignItems:'center',justifyContent:'space-between',padding:'8px 0 6px'}}>
              <div style={{display:'flex',alignItems:'center',gap:5}}>
                <LiveDot color={best.color} size={5}/>
                <span style={{fontSize:8,color:'rgba(255,255,255,0.35)',fontFamily:'JetBrains Mono',letterSpacing:'.1em'}}>BESTE TIPPS</span>
              </div>
              <button onClick={e=>{e.stopPropagation();setMode('details');}} style={{fontSize:9,color:'rgba(255,255,255,0.3)',background:'none',cursor:'pointer',fontFamily:'JetBrains Mono',padding:'2px 6px',borderRadius:6,border:'1px solid rgba(255,255,255,0.08)'}}>Details ▼</button>
            </div>
            {/* Sharp money indicator */}
            {match.lineMovement?.sharpMoney && match.lineMovement.sharpMoney !== 'NEUTRAL' && (
              <div style={{display:'flex',alignItems:'center',gap:5,marginBottom:8,padding:'4px 8px',background:'rgba(0,245,255,0.05)',borderRadius:8,border:'1px solid rgba(0,245,255,0.12)'}}>
                <span style={{fontSize:8,color:'#00f5ff',fontFamily:'JetBrains Mono',letterSpacing:'.08em'}}>📉 SHARP MONEY → {match.lineMovement.sharpMoney}</span>
                {match.lineMovement.steamMove && <span style={{fontSize:7,background:'rgba(255,165,0,0.2)',color:'#ffa500',padding:'1px 5px',borderRadius:99,fontFamily:'JetBrains Mono'}}>STEAM</span>}
              </div>
            )}
            {/* 6 pick options grid */}
            <div style={{display:'grid',gridTemplateColumns:'repeat(3,1fr)',gap:6,marginTop:2}}>
              {options.map(opt=>(
                <QuickPickOption key={opt.type} opt={opt} isBest={opt.type===best.type} match={match} agentResult={agentResult} onAddToTicket={(m,ar)=>{onAddToTicket(m,ar);setMode('closed');}}/>
              ))}
            </div>
            {/* AI overlay if available */}
            {hasAI && (
              <div style={{marginTop:8,padding:'6px 10px',background:`${rc}10`,border:`1px solid ${rc}30`,borderRadius:10,display:'flex',alignItems:'center',gap:8}}>
                <span style={{fontSize:12}}>👑</span>
                <div style={{flex:1,minWidth:0}}>
                  <div style={{fontSize:10,fontWeight:700,color:rc,fontFamily:'Space Grotesk',overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}}>{agentResult.bet_label}</div>
                </div>
                <div style={{fontSize:14,fontWeight:800,fontFamily:'JetBrains Mono',color:'#ffa500',flexShrink:0}}>{formatOdds(agentResult.odds)}</div>
                <button onClick={e=>{e.stopPropagation();onAddToTicket(match,agentResult);setMode('closed');}} style={{padding:'4px 8px',borderRadius:8,background:`${rc}20`,border:`1px solid ${rc}40`,color:rc,cursor:'pointer',fontFamily:'JetBrains Mono',fontWeight:700,fontSize:9,flexShrink:0}}>+ Slip</button>
              </div>
            )}
          </div>
        )}

        {/* ── EXPANDED DETAILS: full stats ── */}
        {exp && (
          <div style={{padding:'0 12px 11px',borderTop:'1px solid rgba(255,255,255,0.06)',animation:'fadeUp .22s ease'}}>
            {/* Form — compact */}
            <div style={{display:'flex',alignItems:'center',gap:4,padding:'7px 0',borderBottom:'1px solid rgba(255,255,255,0.05)'}}>
              <div style={{display:'flex',gap:2}}>{match.form.home.map((f,i)=><FormDot key={i} result={f} idx={i}/>)}</div>
              <div style={{width:1,height:12,background:'rgba(255,255,255,0.1)',flexShrink:0,margin:'0 2px'}}/>
              <div style={{display:'flex',gap:2}}>{match.form.away.map((f,i)=><FormDot key={i} result={f} idx={i}/>)}</div>
              <span style={{fontSize:8,color:'rgba(255,255,255,0.18)',marginLeft:'auto',fontFamily:'JetBrains Mono'}}>H2H {match.h2h}</span>
            </div>
            {/* Stats */}
            <div style={{display:'grid',gridTemplateColumns:'repeat(3,1fr)',gap:5,marginTop:7,marginBottom:7}}>
              {stats.map(s=><StatHex key={s.l} label={s.l} value={s.v} color={s.c}/>)}
            </div>
            <WeatherDetailCard match={match}/>
            {/* Actions */}
            <div style={{display:'flex',gap:5,flexWrap:'wrap',marginTop:5}}>
              <NeonButton color="#00f5ff" size="sm" onClick={e=>{e.stopPropagation();onAnalyse(match);}} style={{flex:1,minWidth:65,justifyContent:'center'}}>🤖 KI</NeonButton>
              <NeonButton color="#a855f7" size="sm" onClick={e=>{e.stopPropagation();onShowH2H(match);}} style={{flex:1,minWidth:50,justifyContent:'center'}}>⚔️ H2H</NeonButton>
              <NeonButton color="#ffa500" size="sm" onClick={e=>{e.stopPropagation();onShowOdds(match);}} style={{flex:1,minWidth:50,justifyContent:'center'}}>📊 Odds</NeonButton>
              {hasAI && <NeonButton color="#00ff88" size="sm" onClick={e=>{e.stopPropagation();onAddToTicket(match,agentResult);}} style={{flex:1,minWidth:50,justifyContent:'center'}}>+ Slip</NeonButton>}
            </div>
          </div>
        )}
      </NeonCard>
    </div>
  );
}

// ─── League Filter ────────────────────────────────────────────
function LeagueChip({ l, active, onSelect }) {
  const a = active;
  const sp = useSpringScale({hoverScale:1.06,tapScale:0.94});
  // Liga-spezifische Farbe (oder Cyan für "Alle")
  const c = l.color || '#00f5ff';
  return (
    <div onClick={onSelect} {...sp}
      style={{...sp.style,
        display:'flex',alignItems:'center',gap:4,padding:'7px 14px',borderRadius:99,
        border:`1px solid ${a?c:c+'66'}`,
        background:a
          ? `linear-gradient(135deg, ${c}25, ${c}08)`
          : `linear-gradient(135deg, ${c}10, rgba(255,255,255,0.03))`,
        color:a?'#fff':'rgba(255,255,255,0.92)',
        cursor:'pointer',whiteSpace:'nowrap',flexShrink:0,
        fontFamily:'JetBrains Mono',fontWeight:700,fontSize:11,letterSpacing:'.06em',
        textShadow:a?`0 0 8px ${c}aa`:`0 0 4px ${c}55`,
        boxShadow:a
          ? `0 0 20px ${c}66, 0 0 40px ${c}33, inset 0 0 12px ${c}22`
          : `0 0 8px ${c}33`,
        backdropFilter:'blur(8px)',
        transition:'all 0.3s ease',
        animation: a ? `chipPulse_${(c.replace('#','')||'cy')} 2.4s ease-in-out infinite` : 'none',
      }}>
      <style>{`
        @keyframes chipPulse_${(c.replace('#','')||'cy')} {
          0%,100% { box-shadow: 0 0 18px ${c}66, 0 0 36px ${c}33, inset 0 0 12px ${c}22; }
          50% { box-shadow: 0 0 28px ${c}aa, 0 0 56px ${c}55, inset 0 0 16px ${c}33; }
        }
      `}</style>
      <span style={{fontSize:12}}>{l.flag}</span>{l.name}
    </div>
  );
}
function LeagueFilter({ leagues, active, onSelect }) {
  const items = [{key:'ALL',flag:'🌍',name:'Alle',color:'#00f5ff'},
    ...Object.entries(leagues).map(([k,v])=>({key:k,flag:v.flag,name:k,color:v.color}))];
  return (
    <div style={{display:'flex',gap:6,overflowX:'auto',padding:'0 16px 12px',scrollbarWidth:'none',flexShrink:0}}>
      {items.map(l => <LeagueChip key={l.key} l={l} active={active===l.key} onSelect={()=>onSelect(l.key)}/>)}
    </div>
  );
}

// ─── Heute Screen ─────────────────────────────────────────────
function HeuteScreen({ onAnalyse, onAddToTicket, agentResults, lastRefresh, liveScores, apiLoading }) {
  const [filter, setFilter] = useState('ALL');
  const [h2hMatch, setH2hMatch] = useState(null);
  const [oddsMatch, setOddsMatch] = useState(null);
  const filtered = filter==='ALL'?MATCHES_TODAY:MATCHES_TODAY.filter(m=>m.leagueShort===filter);
  const top = filtered.filter(m=>m.importance);
  const rest = filtered.filter(m=>!m.importance);
  const usedLeagues = {};
  MATCHES_TODAY.forEach(m=>{usedLeagues[m.leagueShort]=LEAGUES[m.leagueShort]||{};});
  const getESPN = (match) => {
    const scores = Object.values(liveScores||{});
    return scores.find(s=>s.home?.toLowerCase().includes(match.home.split(' ')[0].toLowerCase()))||null;
  };

  return (
    <div style={{display:'flex',flexDirection:'column',height:'100%',position:'relative'}}>
      <div style={{padding:'14px 16px 0',flexShrink:0}}>
        <div style={{display:'flex',alignItems:'center',justifyContent:'space-between',marginBottom:5}}>
          <div style={{fontSize:8,color:'rgba(255,255,255,0.25)',fontFamily:'JetBrains Mono',letterSpacing:'.14em'}}>{getTodayLabel()} · {MATCHES_TODAY.length} SPIELE</div>
          <div style={{display:'flex',alignItems:'center',gap:6}}>
            {apiLoading && <div style={{width:10,height:10,borderRadius:'50%',border:'1.5px solid #00f5ff',borderTopColor:'transparent',animation:'spin 0.8s linear infinite'}}/>}
            <div style={{display:'flex',alignItems:'center',gap:4}}>
              <LiveDot color="#00ff88"/>
              <span style={{fontSize:8,color:'#00ff88',fontFamily:'JetBrains Mono',letterSpacing:'.1em'}}>LIVE</span>
              {lastRefresh&&<span style={{fontSize:7,color:'rgba(255,255,255,0.2)',fontFamily:'JetBrains Mono'}}>{lastRefresh}</span>}
            </div>
          </div>
        </div>
        <HoloText colors={['#00f5ff','#00ff88','#ffffff']} size={22} style={{marginBottom:12}}>{t('today')}</HoloText>
      </div>
      <LeagueFilter leagues={usedLeagues} active={filter} onSelect={setFilter}/>
      <div style={{flex:1,overflowY:'auto',padding:'0 16px'}}>
        {top.length>0&&(
          <>
            <div style={{display:'flex',alignItems:'center',gap:6,marginBottom:10}}>
              <LiveDot color="#00f5ff" size={6}/>
              <span style={{fontSize:8,color:'#00f5ff',fontFamily:'JetBrains Mono',letterSpacing:'.14em'}}>TOP EVENTS</span>
            </div>
            {top.map((m,i)=><MatchCard key={m.id} match={m} onAnalyse={onAnalyse} onAddToTicket={onAddToTicket} agentResult={agentResults[m.id]} isTop idx={i} onShowH2H={setH2hMatch} onShowOdds={setOddsMatch} espnScore={getESPN(m)}/>)}
          </>
        )}
        <div style={{fontSize:8,color:'rgba(255,255,255,0.2)',fontFamily:'JetBrains Mono',letterSpacing:'.14em',marginBottom:10,marginTop:4}}>WEITERE SPIELE</div>
        {rest.map((m,i)=><MatchCard key={m.id} match={m} onAnalyse={onAnalyse} onAddToTicket={onAddToTicket} agentResult={agentResults[m.id]} isTop={false} idx={i} onShowH2H={setH2hMatch} onShowOdds={setOddsMatch} espnScore={getESPN(m)}/>)}
        {filtered.length===0&&<div style={{textAlign:'center',padding:'40px 20px',color:'rgba(255,255,255,0.2)',fontFamily:'Inter',fontSize:13}}>Keine Spiele</div>}
        <div style={{height:20}}/>
      </div>
      {h2hMatch&&<H2HModal match={h2hMatch} onClose={()=>setH2hMatch(null)}/>}
      {oddsMatch&&<OddsComparisonModal match={oddsMatch} onClose={()=>setOddsMatch(null)}/>}
    </div>
  );
}

// ─── Export Card ──────────────────────────────────────────────
function ExportCard({ picks, totalOdds, stake, risk, onClose }) {
  const rc = getRiskColor(risk);
  return (
    <div style={{position:'absolute',inset:0,background:'rgba(4,6,8,0.92)',backdropFilter:'blur(20px)',zIndex:100,display:'flex',alignItems:'center',justifyContent:'center',padding:20}}>
      <NeonCard color={rc} tilt={false} style={{width:'100%'}}>
        <div style={{padding:'16px 18px 0'}}>
          <div style={{display:'flex',alignItems:'center',gap:10,marginBottom:14}}>
            <div style={{width:36,height:36,borderRadius:12,background:`linear-gradient(135deg,${rc},${rc}66)`,display:'flex',alignItems:'center',justifyContent:'center',fontSize:18,boxShadow:`0 0 20px ${rc}50`}}>⚽</div>
            <div>
              <HoloText colors={['#00f5ff','#00ff88']} size={15}>FUSSBALL AI</HoloText>
              <div style={{fontSize:7,color:rc,fontFamily:'JetBrains Mono',letterSpacing:'.14em'}}>9 AGENTS · KI PREDICTION</div>
            </div>
            <div style={{marginLeft:'auto',textAlign:'right'}}>
              <RiskChip risk={risk}/>
            </div>
          </div>
          <GlassDivider color={`${rc}20`}/>
          <div style={{padding:'10px 0'}}>
            {picks.map((p,i)=>(
              <div key={i} style={{display:'flex',justifyContent:'space-between',alignItems:'center',padding:'8px 0',borderBottom:i<picks.length-1?'1px solid rgba(255,255,255,0.05)':'none'}}>
                <div style={{flex:1,minWidth:0}}>
                  <div style={{fontSize:9,color:'rgba(255,255,255,0.3)',fontFamily:'JetBrains Mono',marginBottom:1}}>{p.leagueFlag} {p.league}</div>
                  <div style={{fontSize:12,fontWeight:700,fontFamily:'Space Grotesk',color:'rgba(255,255,255,0.88)',overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}}>{p.home} vs {p.away}</div>
                  <div style={{fontSize:10,color:rc}}>{p.bet_label}</div>
                </div>
                <div style={{fontSize:18,fontWeight:800,fontFamily:'JetBrains Mono',color:'#ffa500',textShadow:'0 0 12px rgba(255,165,0,0.5)',marginLeft:10}}>{p.odds?.toFixed(2)}</div>
              </div>
            ))}
          </div>
          <GlassDivider color="rgba(255,255,255,0.06)"/>
          <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',padding:'14px 0'}}>
            <div>
              <div style={{fontSize:8,color:'rgba(255,255,255,0.3)',fontFamily:'JetBrains Mono',marginBottom:4}}>GESAMTQUOTE</div>
              <div style={{fontSize:30,fontWeight:800,fontFamily:'JetBrains Mono',color:'#ffa500',textShadow:'0 0 20px rgba(255,165,0,0.5)'}}>{totalOdds.toFixed(2)}</div>
            </div>
            <div style={{textAlign:'right'}}>
              <div style={{fontSize:8,color:'rgba(255,255,255,0.3)',fontFamily:'JetBrains Mono',marginBottom:4}}>BEI €{stake}</div>
              <div style={{fontSize:30,fontWeight:800,fontFamily:'JetBrains Mono',color:'#00ff88',textShadow:'0 0 20px rgba(0,255,136,0.5)'}}>€{(totalOdds*stake).toFixed(2)}</div>
            </div>
          </div>
          <div style={{display:'flex',gap:8,paddingBottom:16}}>
            <div style={{flex:1,padding:'10px',textAlign:'center',background:'rgba(255,255,255,0.04)',borderRadius:12,fontSize:10,color:'rgba(255,255,255,0.35)',fontFamily:'Inter'}}>📸 Screenshot</div>
            <NeonButton color="#ff0050" onClick={onClose}>✕ Schließen</NeonButton>
          </div>
        </div>
      </NeonCard>
    </div>
  );
}

// ─── Scheine Screen ───────────────────────────────────────────
function ScheineScreen({ picks, onRemovePick, onUseKITicket, matches, onTrackBets }) {
  const [sub, setSub] = useState('ki');
  const [showExport, setShowExport] = useState(false);
  const totalOdds = picks.reduce((a,p)=>a*(p.odds||1.8),1);
  return (
    <div style={{display:'flex',flexDirection:'column',height:'100%',position:'relative'}}>
      <div style={{padding:'10px 16px 0',flexShrink:0}}>
        <div style={{display:'flex',background:'rgba(255,255,255,0.04)',borderRadius:14,padding:3,gap:2,backdropFilter:'blur(10px)',border:'1px solid rgba(255,255,255,0.08)'}}>
          {[{id:'ki',label: currentLang==='tr'?'🤖 AI':'🤖 KI'},{id:'edge',label:'🎯 ' + t('edge')},{id:'auto',label:'📊 Auto-Bets'}].map(tb=>{
            const a=sub===tb.id;
            const sp=useSpringScale({hoverScale:1.03,tapScale:0.97});
            return <div key={tb.id} onClick={()=>setSub(tb.id)} {...sp} style={{...sp.style,flex:1,padding:'8px 4px',borderRadius:11,cursor:'pointer',fontFamily:'Space Grotesk',fontWeight:700,fontSize:10,textAlign:'center',background:a?`rgba(0,245,255,0.15)`:'transparent',color:a?'#00f5ff':'rgba(255,255,255,0.35)',boxShadow:a?'0 0 12px rgba(0,245,255,0.15)':'none',transition:'background .2s,color .2s'}}>{tb.label}</div>;
          })}
        </div>
      </div>
      <div style={{flex:1,overflow:'hidden'}}>
        {sub==='ki'&&<KIScheine matches={matches}/>}
        {sub==='edge'&&<EdgeHunter matches={matches}/>}
        {sub==='auto'&&<AutoBetTracker matches={matches}/>}
      </div>
    </div>
  );
}

// ─── PWA Install Button ───────────────────────────────────────
function PWAInstallButton() {
  const [available, setAvailable] = React.useState(!!window.__pwaInstallAvailable);
  const [installed, setInstalled] = React.useState(!!window.__pwaInstalled);
  const [installing, setInstalling] = React.useState(false);

  React.useEffect(() => {
    const onReady = () => setAvailable(true);
    window.addEventListener('pwaInstallReady', onReady);
    return () => window.removeEventListener('pwaInstallReady', onReady);
  }, []);

  if (installed) return (
    <div style={{textAlign:'center',padding:'10px',background:'rgba(0,255,136,0.06)',border:'1px solid rgba(0,255,136,0.15)',borderRadius:12,marginBottom:16}}>
      <div style={{fontSize:11,color:'#00ff88',fontFamily:'Space Grotesk',fontWeight:600}}>✅ App installiert!</div>
    </div>
  );

  if (!available) return (
    <div style={{textAlign:'center',padding:'8px',marginBottom:16}}>
      <div style={{fontSize:9,color:'rgba(255,255,255,0.2)',fontFamily:'JetBrains Mono'}}>
        📱 Zum Installieren: Browser-Menü → "Zum Startbildschirm hinzufügen"
      </div>
    </div>
  );

  return (
    <div style={{marginBottom:16}}>
      <NeonButton color="#00f5ff" onClick={async()=>{
        setInstalling(true);
        const ok = await window.__pwaInstall?.();
        if (ok) setInstalled(true);
        setInstalling(false);
      }} style={{width:'100%',justifyContent:'center',fontSize:13}}>
        {installing ? '⏳ Installiere...' : '📱 Als App installieren'}
      </NeonButton>
    </div>
  );
}

// ─── AutoBet-Tracker — simulierte 10€-Wetten auf jeden KI-Schein ─
function AutoBetTracker({ matches }) {
  const [tick, setTick] = useState(0);
  // Refresh jede Sekunde damit nach Auflösung Daten aktuell sind
  useEffect(() => { const iv = setInterval(()=>setTick(t=>t+1), 5000); return ()=>clearInterval(iv); }, []);
  // Versuche auto-link beim Mount
  useEffect(() => { if (matches?.length) window.autobetStore?.linkToMatches(matches); }, [matches]);

  const stats = window.autobetStore?.getStats?.() || null;
  const all = window.autobetStore?.load?.() || [];
  const sorted = [...all].sort((a,b) => b.timestamp - a.timestamp);

  const profitColor = (stats?.profit || 0) > 0 ? '#22ff88' : (stats?.profit||0) < 0 ? '#ff5470' : 'rgba(255,255,255,0.5)';
  const fmtEur = (n) => `${n>0?'+':''}€${n.toFixed(2)}`;

  const reset = () => {
    if (confirm('Alle Auto-Wetten löschen?')) { window.autobetStore.clear(); setTick(t=>t+1); }
  };
  const exportData = () => {
    const blob = new Blob([JSON.stringify(all, null, 2)], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a'); a.href = url;
    a.download = `fussball-ai-autobets-${new Date().toISOString().split('T')[0]}.json`;
    a.click(); URL.revokeObjectURL(url);
  };

  return (
    <div style={{padding:'14px 16px',overflowY:'auto',height:'100%'}}>
      <div style={{marginBottom:12}}>
        <div style={{fontSize:9,color:'#22ff88',fontFamily:'JetBrains Mono',letterSpacing:'.14em',marginBottom:3,textShadow:'0 0 8px #22ff88aa'}}>SIMULATION · 10€ PRO SCHEIN</div>
        <div style={{fontSize:18,fontWeight:700,fontFamily:'Space Grotesk',color:'rgba(255,255,255,0.95)'}}>📊 Auto-Wetten</div>
        <div style={{fontSize:11,color:'rgba(255,255,255,0.4)',fontFamily:'Inter',marginTop:2}}>Jeder generierte KI-Schein wird automatisch mit 10€ simuliert. Live-Auswertung nach Spielende.</div>
      </div>

      {/* Profit-Banner */}
      <div style={{padding:'14px 16px',background:`linear-gradient(135deg, ${profitColor}10 0%, transparent 100%)`,border:`1px solid ${profitColor}33`,borderRadius:14,marginBottom:14,boxShadow:`0 0 24px ${profitColor}10`}}>
        <div style={{display:'flex',justifyContent:'space-between',alignItems:'center'}}>
          <div>
            <div style={{fontSize:9,color:profitColor,fontFamily:'JetBrains Mono',letterSpacing:'.12em',textShadow:`0 0 6px ${profitColor}99`}}>GESAMT P&L</div>
            <div style={{fontSize:32,fontWeight:800,fontFamily:'JetBrains Mono',color:profitColor,marginTop:2,textShadow:`0 0 20px ${profitColor}cc, 0 0 40px ${profitColor}66`}}>{stats ? fmtEur(stats.profit) : '€0.00'}</div>
          </div>
          <div style={{textAlign:'right'}}>
            <div style={{fontSize:9,color:'rgba(255,255,255,0.4)',fontFamily:'JetBrains Mono'}}>ROI</div>
            <div style={{fontSize:18,fontWeight:800,fontFamily:'JetBrains Mono',color:profitColor,textShadow:`0 0 8px ${profitColor}99`}}>{stats && stats.decided>0 ? ((stats.roi>0?'+':'')+(stats.roi*100).toFixed(1)+'%') : '—'}</div>
          </div>
        </div>
      </div>

      {/* Statistiken */}
      <div style={{display:'grid',gridTemplateColumns:'1fr 1fr 1fr',gap:6,marginBottom:14}}>
        {[
          {l:'OFFEN',v:stats?.open||0,sub:`€${(stats?.openStake||0).toFixed(0)} Einsatz`,c:'#5ee7ff'},
          {l:'GEWONNEN',v:stats?.won||0,sub:stats?.decided ? `${(stats.hitRate*100).toFixed(0)}% Quote` : '—',c:'#22ff88'},
          {l:'VERLOREN',v:stats?.lost||0,sub:stats?.decided ? `${stats.decided} entschieden` : '—',c:'#ff5470'},
        ].map(s=>(
          <div key={s.l} style={{padding:'8px 6px',background:`${s.c}06`,borderRadius:10,border:`1px solid ${s.c}25`,textAlign:'center',boxShadow:`inset 0 0 12px ${s.c}10`}}>
            <div style={{fontSize:8,color:s.c,fontFamily:'JetBrains Mono',letterSpacing:'.08em',textShadow:`0 0 6px ${s.c}99`}}>{s.l}</div>
            <div style={{fontSize:20,fontWeight:800,fontFamily:'JetBrains Mono',color:s.c,marginTop:2,textShadow:`0 0 10px ${s.c}cc`}}>{s.v}</div>
            <div style={{fontSize:8,color:'rgba(255,255,255,0.35)',fontFamily:'JetBrains Mono',marginTop:1}}>{s.sub}</div>
          </div>
        ))}
      </div>

      {/* Liste der Wetten */}
      {sorted.length === 0 ? (
        <div style={{textAlign:'center',padding:'40px 20px',color:'rgba(255,255,255,0.3)',fontFamily:'Inter',fontSize:12}}>
          <div style={{fontSize:32,marginBottom:10,opacity:0.5}}>🤖</div>
          Noch keine Auto-Wetten platziert.<br/>
          Generiere KI-Tickets im 🤖 KI Tab — sie werden automatisch hier mit 10€ simuliert.
        </div>
      ) : sorted.map(b => (
        <AutoBetCard key={b.id} bet={b}/>
      ))}

      {sorted.length > 0 && (
        <div style={{display:'flex',gap:6,marginTop:14,marginBottom:8}}>
          <button onClick={exportData} style={{flex:1,padding:'8px',borderRadius:10,background:'rgba(94,231,255,0.08)',border:'1px solid rgba(94,231,255,0.2)',color:'#5ee7ff',fontSize:10,fontFamily:'Space Grotesk',fontWeight:600,cursor:'pointer'}}>📥 Export</button>
          <button onClick={reset} style={{flex:1,padding:'8px',borderRadius:10,background:'rgba(255,84,112,0.06)',border:'1px solid rgba(255,84,112,0.2)',color:'#ff5470',fontSize:10,fontFamily:'Space Grotesk',fontWeight:600,cursor:'pointer'}}>🗑️ Reset</button>
        </div>
      )}
    </div>
  );
}

function AutoBetCard({ bet }) {
  const [open, setOpen] = useState(false);
  const statusColor = bet.status === 'won' ? '#22ff88' : bet.status === 'lost' ? '#ff5470' : '#ffb648';
  const statusLabel = bet.status === 'won' ? 'GEWONNEN' : bet.status === 'lost' ? 'VERLOREN' : 'OFFEN';
  const profitText = bet.status === 'won' ? `+€${(bet.payout - bet.stake).toFixed(2)}`
                   : bet.status === 'lost' ? `−€${bet.stake.toFixed(2)}`
                   : `€${bet.stake.toFixed(2)} → €${bet.potentialPayout.toFixed(2)}`;
  const typeLabel = bet.type === 'classic' ? 'Klassisch' : bet.type === 'ht' ? 'Halbzeit' : bet.type === 'korner' ? 'Korner' : bet.type === 'edge_hunter' ? 'Edge-Hunter' : bet.type;
  return (
    <div style={{padding:'10px 12px',background:`${statusColor}06`,border:`1px solid ${statusColor}33`,borderRadius:12,marginBottom:6,boxShadow:`0 0 14px ${statusColor}08`}}>
      <div onClick={()=>setOpen(!open)} style={{cursor:'pointer'}}>
        <div style={{display:'flex',justifyContent:'space-between',alignItems:'flex-start',gap:8}}>
          <div style={{flex:1,minWidth:0}}>
            <div style={{fontSize:8,color:'rgba(255,255,255,0.4)',fontFamily:'JetBrains Mono',letterSpacing:'.08em'}}>{bet.date} · {typeLabel}</div>
            <div style={{fontSize:12,fontWeight:700,fontFamily:'Space Grotesk',color:'rgba(255,255,255,0.9)',marginTop:1}}>{bet.label}</div>
            <div style={{fontSize:10,color:'rgba(255,255,255,0.5)',fontFamily:'JetBrains Mono',marginTop:2}}>{bet.picks.length} Picks · Quote {bet.totalOdds.toFixed(2)}</div>
          </div>
          <div style={{textAlign:'right',flexShrink:0}}>
            <div style={{fontSize:8,padding:'2px 7px',borderRadius:99,background:`${statusColor}18`,border:`1px solid ${statusColor}40`,color:statusColor,fontFamily:'JetBrains Mono',fontWeight:700,letterSpacing:'.08em',textShadow:`0 0 6px ${statusColor}aa`}}>{statusLabel}</div>
            <div style={{fontSize:13,fontWeight:800,fontFamily:'JetBrains Mono',color:statusColor,marginTop:3,textShadow:`0 0 10px ${statusColor}cc`}}>{profitText}</div>
            <div style={{fontSize:8,color:'rgba(255,255,255,0.3)',fontFamily:'JetBrains Mono',marginTop:1}}>{open?'▲':'▼'} Picks</div>
          </div>
        </div>
      </div>
      {open && (
        <div style={{marginTop:8,paddingTop:8,borderTop:`1px solid ${statusColor}20`}}>
          {bet.picks.map((p,i)=>{
            const pc = p.status === 'won' ? '#22ff88' : p.status === 'lost' ? '#ff5470' : p.status === 'unknown' ? '#888' : '#ffb648';
            const pIcon = p.status === 'won' ? '✓' : p.status === 'lost' ? '✗' : p.status === 'unknown' ? '?' : '⏳';
            return (
              <div key={i} style={{display:'flex',gap:8,padding:'5px 0',fontSize:10,fontFamily:'Inter',color:'rgba(255,255,255,0.7)'}}>
                <span style={{color:pc,fontFamily:'JetBrains Mono',fontWeight:700,minWidth:14,textShadow:`0 0 6px ${pc}99`}}>{pIcon}</span>
                <span style={{flex:1,minWidth:0,overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}}>{p.home} vs {p.away} — <span style={{color:pc}}>{p.bet_label}</span></span>
                <span style={{fontFamily:'JetBrains Mono',color:'#ffb648'}}>{p.odds?.toFixed(2)}</span>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}

// ─── Track Record Panel (Phase 0 Stats) ──────────────────────
function TrackRecordPanel() {
  const [tick, setTick] = useState(0);
  const stats = React.useMemo(() => window.tracker?.getStats?.() || null, [tick]);
  const bySource = React.useMemo(() => window.tracker?.getBySource?.() || {}, [tick]);
  const all = window.tracker?.load?.() || [];
  const open = all.filter(p => !p.outcome).length;
  const closed = all.length - open;
  if (!window.tracker) return null;
  const fmt = (n, d=1, suf='') => n == null || isNaN(n) ? '—' : (n*100).toFixed(d)+suf;
  const exportData = () => {
    const blob = new Blob([JSON.stringify(all, null, 2)], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a'); a.href = url;
    a.download = `fussball-ai-picks-${new Date().toISOString().split('T')[0]}.json`;
    a.click(); URL.revokeObjectURL(url);
  };
  const reset = () => {
    if (confirm(t('confirmReset'))) { window.tracker.clear(); setTick(tk=>tk+1); }
  };
  return (
    <>
      <div style={{fontSize:8,color:'rgba(255,255,255,0.3)',fontFamily:'JetBrains Mono',letterSpacing:'.14em',marginBottom:10}}>{t('trackRecord')}</div>
      <NeonCard color={(stats?.roi||0)>=0?'#22ff88':'#ff5470'} tilt={false} style={{marginBottom:8,padding:'12px 14px'}}>
        <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:10,marginBottom:closed>0?10:0}}>
          {[
            {l: t('picks_'),v:all.length,sub:`${closed} ${t('evaluated')} · ${open} ${t('open_')}`,c:'#5ee7ff'},
            {l: t('hitRate'),v:stats?.hitRate==null?'—':fmt(stats.hitRate,1,'%'),sub:`${stats?.wins||0}W · ${stats?.losses||0}L · ${stats?.pushes||0}P`,c:(stats?.hitRate||0)>=0.5?'#22ff88':'#ffb648'},
            {l: t('roi_'),v:stats?.roi==null||closed===0?'—':((stats.roi>0?'+':'')+(stats.roi*100).toFixed(1)+'%'),sub: t('perPick'),c:(stats?.roi||0)>=0?'#22ff88':'#ff5470'},
            {l: t('brier'),v:stats?.brier==null?'—':stats.brier.toFixed(3),sub: t('lowerBetter'),c:'#a855f7'},
          ].map(s=>(
            <div key={s.l} style={{padding:'8px 10px',background:'rgba(255,255,255,0.03)',borderRadius:10,border:`1px solid ${s.c}25`,boxShadow:`inset 0 0 14px ${s.c}10`}}>
              <div style={{fontSize:8,color:s.c,fontFamily:'JetBrains Mono',letterSpacing:'.12em',textShadow:`0 0 6px ${s.c}99`}}>{s.l}</div>
              <div style={{fontSize:18,fontWeight:800,fontFamily:'JetBrains Mono',color:s.c,marginTop:2,textShadow:`0 0 10px ${s.c}cc, 0 0 20px ${s.c}55`}}>{s.v}</div>
              <div style={{fontSize:8,color:'rgba(255,255,255,0.35)',fontFamily:'JetBrains Mono',marginTop:2}}>{s.sub}</div>
            </div>
          ))}
        </div>
        {closed >= 5 && stats?.clv != null && (
          <div style={{padding:'8px 10px',marginTop:8,background:`linear-gradient(135deg, ${stats.clv>0?'#22ff8815':'#ff547015'} 0%, transparent 100%)`,border:`1px solid ${stats.clv>0?'#22ff8840':'#ff547040'}`,borderRadius:10}}>
            <div style={{display:'flex',justifyContent:'space-between',alignItems:'center'}}>
              <span style={{fontSize:9,color:stats.clv>0?'#22ff88':'#ff5470',fontFamily:'JetBrains Mono',letterSpacing:'.12em'}}>{t('clvLabel')}</span>
              <span style={{fontSize:13,fontWeight:800,fontFamily:'JetBrains Mono',color:stats.clv>0?'#22ff88':'#ff5470'}}>{(stats.clv>0?'+':'')+(stats.clv*100).toFixed(2)}%</span>
            </div>
            <div style={{fontSize:9,color:'rgba(255,255,255,0.5)',fontFamily:'Inter',marginTop:3,lineHeight:1.4}}>
              {stats.clv > 0 ? t('clvWin') : t('clvLose')}
            </div>
          </div>
        )}
      </NeonCard>
      {Object.entries(bySource).filter(([_,s])=>s.total>0).length > 0 && (
        <div style={{marginBottom:12}}>
          <div style={{fontSize:8,color:'rgba(255,255,255,0.3)',fontFamily:'JetBrains Mono',letterSpacing:'.14em',marginBottom:6}}>{t('bySource')}</div>
          {Object.entries(bySource).filter(([_,s])=>s.total>0).map(([src,s])=>(
            <div key={src} style={{display:'flex',justifyContent:'space-between',padding:'7px 10px',background:'rgba(255,255,255,0.03)',borderRadius:8,marginBottom:4,border:'1px solid rgba(255,255,255,0.05)'}}>
              <span style={{fontSize:10,fontFamily:'JetBrains Mono',color:'rgba(255,255,255,0.7)'}}>{src}</span>
              <div style={{display:'flex',gap:10,fontSize:10,fontFamily:'JetBrains Mono'}}>
                <span style={{color:'rgba(255,255,255,0.5)'}}>{s.total}</span>
                <span style={{color:(s.hitRate||0)>=0.5?'#22ff88':'#ffb648'}}>{fmt(s.hitRate,0,'%')}</span>
                <span style={{color:(s.roi||0)>=0?'#22ff88':'#ff5470'}}>{(s.roi>0?'+':'')+(s.roi*100).toFixed(0)}%</span>
              </div>
            </div>
          ))}
        </div>
      )}
      <div style={{display:'flex',gap:6,marginBottom:16}}>
        <button onClick={exportData} disabled={!all.length} style={{flex:1,padding:'8px',borderRadius:10,background:'rgba(94,231,255,0.08)',border:'1px solid rgba(94,231,255,0.2)',color:'#5ee7ff',fontSize:10,fontFamily:'Space Grotesk',fontWeight:600,cursor:all.length?'pointer':'not-allowed',opacity:all.length?1:0.4}}>{t('exportJson')}</button>
        <button onClick={reset} disabled={!all.length} style={{flex:1,padding:'8px',borderRadius:10,background:'rgba(255,84,112,0.06)',border:'1px solid rgba(255,84,112,0.2)',color:'#ff5470',fontSize:10,fontFamily:'Space Grotesk',fontWeight:600,cursor:all.length?'pointer':'not-allowed',opacity:all.length?1:0.4}}>{t('resetBtn')}</button>
      </div>
    </>
  );
}

// ─── Info Screen ──────────────────────────────────────────────
function InfoScreen({ apiStatus }) {
  return (
    <div style={{height:'100%',overflowY:'auto',padding:'16px'}}>
      {apiStatus&&(
        <>
          <div style={{fontSize:8,color:'rgba(255,255,255,0.3)',fontFamily:'JetBrains Mono',letterSpacing:'.14em',marginBottom:10}}>API STATUS</div>
          <APIStatusPanel status={apiStatus}/>
        </>
      )}
      <div style={{fontSize:8,color:'rgba(255,255,255,0.3)',fontFamily:'JetBrains Mono',letterSpacing:'.14em',marginBottom:10,marginTop:6}}>KI-MODELLE · 12 STIMMEN</div>
      <NeonCard color="#a855f7" tilt={false} style={{marginBottom:14,padding:'12px 14px'}}>
        {[
          {icon:'🧠',name:'DeepSeek V4 Chat',desc:'9 LLM-Spezialisten + Master · Server-Proxy',c:'#a855f7',badge:'10× LLM'},
          {icon:'⚡',name:'Groq Llama-3.3 70B',desc:'Co-Master Wave 4 · Server-Proxy',c:'#ffb648',badge:'CO-MASTER'},
          {icon:'✨',name:'OpenAI GPT-OSS 120B',desc:'Co-Master Wave 4 · OpenRouter',c:'#5ee7ff',badge:'CO-MASTER'},
        ].map((s,i,arr)=>(
          <div key={s.name} style={{display:'flex',gap:8,padding:'8px 0',borderBottom:i<arr.length-1?'1px solid rgba(255,255,255,0.05)':'none',alignItems:'center'}}>
            <span style={{fontSize:18,flexShrink:0}}>{s.icon}</span>
            <div style={{flex:1,minWidth:0}}>
              <div style={{fontSize:11,fontWeight:600,color:s.c,fontFamily:'Space Grotesk',textShadow:`0 0 8px ${s.c}99`}}>{s.name}</div>
              <div style={{fontSize:9,color:'rgba(255,255,255,0.45)',fontFamily:'Inter'}}>{s.desc}</div>
            </div>
            <HoloBadge color={s.c} size="xs" style={{flexShrink:0}}>{s.badge}</HoloBadge>
          </div>
        ))}
      </NeonCard>

      <div style={{fontSize:8,color:'rgba(255,255,255,0.3)',fontFamily:'JetBrains Mono',letterSpacing:'.14em',marginBottom:10}}>QUANT-MODELLE · 2 ANKER</div>
      <NeonCard color="#5ee7ff" tilt={false} style={{marginBottom:14,padding:'12px 14px'}}>
        {[
          {icon:'⚙️',name:'Poisson Monte-Carlo',desc:'10.000 Sims pro Match · Deterministisch',c:'#5ee7ff'},
          {icon:'📐',name:'Elo Rating',desc:'K=20 mit MOV-Adjustment · Self-Updating',c:'#a855f7'},
        ].map((s,i,arr)=>(
          <div key={s.name} style={{display:'flex',gap:8,padding:'8px 0',borderBottom:i<arr.length-1?'1px solid rgba(255,255,255,0.05)':'none',alignItems:'center'}}>
            <span style={{fontSize:18,flexShrink:0}}>{s.icon}</span>
            <div style={{flex:1,minWidth:0}}>
              <div style={{fontSize:11,fontWeight:600,color:s.c,fontFamily:'Space Grotesk',textShadow:`0 0 8px ${s.c}99`}}>{s.name}</div>
              <div style={{fontSize:9,color:'rgba(255,255,255,0.45)',fontFamily:'Inter'}}>{s.desc}</div>
            </div>
            <HoloBadge color={s.c} size="xs" style={{flexShrink:0}}>QUANT</HoloBadge>
          </div>
        ))}
      </NeonCard>

      <div style={{fontSize:8,color:'rgba(255,255,255,0.3)',fontFamily:'JetBrains Mono',letterSpacing:'.14em',marginBottom:10}}>DATEN-AGENTEN · 5 ENRICHER</div>
      <NeonCard color="#ffd700" tilt={false} style={{marginBottom:14,padding:'12px 14px'}}>
        {[
          {icon:'⚡',name:'FATIGUE',desc:'Tage Pause · Mittwochs-UEL-Last · ESPN',c:'#ffb648'},
          {icon:'📋',name:'LINEUP',desc:'Bestätigte Aufstellungen · ESPN /summary',c:'#22ff88'},
          {icon:'🏆',name:'MOTIVATION',desc:'Tabelle · Klassenerhalt/Title-Race · ESPN',c:'#ffd700'},
          {icon:'🎙️',name:'REFEREE',desc:'Karten/Elfer-Tendenz · FBref Scrape',c:'#ff5470'},
          {icon:'🤝',name:'HEAD-TO-HEAD',desc:'Vergangene Begegnungen · ESPN /summary',c:'#5ee7ff'},
        ].map((s,i,arr)=>(
          <div key={s.name} style={{display:'flex',gap:8,padding:'8px 0',borderBottom:i<arr.length-1?'1px solid rgba(255,255,255,0.05)':'none',alignItems:'center'}}>
            <span style={{fontSize:18,flexShrink:0}}>{s.icon}</span>
            <div style={{flex:1,minWidth:0}}>
              <div style={{fontSize:11,fontWeight:600,color:s.c,fontFamily:'Space Grotesk',textShadow:`0 0 8px ${s.c}99`}}>{s.name}</div>
              <div style={{fontSize:9,color:'rgba(255,255,255,0.45)',fontFamily:'Inter'}}>{s.desc}</div>
            </div>
            <HoloBadge color={s.c} size="xs" style={{flexShrink:0}}>DATA</HoloBadge>
          </div>
        ))}
      </NeonCard>

      <div style={{fontSize:8,color:'rgba(255,255,255,0.3)',fontFamily:'JetBrains Mono',letterSpacing:'.14em',marginBottom:10}}>DATENQUELLEN · 5 FREE</div>
      <NeonCard color="#22ff88" tilt={false} style={{marginBottom:16,padding:'12px 14px'}}>
        {[
          {icon:'📺',name:'ESPN Soccer API',desc:'Spiele · Live-Scores · Lineups · DraftKings-Quoten · 11 Ligen · Frei',c:'#5ee7ff'},
          {icon:'🌦️',name:'Open-Meteo',desc:'Stadion-Wetter · Wind · Regen · Frei kein Key',c:'#22ff88'},
          {icon:'🏟️',name:'OpenLigaDB',desc:'Bundesliga Backup · Frei kein Key',c:'#ffa500'},
          {icon:'📊',name:'FBref Scrape',desc:'Schiri-Statistiken · Edge-cached 24h',c:'#ff5470'},
          {icon:'☁️',name:'Cloudflare KV',desc:'Globaler Daten-Store · Auto-Bets shared',c:'#a855f7'},
        ].map((s,i,arr)=>(
          <div key={s.name} style={{display:'flex',gap:8,padding:'8px 0',borderBottom:i<arr.length-1?'1px solid rgba(255,255,255,0.05)':'none',alignItems:'center'}}>
            <span style={{fontSize:18,flexShrink:0}}>{s.icon}</span>
            <div style={{flex:1,minWidth:0}}>
              <div style={{fontSize:11,fontWeight:600,color:s.c,fontFamily:'Space Grotesk',textShadow:`0 0 8px ${s.c}99`}}>{s.name}</div>
              <div style={{fontSize:9,color:'rgba(255,255,255,0.45)',fontFamily:'Inter'}}>{s.desc}</div>
            </div>
            <HoloBadge color="#22ff88" size="xs" style={{flexShrink:0}}>LIVE</HoloBadge>
          </div>
        ))}
      </NeonCard>

      <div style={{padding:'10px 12px',background:'rgba(0,255,136,0.05)',border:'1px solid rgba(0,255,136,0.15)',borderRadius:10,marginBottom:16,fontSize:10,color:'rgba(255,255,255,0.6)',fontFamily:'Inter',lineHeight:1.5}}>
        🔒 Alle API-Keys liegen verschlüsselt auf dem Server. Du musst nichts konfigurieren — alles läuft direkt.
      </div>
      <TrackRecordPanel/>

      <div style={{fontSize:8,color:'rgba(255,255,255,0.3)',fontFamily:'JetBrains Mono',letterSpacing:'.14em',marginBottom:10}}>9 LLM-AGENTEN</div>
      <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:8,marginBottom:16}}>
        {AGENTS.filter(a=>a.wave<=3).map(a=>(
          <NeonCard key={a.id} color={a.color} tilt style={{padding:'10px 12px'}}>
            <div style={{fontSize:18,marginBottom:4}}>{a.icon}</div>
            <div style={{fontSize:11,fontWeight:700,color:a.color,fontFamily:'Space Grotesk',marginBottom:2,textShadow:`0 0 10px ${a.color}60`}}>{a.name}</div>
            <div style={{fontSize:9,color:'rgba(255,255,255,0.4)',fontFamily:'Inter',lineHeight:1.4}}>{a.specialty}</div>
            <HoloBadge color={a.color} size="xs" style={{marginTop:6}}>WELLE {a.wave}</HoloBadge>
          </NeonCard>
        ))}
      </div>
      <NeonCard color="#ff0050" tilt={false} style={{padding:'12px 14px',marginBottom:24}}>
        <div style={{fontSize:11,color:'rgba(255,100,80,0.9)',fontFamily:'Inter',lineHeight:1.6}}>⚠️ Nur zu Informationszwecken. Wetten = Risiko. 18+</div>
      </NeonCard>
      <div style={{textAlign:'center',fontSize:9,color:'rgba(255,255,255,0.12)',fontFamily:'JetBrains Mono',paddingBottom:8,marginBottom:10}}>FUSSBALL AI v5.0 · 18 KI-MODELLE · PWA</div>
      <CopyrightFooter accent="#00f5ff" compact={false}/>
      <PWAInstallButton/>
    </div>
  );
}

// ─── Tweak Defaults ───────────────────────────────────────────
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{"accentColor":"#00f5ff","riskMode":"GOOD","showOdds":true,"autoRefreshMin":5}/*EDITMODE-END*/;

// ─── Floating Nav Tab ─────────────────────────────────────────
function NavTab({ tab: tb, active, accent, onClick }) {
  const a = active;
  const sp = useSpringScale({hoverScale:1.1,tapScale:0.88,stiffness:500,damping:22});
  return (
    <button
      onClick={onClick}
      role="tab"
      id={`tab-${tb.id}`}
      aria-controls={`panel-${tb.id}`}
      aria-selected={a}
      aria-label={`${tb.label}${tb.badge>0?` — ${tb.badge} neu`:''}`}
      tabIndex={a?0:-1}
      style={{minWidth:52,flex:1,display:'flex',flexDirection:'column',alignItems:'center',gap:3,padding:'10px 0',background:'none',border:'none',cursor:'pointer',position:'relative'}}>
      <div {...sp} style={{...sp.style,flexDirection:'column',alignItems:'center',gap:1}}>
        {tb.id==='heute'
          ? <img src={TWEMOJI_BALL} alt="" width={a?22:18} height={a?22:18} draggable={false}
              style={{filter:a?`drop-shadow(0 0 8px ${accent})`:'none',transition:'width .2s,height .2s,filter .2s',pointerEvents:'none'}}/>
          : <span style={{fontSize:a?22:18,filter:a?`drop-shadow(0 0 8px ${accent})`:'none',transition:'font-size .2s,filter .2s'}}>{tb.icon}</span>}
        {tb.badge>0&&<div style={{position:'absolute',top:-2,right:-4,width:14,height:14,borderRadius:'50%',background:accent,border:'1.5px solid #080b10',display:'flex',alignItems:'center',justifyContent:'center',fontSize:7,fontWeight:800,color:'#080b10',fontFamily:'JetBrains Mono',boxShadow:`0 0 8px ${accent}`}}>{tb.badge}</div>}
      </div>
      <span style={{fontSize:11,fontFamily:'Space Grotesk',fontWeight:a?800:600,color:a?accent:'rgba(255,255,255,0.85)',transition:'color .2s',letterSpacing:'.02em',whiteSpace:'nowrap',textShadow:a?`0 0 10px ${accent}99, 0 0 20px ${accent}44`:'none'}}>{tb.label}</span>
      {a&&<div style={{position:'absolute',bottom:-1,left:'50%',transform:'translateX(-50%)',width:20,height:2,borderRadius:99,background:accent,boxShadow:`0 0 12px ${accent}`}}/>}
    </button>
  );
}

// ─── App Shell ────────────────────────────────────────────────
function App() {
  const [tab, setTab]           = useState('heute');
  const [selectedMatch, setSM]  = useState(MATCHES_TODAY[0]);
  const [agentResults, setAR]   = useState({});
  const [picks, setPicks]       = useState([]);
  const [tweaks, setTweaks]     = useState(TWEAK_DEFAULTS);
  const [tweaksOn, setTweaksOn] = useState(false);
  const [langKey, setLangKey]   = useState(0);
  const [lastRefresh, setLastRefresh] = useState(null);
  // Splash bei jedem Reload zeigen — kein localStorage-skip mehr
  const [showOnboarding, setShowOnboarding] = useState(true);
  const { weatherLoaded, liveScores, apiStatus, loading: apisLoading } = useLiveData();

  // After ESPN data replaces mock MATCHES_TODAY, refresh selectedMatch to a real one
  useEffect(()=>{
    if (apisLoading) return;
    if (!MATCHES_TODAY.length) return;
    if (!selectedMatch || !MATCHES_TODAY.some(m => m.id === selectedMatch.id)) {
      setSM(MATCHES_TODAY[0]);
    }
  }, [apisLoading]);

  useEffect(()=>{
    const mins = tweaks.autoRefreshMin||5;
    const tick = ()=>{
      const now = new Date();
      setLastRefresh(`${now.getHours().toString().padStart(2,'0')}:${now.getMinutes().toString().padStart(2,'0')}`);
      MATCHES_TODAY.forEach(m=>{
        const d=()=>+(Math.random()*.06-.03).toFixed(2);
        m.odds.home=Math.max(1.01,+(m.odds.home+d()).toFixed(2));
        m.odds.draw=Math.max(1.01,+(m.odds.draw+d()).toFixed(2));
        m.odds.away=Math.max(1.01,+(m.odds.away+d()).toFixed(2));
      });
    };
    tick();
    const iv=setInterval(tick,mins*60*1000);
    return()=>clearInterval(iv);
  },[tweaks.autoRefreshMin]);

  useEffect(()=>{
    const h=e=>{
      if(e.data?.type==='__activate_edit_mode')   setTweaksOn(true);
      if(e.data?.type==='__deactivate_edit_mode') setTweaksOn(false);
    };
    window.addEventListener('message',h);
    window.parent.postMessage({type:'__edit_mode_available'},'*');
    return()=>window.removeEventListener('message',h);
  },[]);

  const handleAnalyse  = useCallback(m=>{setSM(m);setTab('agenten');},[]);
  const handleAgentResult = useCallback((id,r)=>setAR(p=>({...p,[id]:r})),[]);
  const handleAddToTicket = useCallback((match,ar)=>{
    const pick={id:match.id+'_'+Date.now(),league:match.leagueShort,leagueFlag:match.leagueFlag,time:match.time,home:match.home,away:match.away,bet_label:ar.bet_label||ar.final_pick,odds:ar.odds||match.odds.home,risk:ar.risk,confidence:ar.confidence};
    setPicks(p=>p.find(x=>x.id.startsWith(match.id))?p:[...p,pick]);
    setTab('scheine');
  },[]);
  const handleRemove   = useCallback(id=>setPicks(p=>p.filter(x=>x.id!==id)),[]);
  const handleKITicket = useCallback(ticket=>{setPicks(ticket.picks.map((p,i)=>({id:'ki_'+Date.now()+'_'+i,league:p.league||'?',leagueFlag:p.leagueFlag||'⚽',time:p.time||'?',home:p.home,away:p.away,bet_label:p.bet_label,odds:p.odds,risk:p.risk||ticket.risk})));},[]); 
  const handleTrackBets = useCallback(cp=>{cp.forEach(p=>perfStore.addBet({match:`${p.home} vs ${p.away}`,league:p.league,bet_label:p.bet_label,odds:p.odds,stake:10,risk:p.risk}));},[]);

  const ac = tweaks.accentColor;
  const liveCount = Object.values(liveScores).filter(s=>s.isLive).length;
  // langKey forces tabs labels to recompute when language changes
  const tabs = useMemo(()=>[
    {id:'heute',    icon:'⚽', label:t('tabToday'),    badge:MATCHES_TODAY.length},
    {id:'agenten',  icon:'🤖', label:t('tabAgents'),   badge:null},
    {id:'scheine',  icon:'🎟️', label:t('tabTickets'), badge:null},
    {id:'info',     icon:'⚙️', label:t('tabInfo'),     badge:null},
  // eslint-disable-next-line
  ],[langKey]);

  // Detection: läuft die App im Design-Preview-Iframe (Tweaks-Modus)?
  const inPreview = typeof window !== 'undefined' && window.parent !== window;
  // Phone-Frame nur in Design-Preview anzeigen, nicht in echtem Browser/PWA
  return inPreview ? (
    <div style={{width:'100vw',height:'100vh',display:'flex',alignItems:'center',justifyContent:'center',position:'relative',overflow:'hidden',background:'#040608'}}>
      <AuroraBackground accent={ac}/>
      <ParticleField accent={ac} count={24}/>
      <div style={{
        width:390,height:844,borderRadius:52,
        background:'linear-gradient(160deg,#0d1118 0%,#080b10 60%,#060810 100%)',
        border:'1px solid rgba(255,255,255,0.11)',
        boxShadow:`0 0 0 1px rgba(255,255,255,0.04),0 60px 140px rgba(0,0,0,0.95),0 0 120px ${ac}18,0 0 60px ${ac}10,inset 0 1px 0 rgba(255,255,255,0.10),inset 0 -1px 0 rgba(0,0,0,0.5)`,
        overflow:'hidden',display:'flex',flexDirection:'column',position:'relative',zIndex:2,
      }}>
        <div style={{position:'absolute',inset:-1,borderRadius:53,background:`conic-gradient(from 0deg,transparent 0%,${ac}60 20%,transparent 40%,#ff008040 60%,transparent 80%,${ac}40 90%,transparent 100%)`,animation:'spin 10s linear infinite',opacity:0.25,pointerEvents:'none',zIndex:0,filter:'blur(2px)'}}/>
        <div style={{position:'absolute',top:0,left:0,right:0,height:200,background:`radial-gradient(ellipse 80% 60% at 50% 0%,${ac}0a,transparent)`,pointerEvents:'none',zIndex:0}}/>
        <div style={{height:44,background:'rgba(6,9,14,0.98)',flexShrink:0,display:'flex',alignItems:'flex-end',padding:'0 22px 8px',justifyContent:'space-between',position:'relative',zIndex:3}}>
          <span style={{fontSize:12,fontWeight:700,fontFamily:'JetBrains Mono',color:'rgba(255,255,255,0.7)'}}>9:41</span>
          <div style={{width:80,height:20,borderRadius:10,background:'rgba(0,0,0,0.8)',border:'1px solid rgba(255,255,255,0.08)'}}/>
          <span style={{fontSize:9,color:'rgba(255,255,255,0.45)',fontFamily:'JetBrains Mono'}}>●●●● 🔋</span>
        </div>
        <AppContent {...{ac, tab, setTab, langKey, setLangKey, MATCHES_TODAY, selectedMatch, agentResults, picks, lastRefresh, liveScores, apisLoading, apiStatus, handleAnalyse, handleAddToTicket, handleAgentResult, handleRemove, handleKITicket, handleTrackBets, showOnboarding, setShowOnboarding, tweaksOn, setTweaksOn, tweaks, setTweaks, tabs}}/>
      </div>
    </div>
  ) : (
    <div style={{width:'100vw',height:'100dvh',display:'flex',flexDirection:'column',position:'relative',overflow:'hidden',background:'#040608'}}>
      <AuroraBackground accent={ac}/>
      <ParticleField accent={ac} count={24}/>
      <div style={{position:'relative',zIndex:2,display:'flex',flexDirection:'column',height:'100dvh',width:'100%'}}>
        <AppContent {...{ac, tab, setTab, langKey, setLangKey, MATCHES_TODAY, selectedMatch, agentResults, picks, lastRefresh, liveScores, apisLoading, apiStatus, handleAnalyse, handleAddToTicket, handleAgentResult, handleRemove, handleKITicket, handleTrackBets, showOnboarding, setShowOnboarding, tweaksOn, setTweaksOn, tweaks, setTweaks, tabs}}/>
      </div>
    </div>
  );
}

// Trennt Phone-Frame-Wrapper von App-Content damit beide Modes denselben Code teilen
function AppContent({ ac, tab, setTab, langKey, setLangKey, MATCHES_TODAY, selectedMatch, agentResults, picks, lastRefresh, liveScores, apisLoading, apiStatus, handleAnalyse, handleAddToTicket, handleAgentResult, handleRemove, handleKITicket, handleTrackBets, showOnboarding, setShowOnboarding, tweaksOn, setTweaksOn, tweaks, setTweaks, tabs }) {
  return (
    <>
      {/* Skip-Link für Tastatur/Screen-Reader User */}
      <a href="#main-content" style={{position:'absolute',left:-9999,top:8,padding:'8px 12px',background:ac,color:'#040608',fontWeight:700,borderRadius:6,zIndex:9999}}
         onFocus={e=>{e.target.style.left='8px';}}
         onBlur={e=>{e.target.style.left='-9999px';}}>
        Zum Inhalt springen
      </a>
      {/* Inner glow top — nur dezent, keine fake notch */}
      <div style={{position:'absolute',top:0,left:0,right:0,height:140,background:`radial-gradient(ellipse 80% 60% at 50% 0%,${ac}0a,transparent)`,pointerEvents:'none',zIndex:0}}/>

        {/* App Header */}
        <div style={{padding:'18px 16px 12px',flexShrink:0,background:'rgba(6,9,14,0.90)',backdropFilter:'blur(32px)',borderBottom:'1px solid rgba(255,255,255,0.06)',position:'relative',zIndex:3}}>
          <div style={{display:'flex',alignItems:'center',justifyContent:'space-between'}}>
            <div style={{display:'flex',alignItems:'center',gap:10}}>
              {/* Animated Football Logo with Wings */}
              <WingedLogo size={38} accent={ac}/>
              <div>
                <HoloText colors={[ac,'#00ff88','#ffffff',ac]} size={15}>FUSSBALL AI</HoloText>
                <div style={{fontSize:7,color:'rgba(255,255,255,0.3)',fontFamily:'JetBrains Mono',letterSpacing:'.12em',marginTop:1}}>{t('headerSub')||'9 AGENTS · WEATHER · KELLY'}</div>
              </div>
            </div>
            <LangSwitcher onLangChange={()=>setLangKey(k=>k+1)}/>
          </div>
        </div>

        {/* Screen Content */}
        <main id="main-content" role="main" aria-label="Inhalt" style={{flex:1,overflow:'hidden',position:'relative',zIndex:2}}>
          {showOnboarding && <OnboardingScreen onDone={()=>setShowOnboarding(false)} accent={ac}/>}
          <div role="tabpanel" id={`panel-${tab}`} aria-labelledby={`tab-${tab}`} key={`${tab}-${langKey}`} style={{position:'relative',height:'100%',animation:'fadeUp .35s ease both'}}>
            {tab==='heute'    && <HeuteScreen onAnalyse={handleAnalyse} onAddToTicket={handleAddToTicket} agentResults={agentResults} lastRefresh={lastRefresh} liveScores={liveScores} apiLoading={apisLoading}/>}
            {tab==='agenten'  && <AgentPipeline match={selectedMatch} matches={MATCHES_TODAY} onResultReady={handleAgentResult} onAddToTicket={handleAddToTicket}/>}
            {tab==='scheine'  && <ScheineScreen picks={picks} onRemovePick={handleRemove} onUseKITicket={handleKITicket} matches={MATCHES_TODAY} onTrackBets={handleTrackBets}/>}
            {tab==='info'     && <InfoScreen apiStatus={apiStatus}/>}
          </div>
        </main>

        {/* Floating Glass Nav — transparent, Aurora schimmert durch */}
        <div style={{flexShrink:0,padding:'8px 10px calc(14px + env(safe-area-inset-bottom, 0px))',background:'linear-gradient(to top, rgba(4,6,8,0.55) 0%, rgba(4,6,8,0.25) 60%, transparent 100%)',backdropFilter:'blur(18px) saturate(1.2)',WebkitBackdropFilter:'blur(18px) saturate(1.2)',borderTop:'1px solid rgba(255,255,255,0.06)',position:'relative',zIndex:10}}>
          <CopyrightFooter accent={ac} compact={true}/>
          <div role="tablist" aria-label="Hauptnavigation" style={{display:'flex',alignItems:'center',background:'rgba(255,255,255,0.04)',borderRadius:20,padding:'2px',border:'1px solid rgba(255,255,255,0.10)',backdropFilter:'blur(14px) saturate(1.3)',WebkitBackdropFilter:'blur(14px) saturate(1.3)',boxShadow:`0 0 30px ${ac}10, inset 0 1px 0 rgba(255,255,255,0.05)`}}>
            {tabs.map(tb=><NavTab key={tb.id} tab={tb} active={tab===tb.id} accent={ac} onClick={()=>setTab(tb.id)}/>)}
          </div>
        </div>

      {/* Tweaks Panel */}
      {tweaksOn && (
        <TweaksPanel onClose={()=>{setTweaksOn(false);window.parent.postMessage({type:'__edit_mode_dismissed'},'*');}}>
          <TweakSection title="Akzentfarbe">
            <TweakColor label="Neon Farbe" value={tweaks.accentColor} onChange={v=>{setTweaks(p=>({...p,accentColor:v}));window.parent.postMessage({type:'__edit_mode_set_keys',edits:{accentColor:v}},'*');}}/>
          </TweakSection>
          <TweakSection title="Auto-Refresh">
            <TweakSlider label="Minuten" value={tweaks.autoRefreshMin} min={1} max={30} step={1} onChange={v=>{setTweaks(p=>({...p,autoRefreshMin:v}));window.parent.postMessage({type:'__edit_mode_set_keys',edits:{autoRefreshMin:v}},'*');}}/>
          </TweakSection>
          <TweakSection title="Risiko">
            <TweakRadio label="Standard" value={tweaks.riskMode} options={['SAFE','GOOD','RISK']} onChange={v=>{setTweaks(p=>({...p,riskMode:v}));window.parent.postMessage({type:'__edit_mode_set_keys',edits:{riskMode:v}},'*');}}/>
          </TweakSection>
        </TweaksPanel>
      )}
    </>
  );
}

// ─── Error Boundary ─────────────────────────────────────────────
// React fängt nur Render-Errors innerhalb einer Class-Component ab.
// Ohne Boundary crasht ein Fehler in irgendeinem Modul (window.poisson,
// window.tracker etc.) zur weißen Seite. Mit Boundary: lokales Reset
// + sichtbares Fallback ohne Datenverlust (LocalStorage bleibt intakt).
class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { error: null, info: null };
  }
  static getDerivedStateFromError(error) {
    return { error };
  }
  componentDidCatch(error, info) {
    this.setState({ info });
    try {
      console.error('[FUSSBALL AI] Render-Crash:', error, info?.componentStack);
    } catch {}
  }
  reset = () => this.setState({ error: null, info: null });
  hardReset = () => {
    try { localStorage.clear(); } catch {}
    location.reload();
  };
  render() {
    if (!this.state.error) return this.props.children;
    const msg = this.state.error?.message || String(this.state.error);
    return (
      <div role="alert" aria-live="assertive" style={{
        minHeight:'100dvh', padding:'24px', display:'flex', flexDirection:'column',
        alignItems:'center', justifyContent:'center', gap:16,
        background:'#040608', color:'#e6f1ff', fontFamily:'Inter,sans-serif',
      }}>
        <div style={{
          maxWidth:520, width:'100%', padding:24, borderRadius:16,
          background:'rgba(255,84,112,0.08)', border:'1px solid rgba(255,84,112,0.4)',
          boxShadow:'0 0 40px rgba(255,84,112,0.25)',
        }}>
          <h1 style={{ fontSize:18, marginBottom:8, color:'#ff5470' }}>
            ⚠ Etwas ist schiefgelaufen
          </h1>
          <p style={{ fontSize:13, opacity:0.85, marginBottom:14, lineHeight:1.5 }}>
            Die App konnte einen Render-Fehler nicht verarbeiten. Deine Tickets &
            Bankroll bleiben in <code>localStorage</code> erhalten.
          </p>
          <pre style={{
            fontSize:11, fontFamily:'JetBrains Mono,monospace', padding:10,
            background:'rgba(0,0,0,0.4)', border:'1px solid rgba(255,255,255,0.08)',
            borderRadius:8, overflow:'auto', maxHeight:160, marginBottom:14,
          }}>{msg}</pre>
          <div style={{ display:'flex', gap:10, flexWrap:'wrap' }}>
            <button onClick={this.reset} style={btnPrimary}>↻ Erneut versuchen</button>
            <button onClick={() => location.reload()} style={btnSecondary}>Reload</button>
            <button onClick={this.hardReset} style={btnDanger}>Cache leeren</button>
          </div>
        </div>
      </div>
    );
  }
}
const btnPrimary = { padding:'10px 16px', fontSize:13, fontWeight:600, borderRadius:8, border:'1px solid #00f5ff', background:'rgba(0,245,255,0.15)', color:'#00f5ff', cursor:'pointer' };
const btnSecondary = { padding:'10px 16px', fontSize:13, fontWeight:500, borderRadius:8, border:'1px solid rgba(255,255,255,0.2)', background:'transparent', color:'#e6f1ff', cursor:'pointer' };
const btnDanger = { padding:'10px 16px', fontSize:13, fontWeight:500, borderRadius:8, border:'1px solid rgba(255,84,112,0.5)', background:'transparent', color:'#ff5470', cursor:'pointer' };

ReactDOM.createRoot(document.getElementById('root')).render(
  <ErrorBoundary><App/></ErrorBoundary>
);
