// fp-tickets.jsx v2 — KI-Fertigscheine + Ticket Builder
const { useState: useST, useEffect: useET, useMemo: useMT, useRef: useRT } = React;

// ─── KI Ticket Card ───────────────────────────────────────────
function KITicketCard({ ticket }) {
  const [expanded, setExpanded] = useST(false);
  const rc = getRiskColor(ticket.risk);

  const riskGrad = {
    SAFE: 'linear-gradient(135deg, rgba(34,255,136,0.10), rgba(34,255,136,0.03))',
    GOOD: 'linear-gradient(135deg, rgba(255,182,72,0.10), rgba(255,182,72,0.03))',
    RISK: 'linear-gradient(135deg, rgba(255,84,112,0.10), rgba(255,84,112,0.03))',
  }[ticket.risk] || 'rgba(255,255,255,0.03)';

  return (
    <div style={{
      background: riskGrad,
      border: `1px solid ${rc}33`,
      borderRadius: 20, overflow: 'hidden',
      boxShadow: `0 0 24px ${rc}10, inset 0 1px 0 rgba(255,255,255,0.05)`,
      backdropFilter: 'blur(16px)',
      animation: 'fadeUp 0.4s ease both',
      marginBottom: 14,
    }}>
      {/* Header */}
      <div onClick={() => setExpanded(!expanded)} style={{ padding: '14px 16px', cursor: 'pointer' }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 10 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <div style={{
              fontSize: 13, background: rc + '22', color: rc, padding: '3px 10px',
              borderRadius: 99, fontFamily: 'JetBrains Mono', fontWeight: 700, letterSpacing: '0.06em'
            }}>{getRiskIcon(ticket.risk)} {ticket.label}</div>
            <div style={{ fontSize: 9, color: 'rgba(255,255,255,0.3)', fontFamily: 'JetBrains Mono' }}>{ticket.type}</div>
          </div>
          <span style={{ fontSize: 10, color: 'rgba(255,255,255,0.25)', transform: expanded ? 'rotate(180deg)' : 'none', transition: 'transform 0.3s' }}>▼</span>
        </div>

        {/* Stats Row */}
        <div style={{ display: 'flex', gap: 10, alignItems: 'center', marginBottom: 10 }}>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 9, color: 'rgba(255,255,255,0.35)', fontFamily: 'JetBrains Mono', letterSpacing: '0.1em', marginBottom: 3 }}>GESAMTQUOTE</div>
            <div style={{ fontSize: 26, fontWeight: 700, fontFamily: 'JetBrains Mono', color: '#ffb648', lineHeight: 1, textShadow:'0 0 14px #ffb648cc, 0 0 32px #ffb64866' }}>{ticket.totalOdds.toFixed(2)}</div>
          </div>
          <div style={{ textAlign: 'center' }}>
            <div style={{ fontSize: 9, color: 'rgba(255,255,255,0.35)', fontFamily: 'JetBrains Mono', letterSpacing: '0.1em', marginBottom: 3 }}>TIPPS</div>
            <div style={{ fontSize: 22, fontWeight: 700, fontFamily: 'JetBrains Mono', color: 'rgba(255,255,255,0.8)' }}>{ticket.picks.length}</div>
          </div>
          <div style={{ textAlign: 'right' }}>
            <div style={{ fontSize: 9, color: 'rgba(255,255,255,0.35)', fontFamily: 'JetBrains Mono', letterSpacing: '0.1em', marginBottom: 3 }}>BEI €10</div>
            <div style={{ fontSize: 22, fontWeight: 700, fontFamily: 'JetBrains Mono', color: '#22ff88', textShadow:'0 0 12px #22ff88cc, 0 0 24px #22ff8866' }}>€{(ticket.totalOdds * 10).toFixed(0)}</div>
          </div>
        </div>

        {/* Confidence Bar */}
        <div style={{ marginBottom: 8 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 4 }}>
            <span style={{ fontSize: 9, color: 'rgba(255,255,255,0.35)', fontFamily: 'JetBrains Mono', letterSpacing: '0.1em' }}>KI-KONFIDENZ</span>
            <span style={{ fontSize: 9, fontFamily: 'JetBrains Mono', color: rc }}>{ticket.avgConfidence}%</span>
          </div>
          <div style={{ height: 4, background: 'rgba(255,255,255,0.06)', borderRadius: 99, overflow: 'hidden' }}>
            <div style={{ height: '100%', width: `${ticket.avgConfidence}%`, background: `linear-gradient(90deg, ${rc}, ${rc}88)`, borderRadius: 99, boxShadow: `0 0 8px ${rc}`, transition: 'width 0.8s ease' }} />
          </div>
        </div>

        {/* Reasoning */}
        <p style={{ fontSize: 11, color: 'rgba(255,255,255,0.55)', lineHeight: 1.55, margin: 0, fontFamily: 'Inter' }}>{ticket.reasoning}</p>
      </div>

      {/* Expanded Picks */}
      {expanded && (
        <div style={{ borderTop: `1px solid ${rc}15`, padding: '12px 16px' }}>
          <div style={{ fontSize: 9, color: 'rgba(255,255,255,0.3)', fontFamily: 'JetBrains Mono', letterSpacing: '0.12em', marginBottom: 10 }}>PICKS</div>
          {ticket.picks.map((p, i) => (
            <div key={i} style={{
              display: 'flex', alignItems: 'center', gap: 10, padding: '9px 10px',
              background: 'rgba(255,255,255,0.03)', borderRadius: 10,
              border: '1px solid rgba(255,255,255,0.06)', marginBottom: 6,
            }}>
              <div style={{
                width: 22, height: 22, borderRadius: '50%', background: `${rc}20`,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontSize: 9, fontFamily: 'JetBrains Mono', fontWeight: 700, color: rc, flexShrink: 0
              }}>{i+1}</div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 10, color: 'rgba(255,255,255,0.35)', fontFamily: 'JetBrains Mono', letterSpacing: '0.08em', marginBottom: 1 }}>
                  {p.leagueFlag} {p.league} · {p.time}
                </div>
                <div style={{ fontSize: 12, fontWeight: 600, fontFamily: 'Space Grotesk', color: 'rgba(255,255,255,0.85)', marginBottom: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                  {p.home} vs {p.away}
                </div>
                <div style={{ fontSize: 11, color: rc, fontFamily: 'Inter' }}>{p.bet_label}</div>
              </div>
              <div style={{ textAlign: 'right', flexShrink: 0 }}>
                <div style={{ fontSize: 15, fontWeight: 700, fontFamily: 'JetBrains Mono', color: '#ffb648', textShadow:'0 0 8px #ffb648aa' }}>{p.odds.toFixed(2)}</div>
                <div style={{ fontSize: 8, color: getRiskColor(p.risk), fontFamily: 'JetBrains Mono' }}>{p.risk}</div>
              </div>
            </div>
          ))}
          {ticket.type === 'SYSTEM' && (
            <div style={{ padding: '8px 10px', background: 'rgba(94,231,255,0.06)', borderRadius: 10, border: '1px solid rgba(94,231,255,0.15)', marginBottom: 10 }}>
              <span style={{ fontSize: 10, color: '#5ee7ff', fontFamily: 'JetBrains Mono' }}>System {ticket.systemLabel} · {ticket.sheetCount} Scheine · €{ticket.sheetCount * 5} Gesamteinsatz</span>
            </div>
          )}
        </div>
      )}

    </div>
  );
}

// ─── KI Scheine Generator (type-aware: classic / ht / korner) ─
const KI_CACHE_KEY = (type, lang) => `fai_ki_tickets_${type}_${lang||'de'}_v1`;
function loadKICache(type='classic') {
  try {
    const raw = localStorage.getItem(KI_CACHE_KEY(type, currentLang));
    if (!raw) return null;
    const data = JSON.parse(raw);
    const today = new Date().toISOString().split('T')[0];
    if (data.date !== today) return null;
    return data;
  } catch { return null; }
}
function saveKICache(tickets, type='classic') {
  try {
    localStorage.setItem(KI_CACHE_KEY(type, currentLang), JSON.stringify({
      date: new Date().toISOString().split('T')[0],
      timestamp: Date.now(),
      tickets,
      lang: currentLang,
    }));
  } catch {}
}

function getKiTypes() {
  return [
    { id:'classic', label:'🤖 ' + t('classic'),  desc: t('classicDesc'),  count:3 },
    { id:'ht',      label:'🕐 ' + t('halftime'), desc: t('halftimeDesc'), count:3 },
    { id:'oubtts',  label:'⚽ O/U + BTTS',       desc: currentLang==='tr'?'Sadece Üst/Alt + Karşılıklı':currentLang==='en'?'Only Over/Under + BTTS':'Nur Über/Unter + Beide treffen', count:3 },
    { id:'korner',  label:'🚩 ' + t('corners'),  desc: t('cornersDesc'),  count:3 },
  ];
}

function KIScheine({ matches, onUseTicket }) {
  const [type, setType] = useST('classic');
  const cached = loadKICache(type);
  const [loading, setLoading] = useST(false);
  const [tickets, setTickets] = useST(cached?.tickets || []);
  const [error, setError] = useST(null);
  const [cachedAt, setCachedAt] = useST(cached?.timestamp || null);

  // Re-load cache when type changes
  useET(() => {
    const c = loadKICache(type);
    setTickets(c?.tickets || []);
    setCachedAt(c?.timestamp || null);
    setError(null);
  }, [type]);

  const generate = async () => {
    setLoading(true); setError(null);
    const mList = matches.slice(0, 10).map(m =>
      `${m.home} vs ${m.away} (${m.leagueName||m.leagueShort||m.league}, ${m.time}Uhr): H=${m.odds.home} X=${m.odds.draw} A=${m.odds.away} BTTS=${m.btts?.yes} O2.5=${m.overUnder?.o25} xG(H)=${m.xG?.home} xG(A)=${m.xG?.away} Form(H)=${m.form?.home?.join('')||''} Form(A)=${m.form?.away?.join('')||''} H2H=${m.h2h} AvgGoals=${m.avgGoals}`
    ).join('\n');

    const PROMPTS = {
      classic: `Du bist ein Elite-Wettexperte. Erstelle 3 fertige Wettscheine für heute basierend auf diesen Spielen:

${mList}

Erstelle exakt diese 3 Scheine:
1. SAFE KOMBI: 3-4 sichere Tipps, Quote 2.5-6.0, nur klare Favoriten/O2.5/BTTS
2. BALANCED SYSTEM: 5-6 Tipps als System 5/6, Mix aus sicheren und guten Picks
3. HIGH RISK KOMBI: 3-4 risikoreiche Tipps mit hohen Quoten (Außenseiter, HT/FT, Handicap, hohe O/U)

Antworte NUR als JSON: {"tickets":[{"label":"SAFE KOMBI","type":"KOMBI","risk":"SAFE","reasoning":"2 Sätze","picks":[{"home":"...","away":"...","league":"...","leagueFlag":"🇩🇪","time":"21:00","bet_label":"...","odds":1.65,"risk":"SAFE"}]},{"label":"BALANCED SYSTEM","type":"SYSTEM","risk":"GOOD","systemLabel":"5/6","sheetCount":6,"reasoning":"...","picks":[...]},{"label":"HIGH RISK","type":"KOMBI","risk":"RISK","reasoning":"...","picks":[...]}]}`,

      ht: `Du bist Spezialist für Halbzeit-Wetten. Erstelle 3 Halbzeit-Wettscheine (Safe/Balanced/Risk) basierend auf diesen Spielen:

${mList}

Halbzeit-Märkte: 1.HZ-Sieger (1/X/2 erste Hälfte), 1.HZ-BTTS (beide treffen vor Pause), 1.HZ-Über 0.5/1.5 Tore, Halbzeitstand (HT-Score), HT/FT (Halbzeit/Endstand). NUR HT-MÄRKTE.

Erstelle exakt diese 3 Scheine:
1. SAFE HZ-KOMBI: 3-4 sichere HZ-Tipps, Quote 2.0-5.0 gesamt. Nur Über 0.5 1.HZ bei Top-Favoriten + Heim-Stärke.
2. BALANCED HZ-SYSTEM: 5 HZ-Tipps als System 4/5 (1 Fehler erlaubt). Mix aus Über 0.5 1.HZ und 1.HZ-Sieger sicheren Favoriten.
3. HIGH RISK HZ-KOMBI: 3-4 risikoreiche HZ-Tipps, Quote 6.0+. HT/FT-Exotics, Außenseiter-1.HZ-Sieg, 1.HZ-Über 1.5 bei Tor-Spektakel-Spielen.

Antworte NUR als JSON: {"tickets":[{"label":"SAFE HZ-KOMBI","type":"KOMBI","risk":"SAFE","reasoning":"2 Sätze","picks":[{"home":"...","away":"...","league":"...","leagueFlag":"🇩🇪","time":"21:00","bet_label":"Über 0.5 Tore 1.HZ","odds":1.55,"risk":"SAFE","period":"HT"}]},{"label":"BALANCED HZ-SYSTEM","type":"SYSTEM","risk":"GOOD","systemLabel":"4/5","sheetCount":5,"reasoning":"...","picks":[...]},{"label":"HIGH RISK HZ","type":"KOMBI","risk":"RISK","reasoning":"...","picks":[...]}]}`,

      oubtts: `Du bist Tor-Markt-Spezialist. Erstelle 3 Wettscheine (Safe/Balanced/Risk) AUSSCHLIESSLICH mit Über/Unter-Tor-Wetten und BTTS-Märkten — KEINE 1X2-Sieger, KEINE Halbzeit-Märkte, KEINE Korner.

${mList}

Erlaubte Märkte (NUR diese):
- Über/Unter 0.5, 1.5, 2.5, 3.5, 4.5 Tore (Vollzeit)
- BTTS Ja / BTTS Nein (Beide treffen)
- BTTS + Über 2.5 (kombiniert wenn Quote attraktiv)

Erstelle exakt diese 3 Scheine:
1. SAFE TORE-KOMBI: 3-4 sichere Picks, Quote 2.0-5.0. Über 1.5 bei xG-Summe > 2.4, BTTS bei beiden Teams xG ≥ 1.2 und Heim+Gast offensiv.
2. BALANCED TORE-SYSTEM: 5 Picks als System 4/5 (1 Fehler erlaubt). Mix aus Über 2.5 und BTTS.
3. HIGH RISK TORE: 3-4 risikoreiche Picks, Quote 6.0+. Über 3.5 bei Tor-Spektakel-Spielen, BTTS+Über 2.5 Kombi-Märkte.

Antworte NUR als JSON: {"tickets":[{"label":"SAFE TORE-KOMBI","type":"KOMBI","risk":"SAFE","reasoning":"2 Sätze","picks":[{"home":"...","away":"...","league":"...","leagueFlag":"🇩🇪","time":"21:00","bet_label":"Über 2.5 Tore","odds":1.65,"risk":"SAFE","market":"GOALS"}]},{"label":"BALANCED TORE-SYSTEM","type":"SYSTEM","risk":"GOOD","systemLabel":"4/5","sheetCount":5,"reasoning":"...","picks":[...]},{"label":"HIGH RISK TORE","type":"KOMBI","risk":"RISK","reasoning":"...","picks":[...]}]}`,

      korner: `Du bist Korner-Markt-Spezialist. Erstelle 3 Korner-Wettscheine (Safe/Balanced/Risk) basierend auf diesen Spielen:

${mList}

Korner-Märkte: Korner-Total Über/Unter (9.5, 10.5, 11.5), Korner-Handicap (Heim/Gast), Erste-Halbzeit-Korner Über/Unter 4.5, Team-Korner (welches Team mehr Korner). NUR KORNER-MÄRKTE.

Erstelle exakt diese 3 Scheine:
1. SAFE KORNER-KOMBI: 3-4 sichere Korner-Tipps, Quote 2.0-4.5. Über 9.5 bei Hochintensiv-Pressing-Teams + offensive Heimfavoriten.
2. BALANCED KORNER-SYSTEM: 5 Korner-Tipps als System 4/5 (1 Fehler erlaubt). Mix Über 9.5 und Team-Korner-Märkte.
3. HIGH RISK KORNER: 3-4 risikoreiche Korner-Tipps, Quote 6.0+. Über 11.5 oder Korner-Handicap-Picks.

Antworte NUR als JSON: {"tickets":[{"label":"SAFE KORNER-KOMBI","type":"KOMBI","risk":"SAFE","reasoning":"2 Sätze","picks":[{"home":"...","away":"...","league":"...","leagueFlag":"🇩🇪","time":"21:00","bet_label":"Über 9.5 Korner","odds":1.75,"risk":"SAFE","market":"CORNERS"}]},{"label":"BALANCED KORNER-SYSTEM","type":"SYSTEM","risk":"GOOD","systemLabel":"4/5","sheetCount":5,"reasoning":"...","picks":[...]},{"label":"HIGH RISK KORNER","type":"KOMBI","risk":"RISK","reasoning":"...","picks":[...]}]}`,
    };
    const prompt = PROMPTS[type] || PROMPTS.classic;

    try {
      const text = await callAI(prompt);
      const match = text.match(/\{[\s\S]*\}/);
      if (!match) throw new Error('Kein JSON');
      const data = JSON.parse(match[0]);
      const enriched = data.tickets.map(t => ({
        ...t,
        totalOdds: t.picks.reduce((a, p) => a * p.odds, 1),
        avgConfidence: Math.round(t.picks.reduce((a, p, _, arr) => a + (p.confidence || (t.risk === 'SAFE' ? 80 : t.risk === 'GOOD' ? 72 : 62)), 0) / t.picks.length),
      }));
      setTickets(enriched);
      saveKICache(enriched, type);
      setCachedAt(Date.now());
      // Auto-Bet: 10€ pro Ticket simulieren
      try { window.autobetStore?.placeForTickets?.(enriched, type); window.autobetStore?.linkToMatches?.(matches); } catch(e) {}
      // Track each pick into outcome logger (für Calibrator)
      try {
        enriched.forEach(t => (t.picks || []).forEach(p => {
          const matched = (matches || []).find(m =>
            (m.home || '').toLowerCase().includes((p.home||'').toLowerCase().split(' ')[0]) ||
            (p.home||'').toLowerCase().includes((m.home||'').toLowerCase().split(' ')[0])
          );
          window.tracker?.logPick({
            matchId: matched?.id || `manual_${p.home}_${p.away}`,
            source: `ki_${t.risk?.toLowerCase() || 'unknown'}`,
            market: (p.bet_label||'').toLowerCase().includes('über')||(p.bet_label||'').toLowerCase().includes('over') ? 'O2.5'
                  : (p.bet_label||'').toLowerCase().includes('btts')||(p.bet_label||'').toLowerCase().includes('beide') ? 'BTTS'
                  : '1X2',
            pick: p.bet_label,
            confidence: p.confidence || (t.risk==='SAFE'?80:t.risk==='GOOD'?72:62),
            oddsAtPick: p.odds,
            kickoff: matched ? new Date().toISOString() : null,
            label: p.bet_label,
            meta: { home: p.home, away: p.away, ticketLabel: t.label },
          });
        }));
      } catch(e) { console.warn('tracker log failed:', e.message); }
    } catch(e) {
      setError(t('generateFailed'));
    }
    setLoading(false);
  };

  useET(() => { if (tickets.length === 0) generate(); }, []);

  if (loading) return (
    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', height: '100%', gap: 16, padding: 32 }}>
      <div style={{ position: 'relative', width: 60, height: 60 }}>
        <div style={{ position: 'absolute', inset: 0, borderRadius: '50%', border: '2px solid rgba(34,255,136,0.15)' }} />
        <div style={{ position: 'absolute', inset: 0, borderRadius: '50%', border: '2px solid #22ff88', borderTopColor: 'transparent', animation: 'spin 1s linear infinite' }} />
        <div style={{ position: 'absolute', inset: 6, borderRadius: '50%', border: '2px solid #5ee7ff', borderBottomColor: 'transparent', animation: 'spin 1.4s linear infinite reverse' }} />
        <div style={{ position: 'absolute', inset: 12, borderRadius: '50%', border: '2px solid #ffb648', borderLeftColor: 'transparent', animation: 'spin 0.8s linear infinite' }} />
      </div>
      <div style={{ textAlign: 'center' }}>
        <div style={{ fontSize: 14, fontWeight: 600, color: 'rgba(255,255,255,0.7)', fontFamily: 'Space Grotesk', marginBottom: 6 }}>{t('generating')}</div>
        <div style={{ fontSize: 11, color: 'rgba(255,255,255,0.35)', fontFamily: 'Inter' }}>Analysiere {matches.length} Spiele · {AGENTS.length} Agenten</div>
      </div>
    </div>
  );

  if (error) return (
    <div style={{ padding: 24, textAlign: 'center' }}>
      <div style={{ fontSize: 13, color: '#ff5470', fontFamily: 'Inter', marginBottom: 16 }}>{error}</div>
      <button onClick={generate} style={{ padding: '10px 24px', background: 'rgba(255,84,112,0.15)', border: '1px solid rgba(255,84,112,0.3)', borderRadius: 10, color: '#ff5470', cursor: 'pointer', fontFamily:'Space Grotesk', fontWeight:600, fontSize:13 }}>{t('retry')}</button>
    </div>
  );

  return (
    <div style={{ padding: '14px 16px', overflowY: 'auto', height: '100%' }}>
      <div style={{ marginBottom: 14 }}>
        <div style={{ fontSize: 9, color: '#22ff88', fontFamily: 'JetBrains Mono', letterSpacing: '0.14em', marginBottom: 3 }}>KI GENERIERT · HEUTE</div>
        <div style={{ fontSize: 18, fontWeight: 700, fontFamily: 'Space Grotesk', color: 'rgba(255,255,255,0.95)' }}>{getKiTypes().find(t=>t.id===type)?.label || 'Fertige Scheine'}</div>
        <div style={{ fontSize: 11, color: 'rgba(255,255,255,0.35)', fontFamily: 'Inter', marginTop: 2 }}>
          {cachedAt ? `${t('saved')} · ${new Date(cachedAt).toLocaleTimeString(currentLang==='tr'?'tr-TR':currentLang==='en'?'en-GB':'de-DE',{hour:'2-digit',minute:'2-digit'})}` : getKiTypes().find(tk=>tk.id===type)?.desc}
        </div>
      </div>
      {/* Type-Selector */}
      <div style={{ display:'flex', gap:5, marginBottom:14, overflowX:'auto', paddingBottom:2 }}>
        {getKiTypes().map(kt => (
          <button key={kt.id} onClick={()=>setType(kt.id)} style={{
            padding:'7px 12px', borderRadius:99, cursor:'pointer', whiteSpace:'nowrap', flexShrink:0,
            background: type===kt.id ? 'rgba(34,255,136,0.12)' : 'rgba(255,255,255,0.04)',
            border: `1px solid ${type===kt.id ? 'rgba(34,255,136,0.4)' : 'rgba(255,255,255,0.1)'}`,
            color: type===kt.id ? '#22ff88' : 'rgba(255,255,255,0.6)',
            fontFamily:'JetBrains Mono', fontWeight:700, fontSize:10, letterSpacing:'.04em',
          }}>{kt.label}</button>
        ))}
      </div>
      {tickets.map((t, i) => <KITicketCard key={i} ticket={t} />)}
      <button onClick={generate} disabled={loading} style={{
        width: '100%', padding: '11px', borderRadius: 12, marginBottom: 24,
        background: 'rgba(255,255,255,0.04)', border: '1px solid rgba(255,255,255,0.08)',
        cursor: loading?'wait':'pointer', color: 'rgba(255,255,255,0.6)',
        fontFamily: 'Space Grotesk', fontWeight: 600, fontSize: 12,
        display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
        opacity: loading?0.5:1,
      }}>🔄 {loading ? t('generating2') : t('generateNew')}</button>
    </div>
  );
}

// ─── Pick Row (Builder) ───────────────────────────────────────
function PickRow({ pick, onRemove }) {
  const c = getRiskColor(pick.risk);
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 12px', background: 'rgba(255,255,255,0.03)', borderRadius: 12, border: `1px solid ${c}20`, marginBottom: 6, animation: 'fadeUp 0.3s ease' }}>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 9, color: 'rgba(255,255,255,0.3)', fontFamily: 'JetBrains Mono', letterSpacing: '0.08em', marginBottom: 2 }}>{pick.leagueFlag || ''} {pick.league} · {pick.time}</div>
        <div style={{ fontSize: 12, fontWeight: 600, fontFamily: 'Space Grotesk', color: 'rgba(255,255,255,0.85)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', marginBottom: 1 }}>{pick.home} vs {pick.away}</div>
        <div style={{ fontSize: 11, color: c, fontFamily: 'Inter' }}>{pick.bet_label}</div>
      </div>
      <div style={{ textAlign: 'right', flexShrink: 0 }}>
        <div style={{ fontSize: 16, fontWeight: 700, fontFamily: 'JetBrains Mono', color: '#ffb648' }}>{pick.odds?.toFixed(2)}</div>
        <div style={{ fontSize: 8, color: c, fontFamily: 'JetBrains Mono', background: c+'18', padding: '1px 5px', borderRadius: 4, marginTop: 1 }}>{pick.risk}</div>
      </div>
      <button onClick={() => onRemove(pick.id)} style={{ width: 28, height: 28, borderRadius: 8, background: 'rgba(255,84,112,0.12)', border: '1px solid rgba(255,84,112,0.25)', color: '#ff5470', cursor: 'pointer', fontSize: 16, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>×</button>
    </div>
  );
}

// System-Definition: ksizes = welche Kombi-Größen werden gebildet, requiredPicks = exakte Anzahl Picks
// K/N: alle C(N,k) Kombis. Trixie/Yankee/Patent etc.: definierte Mehrfach-Größen.
const SYSTEM_TYPES = [
  // K/N Systeme: ein oder mehrere Fehler erlaubt
  { label:'2/3',     ksizes:[2],          requiredPicks:3,  desc:'3 Picks · 3 Doppel · 1 Fehler erlaubt',  group:'K/N' },
  { label:'3/4',     ksizes:[3],          requiredPicks:4,  desc:'4 Picks · 4 Dreier · 1 Fehler erlaubt',  group:'K/N' },
  { label:'4/5',     ksizes:[4],          requiredPicks:5,  desc:'5 Picks · 5 Vierer · 1 Fehler erlaubt',  group:'K/N' },
  { label:'5/6',     ksizes:[5],          requiredPicks:6,  desc:'6 Picks · 6 Fünfer · 1 Fehler erlaubt',  group:'K/N' },
  { label:'6/7',     ksizes:[6],          requiredPicks:7,  desc:'7 Picks · 7 Sechser · 1 Fehler erlaubt', group:'K/N' },
  { label:'4/6',     ksizes:[4],          requiredPicks:6,  desc:'6 Picks · 15 Vierer · 2 Fehler erlaubt', group:'K/N' },
  { label:'5/7',     ksizes:[5],          requiredPicks:7,  desc:'7 Picks · 21 Fünfer · 2 Fehler erlaubt', group:'K/N' },
  // Englische Volletts (alle Größen kombiniert)
  { label:'Trixie',  ksizes:[2,3],        requiredPicks:3,  desc:'3 Picks · 4 Wetten · alle müssen treffen', group:'Vollett' },
  { label:'Patent',  ksizes:[1,2,3],      requiredPicks:3,  desc:'3 Picks · 7 Wetten · jeder Pick zählt einzeln', group:'Vollett' },
  { label:'Yankee',  ksizes:[2,3,4],      requiredPicks:4,  desc:'4 Picks · 11 Wetten', group:'Vollett' },
  { label:'Lucky 15',ksizes:[1,2,3,4],    requiredPicks:4,  desc:'4 Picks · 15 Wetten · 1 Treffer reicht', group:'Vollett' },
  { label:'Lucky 31',ksizes:[1,2,3,4,5],  requiredPicks:5,  desc:'5 Picks · 31 Wetten', group:'Vollett' },
  { label:'Heinz',   ksizes:[2,3,4,5,6],  requiredPicks:6,  desc:'6 Picks · 57 Wetten', group:'Vollett' },
];
function getCombinations(arr, k) {
  const res = []; const h = (s, c) => { if (c.length===k){res.push([...c]);return;} for(let i=s;i<arr.length;i++){c.push(arr[i]);h(i+1,c);c.pop();} }; h(0,[]); return res;
}
function getAllSystemBets(picks, ksizes) {
  const all = [];
  ksizes.forEach(k => { if (picks.length >= k) all.push(...getCombinations(picks, k)); });
  return all;
}

// ─── Edge-Hunter — Quant-only, no LLM ─────────────────────────
function EdgeHunter({ matches, onUseTicket }) {
  const [minEdge, setMinEdge] = useST(3);
  const [tick, setTick] = useST(0);
  const allBets = useMT(() => {
    if (!window.poisson || !matches?.length) return [];
    const bets = [];
    matches.forEach(m => {
      try {
        const sim = window.poisson.simulate(m, 10000);
        if (!sim.bestBets) return;
        sim.bestBets.forEach(b => {
          if (b.edge != null && b.edge >= minEdge/100 && b.odd) {
            bets.push({ ...b, match: m, prob: b.prob });
          }
        });
      } catch {}
    });
    return bets.sort((a,b) => b.edge - a.edge);
  }, [matches, minEdge, tick]);

  const useEdgeTicket = () => {
    const top = allBets.slice(0, 6);
    if (top.length < 2) return;
    const totalOdds = top.reduce((a,b) => a*b.odd, 1);
    const ticket = {
      label: 'EDGE-HUNTER', type:'KOMBI', risk: top.length>=4?'GOOD':'SAFE',
      reasoning: `${top.length} Picks mit positivem Edge (Quant-Modell). Erwarteter Wert: ${(top.reduce((a,b)=>a+b.edge,0)/top.length*100).toFixed(1)}% pro Pick.`,
      totalOdds,
      avgConfidence: Math.round(top.reduce((a,b)=>a+b.prob,0)/top.length*100),
      picks: top.map(b => ({
        home: b.match.home, away: b.match.away,
        league: b.match.leagueShort, leagueFlag: b.match.leagueFlag,
        time: b.match.time, bet_label: b.label,
        odds: b.odd, risk: b.edge>0.08?'SAFE':'GOOD',
        confidence: Math.round(b.prob*100),
      })),
    };
    // Auto-track
    top.forEach(b => window.tracker?.logPick({
      matchId: b.match.id, source: 'edge_hunter',
      market: b.market, pick: b.pick,
      confidence: Math.round(b.prob*100), oddsAtPick: b.odd,
      kickoff: b.match.espnData?.date || null, label: b.label,
      meta: { edge: b.edge },
    }));
    // Auto-Bet 10€
    try { window.autobetStore?.placeForTickets?.([ticket], 'edge_hunter'); window.autobetStore?.linkToMatches?.(matches); } catch(e) {}
    if (onUseTicket) onUseTicket(ticket);
  };

  return (
    <div style={{padding:'14px 16px',overflowY:'auto',height:'100%'}}>
      <div style={{marginBottom:12}}>
        <div style={{fontSize:9,color:'#5ee7ff',fontFamily:'JetBrains Mono',letterSpacing:'.14em',marginBottom:3}}>{t('edgeHunterSub')}</div>
        <div style={{fontSize:18,fontWeight:700,fontFamily:'Space Grotesk',color:'rgba(255,255,255,0.95)'}}>🎯 {t('edgeHunter')}</div>
        <div style={{fontSize:11,color:'rgba(255,255,255,0.4)',fontFamily:'Inter',marginTop:2}}>Poisson-Edge ≥ {minEdge}% {currentLang==='de'?'gegen Markt':currentLang==='tr'?'piyasaya karşı':'vs market'}</div>
      </div>
      <div style={{display:'flex',gap:5,marginBottom:14,flexWrap:'wrap'}}>
        {[2,3,5,8,12].map(v=>(
          <button key={v} onClick={()=>setMinEdge(v)} style={{padding:'5px 11px',borderRadius:99,cursor:'pointer',background:minEdge===v?'rgba(94,231,255,0.15)':'rgba(255,255,255,0.04)',border:`1px solid ${minEdge===v?'#5ee7ff':'rgba(255,255,255,0.08)'}`,color:minEdge===v?'#5ee7ff':'rgba(255,255,255,0.45)',fontFamily:'JetBrains Mono',fontWeight:700,fontSize:11}}>{v}%+</button>
        ))}
        <button onClick={()=>setTick(t=>t+1)} style={{padding:'5px 11px',borderRadius:99,cursor:'pointer',background:'rgba(255,255,255,0.04)',border:'1px solid rgba(255,255,255,0.08)',color:'rgba(255,255,255,0.5)',fontFamily:'Space Grotesk',fontWeight:600,fontSize:11}}>🔄</button>
      </div>
      {allBets.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>
          {t('noEdgesFound').replace('{x}', minEdge)}<br/>{t('loweringThreshold')}
        </div>
      ) : (
        <>
          <div style={{padding:'10px 12px',background:'rgba(34,255,136,0.06)',border:'1px solid rgba(34,255,136,0.2)',borderRadius:12,marginBottom:14}}>
            <div style={{display:'flex',justifyContent:'space-between',alignItems:'center'}}>
              <div>
                <div style={{fontSize:9,color:'#22ff88',fontFamily:'JetBrains Mono',letterSpacing:'.12em'}}>{allBets.length} {t('valuePicks')}</div>
                <div style={{fontSize:14,fontWeight:700,fontFamily:'Space Grotesk',color:'#fff',marginTop:2}}>{t('avgEdge')}: {(allBets.reduce((a,b)=>a+b.edge,0)/allBets.length*100).toFixed(1)}%</div>
              </div>
              <button onClick={useEdgeTicket} disabled={allBets.length<2} style={{padding:'8px 14px',borderRadius:10,background:'rgba(34,255,136,0.15)',border:'1px solid #22ff88',color:'#22ff88',cursor:'pointer',fontFamily:'Space Grotesk',fontWeight:700,fontSize:11}}>{t('topToSlip')}</button>
            </div>
          </div>
          {allBets.slice(0, 20).map((b, i) => (
            <div key={i} style={{padding:'10px 12px',background:'rgba(255,255,255,0.03)',borderRadius:10,marginBottom:6,border:`1px solid ${b.edge>0.08?'rgba(34,255,136,0.25)':b.edge>0.04?'rgba(255,182,72,0.2)':'rgba(255,255,255,0.06)'}`}}>
              <div style={{display:'flex',justifyContent:'space-between',gap:8,alignItems:'flex-start'}}>
                <div style={{flex:1,minWidth:0}}>
                  <div style={{fontSize:9,color:'rgba(255,255,255,0.35)',fontFamily:'JetBrains Mono',letterSpacing:'.08em'}}>{b.match.leagueFlag} {b.match.leagueShort} · {b.match.time}</div>
                  <div style={{fontSize:12,fontWeight:600,fontFamily:'Space Grotesk',color:'rgba(255,255,255,0.85)',whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>{b.match.home} vs {b.match.away}</div>
                  <div style={{fontSize:11,color:'#5ee7ff',fontFamily:'Inter',marginTop:2}}>{b.label}</div>
                </div>
                <div style={{textAlign:'right',flexShrink:0}}>
                  <div style={{fontSize:14,fontWeight:700,fontFamily:'JetBrains Mono',color:'#ffb648',textShadow:'0 0 8px #ffb648,0 0 16px #ffb64880'}}>{b.odd?.toFixed(2)}</div>
                  <div style={{fontSize:10,fontWeight:700,fontFamily:'JetBrains Mono',color:b.edge>0.08?'#22ff88':b.edge>0.04?'#ffb648':'rgba(255,255,255,0.5)',marginTop:1,textShadow:`0 0 8px currentColor`}}>+{(b.edge*100).toFixed(1)}%</div>
                  <div style={{fontSize:9,color:'rgba(255,255,255,0.3)',fontFamily:'JetBrains Mono',marginTop:1}}>{(b.prob*100).toFixed(0)}%</div>
                </div>
              </div>
            </div>
          ))}
        </>
      )}
    </div>
  );
}

// ─── Manual Ticket Builder ────────────────────────────────────
function TicketBuilder({ picks, onRemovePick }) {
  const [ticketType, setTicketType] = useST('combo');
  const [systemLabel, setSystemLabel] = useST('5/6');
  const [stake, setStake] = useST(10);
  const sel = SYSTEM_TYPES.find(s => s.label === systemLabel) || SYSTEM_TYPES[3];
  const comboOdds = useMT(() => picks.reduce((a, p) => a * (p.odds || 1.8), 1), [picks]);
  const comboPotential = comboOdds * stake;
  const allBets = useMT(() => picks.length >= Math.min(...sel.ksizes) ? getAllSystemBets(picks, sel.ksizes) : [], [picks, sel]);
  const sheets = allBets.length;
  const allPotentials = allBets.map(c => c.reduce((a, p) => a * (p.odds || 1.8), 1) * stake);
  const minWin = allPotentials.length ? Math.min(...allPotentials) : 0;
  const maxWin = allPotentials.length ? Math.max(...allPotentials) : 0;
  const picksOk = picks.length >= sel.requiredPicks;

  const tabStyle = (a) => ({
    flex: 1, padding: '8px', borderRadius: 10, border: 'none', cursor: 'pointer',
    fontFamily: 'Space Grotesk', fontWeight: 600, fontSize: 12,
    background: a ? 'rgba(34,255,136,0.15)' : 'transparent',
    color: a ? '#22ff88' : 'rgba(255,255,255,0.4)', transition: 'all 0.2s',
  });

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      <div style={{ padding: '12px 16px 0', flexShrink: 0 }}>
        <div style={{ fontSize: 9, color: 'rgba(255,255,255,0.35)', fontFamily: 'JetBrains Mono', letterSpacing: '0.14em', marginBottom: 10 }}>{t('manualSlip')}</div>
        <div style={{ display: 'flex', background: 'rgba(255,255,255,0.04)', borderRadius: 12, padding: 3, marginBottom: 12, gap: 2 }}>
          <button style={tabStyle(ticketType==='combo')} onClick={() => setTicketType('combo')}>{t('combo')}</button>
          <button style={tabStyle(ticketType==='system')} onClick={() => setTicketType('system')}>{t('system')}</button>
        </div>
      </div>
      <div style={{ flex: 1, overflowY: 'auto', padding: '0 16px' }}>
        {picks.length === 0 ? (
          <div style={{ textAlign: 'center', padding: '32px 20px', color: 'rgba(255,255,255,0.2)', fontFamily: 'Inter', fontSize: 12 }}>
            <div style={{ fontSize: 36, marginBottom: 10, opacity: 0.5 }}>🎟️</div>
            Öffne "Heute" → Spiel analysieren<br/>→ "+ Zum Schein" tippen
          </div>
        ) : picks.map(p => <PickRow key={p.id} pick={p} onRemove={onRemovePick} />)}

        {ticketType === 'system' && picks.length >= 2 && (
          <div style={{ marginTop: 8 }}>
            <div style={{ fontSize: 9, color: 'rgba(255,255,255,0.3)', fontFamily: 'JetBrains Mono', letterSpacing: '0.12em', marginBottom: 6, marginTop: 4 }}>{t('sysFehler')}</div>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 5, marginBottom: 10 }}>
              {SYSTEM_TYPES.filter(s => s.group === 'K/N').map(s => (
                <button key={s.label} onClick={() => setSystemLabel(s.label)} style={{
                  padding: '5px 11px', borderRadius: 8, cursor: 'pointer',
                  background: systemLabel===s.label ? 'rgba(94,231,255,0.15)' : 'rgba(255,255,255,0.04)',
                  border: `1px solid ${systemLabel===s.label ? '#5ee7ff' : 'rgba(255,255,255,0.08)'}`,
                  color: systemLabel===s.label ? '#5ee7ff' : 'rgba(255,255,255,0.55)',
                  fontFamily: 'JetBrains Mono', fontWeight: 700, fontSize: 11,
                }}>{s.label}</button>
              ))}
            </div>
            <div style={{ fontSize: 9, color: 'rgba(255,255,255,0.3)', fontFamily: 'JetBrains Mono', letterSpacing: '0.12em', marginBottom: 6 }}>{t('sysVollett')}</div>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 5 }}>
              {SYSTEM_TYPES.filter(s => s.group === 'Vollett').map(s => (
                <button key={s.label} onClick={() => setSystemLabel(s.label)} style={{
                  padding: '5px 11px', borderRadius: 8, cursor: 'pointer',
                  background: systemLabel===s.label ? 'rgba(255,215,0,0.15)' : 'rgba(255,255,255,0.04)',
                  border: `1px solid ${systemLabel===s.label ? '#ffd700' : 'rgba(255,255,255,0.08)'}`,
                  color: systemLabel===s.label ? '#ffd700' : 'rgba(255,255,255,0.55)',
                  fontFamily: 'JetBrains Mono', fontWeight: 700, fontSize: 11,
                }}>{s.label}</button>
              ))}
            </div>
          </div>
        )}
      </div>

      {picks.length >= 2 && (
        <div style={{ padding: '12px 16px 14px', borderTop: '1px solid rgba(255,255,255,0.05)', flexShrink: 0 }}>
          <div style={{ display: 'flex', gap: 5, marginBottom: 10, flexWrap: 'wrap' }}>
            {[2,5,10,20,50].map(v => (
              <button key={v} onClick={() => setStake(v)} style={{
                padding: '5px 11px', borderRadius: 8, cursor: 'pointer',
                background: stake===v ? 'rgba(34,255,136,0.15)' : 'rgba(255,255,255,0.04)',
                border: `1px solid ${stake===v ? '#22ff88' : 'rgba(255,255,255,0.08)'}`,
                color: stake===v ? '#22ff88' : 'rgba(255,255,255,0.4)',
                fontFamily: 'JetBrains Mono', fontWeight: 600, fontSize: 12,
              }}>€{v}</button>
            ))}
          </div>
          {ticketType === 'combo' ? (
            <div style={{ background: 'rgba(255,182,72,0.08)', border: '1px solid rgba(255,182,72,0.2)', borderRadius: 14, padding: '12px 14px' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 4 }}>
                <span style={{ fontSize: 11, color: 'rgba(255,255,255,0.4)', fontFamily: 'Inter' }}>{picks.length}-fach Kombi · €{stake}</span>
                <span style={{ fontSize: 12, fontFamily: 'JetBrains Mono', fontWeight: 700, color: '#ffb648' }}>Quote: {comboOdds.toFixed(2)}</span>
              </div>
              <div style={{ fontSize: 22, fontWeight: 700, fontFamily: 'JetBrains Mono', color: '#22ff88', textAlign: 'right' }}>→ €{comboPotential.toFixed(2)}</div>
            </div>
          ) : (
            <div style={{ background: 'rgba(94,231,255,0.06)', border: `1px solid ${picksOk?'rgba(94,231,255,0.18)':'rgba(255,84,112,0.3)'}`, borderRadius: 14, padding: '12px 14px' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 4 }}>
                <span style={{ fontSize: 11, color: 'rgba(255,255,255,0.4)', fontFamily: 'Inter' }}>System {systemLabel} · {sheets} Wetten</span>
                <span style={{ fontSize: 11, fontFamily: 'JetBrains Mono', color: '#5ee7ff' }}>€{(stake*sheets).toFixed(0)} Einsatz</span>
              </div>
              <div style={{fontSize:9,color:'rgba(255,255,255,0.35)',fontFamily:'JetBrains Mono',marginBottom:6}}>{sel.desc}</div>
              {!picksOk && <div style={{fontSize:10,color:'#ff5470',fontFamily:'Inter',marginBottom:6}}>⚠ {t('needsPicks').replace('{n}', sel.requiredPicks).replace('{m}', picks.length)}</div>}
              <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                <span style={{ fontSize: 11, color: 'rgba(255,255,255,0.4)', fontFamily: 'Inter' }}>Min/Max Gewinn</span>
                <span style={{ fontSize: 16, fontFamily: 'JetBrains Mono', fontWeight: 700, color: '#22ff88' }}>€{minWin.toFixed(0)} – €{maxWin.toFixed(0)}</span>
              </div>
            </div>
          )}
        </div>
      )}
    </div>
  );
}

// ─── Daily Best Screen ────────────────────────────────────────
function DailyBestCard({ pick, rank, accentColor }) {
  const [exp, setExp] = useST(false);
  return (
    <div onClick={() => setExp(!exp)} style={{
      background: `${accentColor}09`, border: `1px solid ${accentColor}28`,
      borderRadius: 16, padding: '12px 14px', cursor: 'pointer',
      boxShadow: exp ? `0 0 20px ${accentColor}12` : 'none',
      transition: 'all 0.3s ease', marginBottom: 8,
      backdropFilter: 'blur(12px)',
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
        <div style={{ width: 30, height: 30, borderRadius: '50%', background: `${accentColor}20`, border: `1.5px solid ${accentColor}55`, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 12, fontFamily: 'JetBrains Mono', fontWeight: 700, color: accentColor, flexShrink: 0 }}>#{rank}</div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 9, color: 'rgba(255,255,255,0.3)', fontFamily: 'JetBrains Mono', letterSpacing: '0.08em', marginBottom: 1 }}>{pick.league} · {pick.time}</div>
          <div style={{ fontSize: 12, fontWeight: 600, fontFamily: 'Space Grotesk', color: 'rgba(255,255,255,0.88)' }}>{pick.home} vs {pick.away}</div>
        </div>
        <div style={{ textAlign: 'right', flexShrink: 0 }}>
          <div style={{ fontSize: 17, fontWeight: 700, fontFamily: 'JetBrains Mono', color: '#ffb648' }}>{formatOdds(pick.odds)}</div>
          <div style={{ fontSize: 9, color: accentColor, fontFamily: 'JetBrains Mono' }}>{pick.bet_label}</div>
        </div>
        <span style={{ fontSize: 9, color: 'rgba(255,255,255,0.25)', transform: exp ? 'rotate(180deg)' : 'none', transition: 'transform 0.3s', flexShrink: 0 }}>▼</span>
      </div>
      {exp && (
        <div style={{ marginTop: 10, paddingTop: 10, borderTop: `1px solid ${accentColor}15` }}>
          <div style={{ display: 'flex', gap: 6, marginBottom: 8 }}>
            <span style={{ fontSize: 9, background: getRiskColor(pick.risk)+'18', color: getRiskColor(pick.risk), padding: '2px 8px', borderRadius: 99, fontFamily: 'JetBrains Mono' }}>{getRiskIcon(pick.risk)} {pick.risk}</span>
            <span style={{ fontSize: 9, background: accentColor+'15', color: accentColor, padding: '2px 8px', borderRadius: 99, fontFamily: 'JetBrains Mono' }}>{pick.confidence}%</span>
          </div>
          <p style={{ fontSize: 11, color: 'rgba(255,255,255,0.6)', lineHeight: 1.55, margin: 0, fontFamily: 'Inter' }}>{pick.reasoning}</p>
        </div>
      )}
    </div>
  );
}

function DailyBestScreen({ matches }) {
  const [loading, setLoading] = useST(false);
  const [data, setData] = useST(null);

  const load = async () => {
    setLoading(true); setData(null);
    const mList = matches.map(m => `${m.home} vs ${m.away}(${m.league}): O2.5=${m.overUnder.o25} U2.5=${m.overUnder.u25} BTTS=${m.btts.yes} H=${m.odds.home} X=${m.odds.draw} A=${m.odds.away} xG(H)=${m.xG.home} xG(A)=${m.xG.away} Form(H)=${m.form.home.join('')} Form(A)=${m.form.away.join('')} AvgGoals=${m.avgGoals}`).join('\n');
    const prompt = `Du bist Elite-Wettexperte. Analysiere und wähle Top 3 für jede Kategorie:\n${mList}\nAntworte NUR als JSON:\n{"overUnder":[{"home":"...","away":"...","league":"...","time":"...","bet_label":"Über 2.5 Tore","odds":1.85,"confidence":78,"risk":"SAFE","reasoning":"..."}],"btts":[...],"homeAway":[...]}`;
    try {
      const text = await callAI(prompt);
      const match = text.match(/\{[\s\S]*\}/);
      if (match) setData(JSON.parse(match[0]));
    } catch(e) {}
    setLoading(false);
  };

  useET(() => { load(); }, []);

  const sections = [
    { key:'overUnder', label:'ÜBER / UNTER TORE', icon:'⚽', color:'#22ff88' },
    { key:'btts',      label:'BEIDE TREFFEN',     icon:'🎯', color:'#5ee7ff' },
    { key:'homeAway',  label:'1X2 BEST PICKS',    icon:'🏠', color:'#ffb648' },
  ];

  return (
    <div style={{ height: '100%', overflowY: 'auto', padding: '16px' }}>
      <div style={{ marginBottom: 16 }}>
        <div style={{ fontSize: 9, color: 'rgba(255,255,255,0.35)', fontFamily: 'JetBrains Mono', letterSpacing: '0.14em', marginBottom: 4 }}>TÄGLICH · KI GENERIERT</div>
        <div style={{ fontSize: 20, fontWeight: 700, fontFamily: 'Space Grotesk', color: 'rgba(255,255,255,0.95)' }}>Daily Best Picks</div>
      </div>
      {loading && (
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', padding: '40px 0', gap: 14 }}>
          <div style={{ width: 36, height: 36, borderRadius: '50%', border: '3px solid #22ff88', borderTopColor: 'transparent', animation: 'spin 0.8s linear infinite' }} />
          <span style={{ fontSize: 12, color: 'rgba(255,255,255,0.35)', fontFamily: 'Inter' }}>Analysiere {matches.length} Spiele...</span>
        </div>
      )}
      {!loading && data && sections.map(s => (
        <div key={s.key} style={{ marginBottom: 22 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
            <span style={{ fontSize: 18 }}>{s.icon}</span>
            <div>
              <div style={{ fontSize: 11, fontWeight: 700, fontFamily: 'JetBrains Mono', letterSpacing: '0.1em', color: s.color }}>{s.label}</div>
            </div>
          </div>
          {(data[s.key] || []).map((p, i) => <DailyBestCard key={i} pick={p} rank={i+1} accentColor={s.color} />)}
        </div>
      ))}
      {!loading && <button onClick={load} style={{ width:'100%', padding:'11px', borderRadius:12, background:'rgba(255,255,255,0.04)', border:'1px solid rgba(255,255,255,0.08)', cursor:'pointer', color:'rgba(255,255,255,0.4)', fontFamily:'Space Grotesk', fontWeight:600, fontSize:12, display:'flex', alignItems:'center', justifyContent:'center', gap:8, marginBottom:24 }}>🔄 Aktualisieren</button>}
    </div>
  );
}

Object.assign(window, { KIScheine, TicketBuilder, DailyBestScreen, EdgeHunter });
