// ================= Data service =================
const STORAGE_KEYS = {
  wins: "leanerWins",
  meals: "leanerMeals",
  tips: "leanerTips",
  checkIns: "leanerCheckIns",
  pointsBalance: "leanerPointsBalance",
  pointEvents: "leanerPointEvents",
  rewards: "leanerRewards",
  redemptions: "leanerRedemptions",
  supportContent: "leanerSupportContent",
  weeklySupportSelections: "leanerWeeklySupportSelections",
  supportContentVersion: "leanerSupportContentVersion",
  rewardPackagesVersion: "leanerRewardPackagesVersion",
  currentRole: "leanerPrototypeRole",
  authSession: AUTH_SESSION_KEY
};

function loadFromStorage(key, fallback) {
  try {
    return JSON.parse(localStorage.getItem(key)) || fallback;
  } catch {
    return fallback;
  }
}

function saveToStorage(key, value) {
  localStorage.setItem(key, JSON.stringify(value));
}

function loadInitialState() {
  return {
    route: ROUTES.HOME,
    adminTab: "dashboard",
    filter: "All",
    wins: loadFromStorage(STORAGE_KEYS.wins, seedWins),
    meals: loadFromStorage(STORAGE_KEYS.meals, meals),
    tips: loadFromStorage(STORAGE_KEYS.tips, coachTips),
    checkIns: loadFromStorage(STORAGE_KEYS.checkIns, checkIns),
    pointsBalance: loadFromStorage(STORAGE_KEYS.pointsBalance, patient.pointsBalance),
    pointEvents: loadFromStorage(STORAGE_KEYS.pointEvents, seedPointEvents),
    rewards: loadFromStorage(STORAGE_KEYS.rewards, rewards),
    redemptions: loadFromStorage(STORAGE_KEYS.redemptions, []),
    supportContent: loadFromStorage(STORAGE_KEYS.supportContent, supportContentBank),
    weeklySupportSelections: loadFromStorage(STORAGE_KEYS.weeklySupportSelections, []),
    csvImport: null,
    suggestedWin: null
  };
}

function runPrototypeMigrations() {
  if (loadFromStorage(STORAGE_KEYS.supportContentVersion, "") !== supportContentVersion) {
    state.supportContent = supportContentBank;
    state.weeklySupportSelections = [];
    saveToStorage(STORAGE_KEYS.supportContentVersion, supportContentVersion);
    saveToStorage(STORAGE_KEYS.supportContent, state.supportContent);
    saveToStorage(STORAGE_KEYS.weeklySupportSelections, state.weeklySupportSelections);
  }

  if (loadFromStorage(STORAGE_KEYS.rewardPackagesVersion, "") !== rewardPackagesVersion) {
    state.rewards = rewards;
    saveToStorage(STORAGE_KEYS.rewardPackagesVersion, rewardPackagesVersion);
    saveToStorage(STORAGE_KEYS.rewards, state.rewards);
  }
}

function saveState() {
  saveToStorage(STORAGE_KEYS.wins, state.wins);
  saveToStorage(STORAGE_KEYS.meals, state.meals);
  saveToStorage(STORAGE_KEYS.tips, state.tips);
  saveToStorage(STORAGE_KEYS.checkIns, state.checkIns);
  saveToStorage(STORAGE_KEYS.pointsBalance, state.pointsBalance);
  saveToStorage(STORAGE_KEYS.pointEvents, state.pointEvents);
  saveToStorage(STORAGE_KEYS.rewards, state.rewards);
  saveToStorage(STORAGE_KEYS.redemptions, state.redemptions);
  saveToStorage(STORAGE_KEYS.supportContent, state.supportContent);
  saveToStorage(STORAGE_KEYS.weeklySupportSelections, state.weeklySupportSelections);
  if (isFirebaseMode()) {
    saveStateToBackend();
  }
}

function stateSnapshot() {
  return {
    wins: state.wins,
    meals: state.meals,
    tips: state.tips,
    checkIns: state.checkIns,
    pointsBalance: state.pointsBalance,
    pointEvents: state.pointEvents,
    rewards: state.rewards,
    redemptions: state.redemptions,
    supportContent: state.supportContent,
    weeklySupportSelections: state.weeklySupportSelections
  };
}

function applyStateSnapshot(snapshot) {
  if (!snapshot || typeof snapshot !== "object") return;
  hydrateState({
    ...state,
    ...snapshot,
    csvImport: null,
    suggestedWin: null
  });
}

function backendStateUrl(uid) {
  return `https://firestore.googleapis.com/v1/projects/${APP_CONFIG.firebase.projectId}/databases/(default)/documents/prototypeStates/${uid}`;
}

async function loadStateFromBackend() {
  if (!isFirebaseMode()) return false;
  const session = loadAuthSession();
  if (!session?.user?.uid || !session?.idToken) return false;
  try {
    const response = await fetch(backendStateUrl(session.user.uid), {
      headers: { Authorization: `Bearer ${session.idToken}` }
    });
    if (!response.ok) return false;
    const doc = await response.json();
    const payload = doc?.fields?.payload?.stringValue;
    if (!payload) return false;
    applyStateSnapshot(JSON.parse(payload));
    return true;
  } catch {
    return false;
  }
}

async function saveStateToBackend() {
  const session = loadAuthSession();
  if (!session?.user?.uid || !session?.idToken) return false;
  try {
    const response = await fetch(backendStateUrl(session.user.uid), {
      method: "PATCH",
      headers: {
        Authorization: `Bearer ${session.idToken}`,
        "Content-Type": "application/json"
      },
      body: JSON.stringify({
        fields: {
          payload: { stringValue: JSON.stringify(stateSnapshot()) },
          updatedAt: { timestampValue: new Date().toISOString() }
        }
      })
    });
    return response.ok;
  } catch {
    return false;
  }
}

function hasFirebaseConfig() {
  const firebase = APP_CONFIG.firebase || {};
  return Boolean(firebase.apiKey && firebase.projectId);
}

function isFirebaseMode() {
  return APP_CONFIG.dataMode === DATA_MODES.FIREBASE && hasFirebaseConfig();
}

function loadAuthSession() {
  return loadFromStorage(STORAGE_KEYS.authSession, null);
}

function saveAuthSession(session) {
  saveToStorage(STORAGE_KEYS.authSession, session);
}

function clearAuthSession() {
  localStorage.removeItem(STORAGE_KEYS.authSession);
}
