// persist.jsx — Prototip veri kalıcılığı (mini "veritabanı")
// Build'siz/sunucusuz prototipte test kolaylığı için tüm paylaşılan state localStorage'a
// yazılır → sayfa yenilense de veri kaybolmaz. Ayrıca dosyaya dışa/içe aktarma + sıfırla.
// NOT: Gerçek üründe yerini backend + gerçek DB alacak; bu yalnızca prototip test aracı.
// Sürüm anahtarı: seed/yapı değişince bump'la → eski snapshot yok sayılır (eski veri tuzağı).
(function () {
  const KEY = 'ittalep-data-v3';
  let cache = null;

  function readAll() {
    if (cache) return cache;
    try { cache = JSON.parse(window.localStorage.getItem(KEY)) || {}; }
    catch (e) { cache = {}; }
    return cache;
  }

  window.__store = {
    enabled: true,
    key: KEY,
    // İlk state için: kayıtlı değer varsa onu, yoksa fallback (demo seed)
    get(k, fallback) {
      const all = readAll();
      return (all && Object.prototype.hasOwnProperty.call(all, k)) ? all[k] : fallback;
    },
    // Tüm snapshot'ı yaz (App tek efekttte çağırır)
    saveAll(obj) {
      try { cache = obj; window.localStorage.setItem(KEY, JSON.stringify(obj)); }
      catch (e) { /* kota dolabilir; sessiz geç */ }
    },
    has() {
      try { return !!window.localStorage.getItem(KEY); } catch (e) { return false; }
    },
    // Demo verisine dön
    reset() {
      if (!window.confirm('Tüm kayıtlı veri silinsin ve demo verisine dönülsün mü? (Sayfa yenilenecek)')) return;
      try { window.localStorage.removeItem(KEY); } catch (e) {}
      cache = {};
      window.location.reload();
    },
    // Gerçek dosyaya yedekle
    exportFile() {
      const data = (function () { try { return window.localStorage.getItem(KEY) || '{}'; } catch (e) { return '{}'; } })();
      const blob = new Blob([data], { type: 'application/json' });
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = 'ittalep-veri-' + new Date().toISOString().slice(0, 10) + '.json';
      document.body.appendChild(a); a.click(); a.remove();
      URL.revokeObjectURL(url);
    },
    // Dosyadan geri yükle
    importFile() {
      const inp = document.createElement('input');
      inp.type = 'file'; inp.accept = 'application/json,.json';
      inp.onchange = (e) => {
        const f = e.target.files && e.target.files[0];
        if (!f) return;
        const r = new FileReader();
        r.onload = () => {
          try { JSON.parse(r.result); window.localStorage.setItem(KEY, r.result); window.location.reload(); }
          catch (err) { window.alert('Geçersiz veri dosyası.'); }
        };
        r.readAsText(f);
      };
      inp.click();
    },
  };
})();
