// ═══════════════════════════════════════════════════════════════
// AutoBet-Store — synchronisiert mit Cloudflare KV (global geteilt)
// localStorage dient als Offline-Cache + Failover.
// ═══════════════════════════════════════════════════════════════

const autobetStore = {
  KEY: 'fai_autobets_v2',  // localStorage cache key
  STAKE: 10,
  syncing: false,
  lastSync: 0,

  // ─── Local cache (Offline-Fallback + sofortiges Read) ─────
  loadLocal() {
    try { return JSON.parse(localStorage.getItem(this.KEY) || '[]'); }
    catch { return []; }
  },
  saveLocal(arr) {
    try { localStorage.setItem(this.KEY, JSON.stringify(arr.slice(-800))); }
    catch {}
  },
  load() { return this.loadLocal(); }, // Sync-API für UI

  // ─── Online-Sync ──────────────────────────────────────────
  async pull() {
    try {
      const r = await fetch('/api/store/autobets');
      if (!r.ok) return false;
      const d = await r.json();
      if (Array.isArray(d.autobets)) {
        this.saveLocal(d.autobets);
        this.lastSync = Date.now();
        return true;
      }
    } catch(e) { console.warn('autobet pull failed:', e.message); }
    return false;
  },

  async placeForTickets(tickets, type = 'classic') {
    if (!tickets?.length) return 0;
    try {
      const r = await fetch('/api/store/autobets/place', {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ tickets, type }),
      });
      if (!r.ok) throw new Error(`HTTP ${r.status}`);
      const d = await r.json();
      if (d.added > 0) await this.pull();
      return d.added || 0;
    } catch(e) { console.warn('autobet place failed:', e.message); return 0; }
  },

  async linkToMatches(matches) {
    if (!matches?.length) return 0;
    try {
      const r = await fetch('/api/store/autobets/link', {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ matches: matches.map(m => ({ id: m.id, home: m.home, away: m.away })) }),
      });
      if (!r.ok) return 0;
      const d = await r.json();
      if (d.linked > 0) await this.pull();
      return d.linked || 0;
    } catch { return 0; }
  },

  async resolveMatchPicks(matchId, score) {
    if (!score || score.home == null || score.away == null) return 0;
    try {
      const r = await fetch('/api/store/autobets/resolve', {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ matchId, score }),
      });
      if (!r.ok) return 0;
      const d = await r.json();
      if (d.touched > 0) await this.pull();
      return d.touched || 0;
    } catch { return 0; }
  },

  async clear() {
    try { await fetch('/api/store/autobets', { method: 'DELETE' }); } catch {}
    localStorage.removeItem(this.KEY);
  },

  // ─── Stats (aus lokalem Cache) ────────────────────────────
  getStats() {
    const arr = this.load();
    const decided = arr.filter(b => b.status === 'won' || b.status === 'lost');
    const open    = arr.filter(b => b.status === 'pending');
    const won     = decided.filter(b => b.status === 'won');
    const totalStake = arr.reduce((a, b) => a + (b.stake || 0), 0);
    const decidedStake = decided.reduce((a, b) => a + (b.stake || 0), 0);
    const totalPayout = decided.reduce((a, b) => a + (b.payout || 0), 0);
    const profit = +(totalPayout - decidedStake).toFixed(2);
    const openStake = open.reduce((a, b) => a + (b.stake || 0), 0);
    return {
      total: arr.length,
      open: open.length,
      decided: decided.length,
      won: won.length,
      lost: decided.length - won.length,
      hitRate: decided.length ? won.length / decided.length : 0,
      totalStake, decidedStake, openStake,
      totalPayout, profit,
      roi: decidedStake > 0 ? profit / decidedStake : 0,
    };
  },
};

// Initial-Pull beim Laden
if (typeof window !== 'undefined') {
  window.autobetStore = autobetStore;
  // Kick off async pull, but don't block
  setTimeout(() => autobetStore.pull(), 1500);
  // Periodic re-sync alle 60s
  setInterval(() => autobetStore.pull(), 60_000);
}
