import { supabase } from './supabase';
import * as offline from './offlineStorage';

const USE_OFFLINE = true;

// Score-to-stat mapping per game type
const STAT_BONUSES = {
  reflex_tap:        { discipline: 1.0, focus: 0.3, consistency: 0.2 },
  focus_hold:        { discipline: 0.3, focus: 1.0, consistency: 0.3 },
  temptation_choice: { discipline: 0.4, focus: 0.2, consistency: 1.0 },
  timing_tap:        { discipline: 0.5, focus: 0.8, consistency: 0.2 },
};

export async function saveGameSession(identityId, gameType, score) {
  const bonuses = STAT_BONUSES[gameType] || { discipline: 0.5, focus: 0.5, consistency: 0.5 };

  if (USE_OFFLINE) {
    await offline.insert('game_sessions', {
      identity_id: identityId,
      game_type: gameType,
      score,
    });

    const stats = await offline.getOne('stats', { identity_id: identityId });
    if (stats) {
      await offline.update('stats', { id: stats.id }, {
        discipline_score: stats.discipline_score + Math.round(score * bonuses.discipline),
        focus_score: stats.focus_score + Math.round(score * bonuses.focus),
        consistency_score: stats.consistency_score + Math.round(score * bonuses.consistency),
      });
    }
    return;
  }

  const { error } = await supabase.from('game_sessions').insert({
    identity_id: identityId,
    game_type: gameType,
    score,
  });
  if (error) throw error;

  const { data: stats } = await supabase
    .from('stats')
    .select('*')
    .eq('identity_id', identityId)
    .single();

  if (stats) {
    await supabase
      .from('stats')
      .update({
        discipline_score: stats.discipline_score + Math.round(score * bonuses.discipline),
        focus_score: stats.focus_score + Math.round(score * bonuses.focus),
        consistency_score: stats.consistency_score + Math.round(score * bonuses.consistency),
      })
      .eq('id', stats.id);
  }
}

export function getResultMessage(gameType, score) {
  const messages = {
    reflex_tap: [
      { min: 0, text: 'Slow start. Sharpen your reflexes.' },
      { min: 5, text: 'Getting faster. Keep pushing.' },
      { min: 10, text: 'Quick hands. Your discipline is showing.' },
      { min: 15, text: 'Lightning reflexes. You act without hesitation.' },
    ],
    focus_hold: [
      { min: 0, text: 'Your focus wavers. Train your stillness.' },
      { min: 2, text: 'Decent focus. Room to grow.' },
      { min: 4, text: 'Strong focus. You hold your ground.' },
      { min: 5, text: 'Unshakeable. Your mind is iron.' },
    ],
    temptation_choice: [
      { min: 0, text: 'You gave in. Next time, choose differently.' },
      { min: 3, text: 'Some good choices. Stay aware.' },
      { min: 4, text: 'Strong willpower. You chose your identity.' },
      { min: 5, text: 'Perfect clarity. Temptation has no power over you.' },
    ],
    timing_tap: [
      { min: 0, text: 'Off-beat. Train your timing.' },
      { min: 3, text: 'Getting in rhythm. Stay present.' },
      { min: 6, text: 'Great timing. You know when to strike.' },
      { min: 9, text: 'Perfect precision. You are in the zone.' },
    ],
  };

  const list = messages[gameType] || messages.reflex_tap;
  let result = list[0].text;
  for (const entry of list) {
    if (score >= entry.min) result = entry.text;
  }
  return result;
}

export function getStatLabel(gameType) {
  const labels = {
    reflex_tap: 'Discipline',
    focus_hold: 'Focus',
    temptation_choice: 'Consistency',
    timing_tap: 'Focus',
  };
  return labels[gameType] || 'Score';
}

/**
 * Get best score and last score for each game type.
 * Returns { [gameType]: { best, last } }
 */
export async function getGameScores(identityId) {
  let sessions;

  if (USE_OFFLINE) {
    sessions = await offline.getAll('game_sessions', { identity_id: identityId });
  } else {
    const { data } = await supabase
      .from('game_sessions')
      .select('game_type, score, created_at')
      .eq('identity_id', identityId);
    sessions = data || [];
  }

  const scores = {};
  // Sort by created_at so last entry is the most recent
  sessions.sort((a, b) => (a.created_at || '').localeCompare(b.created_at || ''));

  for (const s of sessions) {
    if (!scores[s.game_type]) {
      scores[s.game_type] = { best: s.score, last: s.score };
    } else {
      if (s.score > scores[s.game_type].best) scores[s.game_type].best = s.score;
      scores[s.game_type].last = s.score;
    }
  }
  return scores;
}

// Difficulty scaling based on current day
export function getDifficulty(currentDay) {
  if (currentDay <= 10) return 1;
  if (currentDay <= 20) return 2;
  if (currentDay <= 30) return 3;
  return 4;
}
