// Firebase wrapper — lazy, opt-in. Pokud není nakonfigurován, vše padá do localStorage
// (prototyp funguje offline). Po zadání config se Firebase aktivuje a začne synchronizovat.

const ADMIN_EMAILS = ['ondracraft@gmail.com']; // role admin (case-insensitive)

// Configure via window.PANDICKA_FIREBASE_CONFIG in index.html nebo přes localStorage
function readFirebaseConfig() {
  if (typeof window.PANDICKA_FIREBASE_CONFIG === 'object' && window.PANDICKA_FIREBASE_CONFIG?.apiKey) {
    return window.PANDICKA_FIREBASE_CONFIG;
  }
  try {
    const raw = localStorage.getItem('pandicka-firebase-config');
    if (raw) {
      const cfg = JSON.parse(raw);
      if (cfg?.apiKey) return cfg;
    }
  } catch {}
  return null;
}

// ─── Init ─────────────────────────────────────────────────────
let fbApp = null;
let fbAuth = null;
let fbDb = null;
let fbReady = false;

function initFirebase() {
  if (fbReady) return true;
  if (typeof window.firebase === 'undefined') return false; // CDN ještě nenačtený
  const cfg = readFirebaseConfig();
  if (!cfg) return false;
  try {
    fbApp = window.firebase.apps?.length ? window.firebase.app() : window.firebase.initializeApp(cfg);
    fbAuth = window.firebase.auth();
    fbDb = window.firebase.firestore();
    fbReady = true;
    // Zvládni redirect výsledek (po návratu z Google)
    fbAuth.getRedirectResult().catch(() => {});
    return true;
  } catch (e) {
    console.warn('Firebase init failed — pokračujeme v local módu', e);
    return false;
  }
}

function isFirebaseReady() {
  return fbReady || initFirebase();
}

// ─── Auth ─────────────────────────────────────────────────────
async function signInWithGoogle() {
  if (!isFirebaseReady()) throw new Error('Firebase není nakonfigurováno.');
  const provider = new window.firebase.auth.GoogleAuthProvider();
  provider.addScope('email');
  provider.addScope('profile');
  provider.setCustomParameters({ prompt: 'select_account' });
  let cred;
  try {
    cred = await fbAuth.signInWithPopup(provider);
  } catch (e) {
    // popup blokovaný / na mobile standalone PWA → redirect fallback
    if (/popup-blocked|operation-not-supported|web-storage-unsupported/.test(String(e?.code || ''))) {
      await fbAuth.signInWithRedirect(provider);
      return null;
    }
    throw e;
  }
  const u = cred.user;
  const existing = await fbDb.collection('users').doc(u.uid).get();
  const isFirst = !existing.exists;
  await fbDb.collection('users').doc(u.uid).set({
    email: u.email,
    displayName: u.displayName || '',
    photoURL: u.photoURL || '',
    role: existing.data()?.role || (isAdminEmail(u.email) ? 'admin' : 'parent'),
    provider: 'google',
    lastLoginAt: window.firebase.firestore.FieldValue.serverTimestamp(),
    ...(isFirst ? { createdAt: window.firebase.firestore.FieldValue.serverTimestamp(), consent: null } : {}),
  }, { merge: true });
  return u;
}

async function signOutParent() {
  if (!isFirebaseReady()) return;
  await fbAuth.signOut();
}

function onAuthChange(cb) {
  if (!isFirebaseReady()) { cb(null); return () => {}; }
  return fbAuth.onAuthStateChanged(cb);
}

function currentUser() {
  return isFirebaseReady() ? fbAuth.currentUser : null;
}

function isAdminEmail(email) {
  if (!email) return false;
  return ADMIN_EMAILS.includes(String(email).toLowerCase());
}

async function isAdmin() {
  const u = currentUser();
  if (!u) return false;
  if (isAdminEmail(u.email)) return true;
  try {
    const snap = await fbDb.collection('users').doc(u.uid).get();
    return snap.exists && snap.data()?.role === 'admin';
  } catch {
    return false;
  }
}

// ─── Consent (GDPR/COPPA) ─────────────────────────────────────
async function recordConsent(uid, consent) {
  const record = {
    ...consent,
    timestamp: isFirebaseReady()
      ? window.firebase.firestore.FieldValue.serverTimestamp()
      : new Date().toISOString(),
    userAgent: typeof navigator !== 'undefined' ? navigator.userAgent : '',
    version: '1.0',
  };
  try { localStorage.setItem('pandicka-consent', JSON.stringify({ ...record, timestamp: new Date().toISOString() })); } catch {}
  if (isFirebaseReady() && uid) {
    await fbDb.collection('users').doc(uid).set({ consent: record }, { merge: true });
  }
  return record;
}

function hasLocalConsent() {
  try {
    const raw = localStorage.getItem('pandicka-consent');
    if (!raw) return false;
    const c = JSON.parse(raw);
    return !!(c?.parentalConsent && c?.privacyPolicy);
  } catch { return false; }
}

// ─── Profiles ────────────────────────────────────────────────
async function listProfiles(uid) {
  if (!isFirebaseReady() || !uid) {
    try {
      const raw = localStorage.getItem('pandicka-profiles');
      return raw ? JSON.parse(raw) : [];
    } catch { return []; }
  }
  const snap = await fbDb.collection('users').doc(uid).collection('profiles').get();
  return snap.docs.map(d => ({ id: d.id, ...d.data() }));
}

async function saveProfile(uid, profile) {
  if (!isFirebaseReady() || !uid) {
    try {
      const list = JSON.parse(localStorage.getItem('pandicka-profiles') || '[]');
      const idx = list.findIndex(p => p.id === profile.id);
      if (idx >= 0) list[idx] = profile; else list.push(profile);
      localStorage.setItem('pandicka-profiles', JSON.stringify(list));
    } catch {}
    return profile;
  }
  const id = profile.id || fbDb.collection('_').doc().id;
  await fbDb.collection('users').doc(uid).collection('profiles').doc(id).set(
    { ...profile, id, updatedAt: window.firebase.firestore.FieldValue.serverTimestamp() },
    { merge: true },
  );
  return { ...profile, id };
}

async function deleteProfile(uid, profileId) {
  if (!isFirebaseReady() || !uid) {
    try {
      const list = JSON.parse(localStorage.getItem('pandicka-profiles') || '[]');
      localStorage.setItem('pandicka-profiles', JSON.stringify(list.filter(p => p.id !== profileId)));
    } catch {}
    return;
  }
  await fbDb.collection('users').doc(uid).collection('profiles').doc(profileId).delete();
}

// ─── Tasks (global catalog) ──────────────────────────────────
async function listGlobalTasks() {
  if (!isFirebaseReady()) return null; // → fallback to in-memory catalog v tasks.jsx
  const snap = await fbDb.collection('tasks').get();
  return snap.docs.map(d => ({ id: d.id, ...d.data() }));
}

async function upsertGlobalTask(task) {
  if (!isFirebaseReady()) throw new Error('Firebase není nakonfigurováno.');
  const admin = await isAdmin();
  if (!admin) throw new Error('Pouze admin může upravovat globální katalog.');
  await fbDb.collection('tasks').doc(task.id).set({
    ...task,
    updatedAt: window.firebase.firestore.FieldValue.serverTimestamp(),
  }, { merge: true });
}

async function deleteGlobalTask(taskId) {
  if (!isFirebaseReady()) throw new Error('Firebase není nakonfigurováno.');
  const admin = await isAdmin();
  if (!admin) throw new Error('Pouze admin může mazat z globálního katalogu.');
  await fbDb.collection('tasks').doc(taskId).delete();
}

// ─── Progress log ────────────────────────────────────────────
async function logProgress(uid, profileId, entry) {
  const record = { ...entry, profileId, timestamp: new Date().toISOString() };
  try {
    const key = `pandicka-progress-${profileId}`;
    const arr = JSON.parse(localStorage.getItem(key) || '[]');
    arr.push(record);
    // keep last 500 entries lokálně
    localStorage.setItem(key, JSON.stringify(arr.slice(-500)));
  } catch {}
  if (isFirebaseReady() && uid) {
    try {
      await fbDb.collection('users').doc(uid).collection('profiles').doc(profileId).collection('progress').add({
        ...entry,
        timestamp: window.firebase.firestore.FieldValue.serverTimestamp(),
      });
    } catch (e) {
      console.warn('Progress log to Firestore selhal:', e);
    }
  }
}

// ─── Data export / Right to erasure (GDPR) ──────────────────
async function exportMyData(uid) {
  const out = { exportedAt: new Date().toISOString(), local: {}, remote: {} };
  try {
    for (let i = 0; i < localStorage.length; i++) {
      const k = localStorage.key(i);
      if (k && k.startsWith('pandicka-')) out.local[k] = localStorage.getItem(k);
    }
  } catch {}
  if (isFirebaseReady() && uid) {
    const user = await fbDb.collection('users').doc(uid).get();
    out.remote.user = user.exists ? user.data() : null;
    const profiles = await fbDb.collection('users').doc(uid).collection('profiles').get();
    out.remote.profiles = profiles.docs.map(d => ({ id: d.id, ...d.data() }));
  }
  return out;
}

async function deleteAllMyData(uid) {
  // local
  try {
    const keys = [];
    for (let i = 0; i < localStorage.length; i++) {
      const k = localStorage.key(i);
      if (k && k.startsWith('pandicka-')) keys.push(k);
    }
    keys.forEach(k => localStorage.removeItem(k));
  } catch {}
  // remote
  if (isFirebaseReady() && uid) {
    const profiles = await fbDb.collection('users').doc(uid).collection('profiles').get();
    const batch = fbDb.batch();
    profiles.docs.forEach(d => batch.delete(d.ref));
    batch.delete(fbDb.collection('users').doc(uid));
    await batch.commit();
    try { await fbAuth.currentUser?.delete(); } catch {}
  }
}

Object.assign(window, {
  ADMIN_EMAILS,
  initFirebase, isFirebaseReady, isAdminEmail, isAdmin,
  signInWithGoogle, signOutParent,
  onAuthChange, currentUser,
  recordConsent, hasLocalConsent,
  listProfiles, saveProfile, deleteProfile,
  listGlobalTasks, upsertGlobalTask, deleteGlobalTask,
  logProgress, exportMyData, deleteAllMyData,
});
