import { VOCAB } from './collection-vocabulary.js';

export const SCANNER_SESSION_STORAGE_KEY = 'deckhearth:scanner-session';

export const DEFAULT_SCANNER_DESTINATION = {
  type: 'owned',
  id: null,
  label: VOCAB.MY_COLLECTION,
};

export const DEFAULT_SCAN_DEFAULTS = { condition: 'NM', isFoil: false };

export function loadSavedScannerSession() {
  if (typeof window === 'undefined') {
    return {
      destination: DEFAULT_SCANNER_DESTINATION,
      gameFilter: 'All',
      scanDefaults: DEFAULT_SCAN_DEFAULTS,
    };
  }

  try {
    const saved = JSON.parse(localStorage.getItem(SCANNER_SESSION_STORAGE_KEY));
    return {
      destination: saved?.destination || DEFAULT_SCANNER_DESTINATION,
      gameFilter: saved?.gameFilter || 'All',
      scanDefaults: saved?.scanDefaults || DEFAULT_SCAN_DEFAULTS,
    };
  } catch {
    return {
      destination: DEFAULT_SCANNER_DESTINATION,
      gameFilter: 'All',
      scanDefaults: DEFAULT_SCAN_DEFAULTS,
    };
  }
}

export function saveScannerSession({ destination, gameFilter, scanDefaults }) {
  if (typeof window === 'undefined') return;
  localStorage.setItem(
    SCANNER_SESSION_STORAGE_KEY,
    JSON.stringify({ destination, gameFilter, scanDefaults })
  );
}

export function createScanCardId() {
  return Date.now() + Math.random();
}

export function destinationActionKey(destination) {
  if (!destination) return 'pending';
  return destination.type === 'owned' ? 'owned' : destination.type;
}

export function mergeScannedCardEntry(existingCards, cardData, scanDefaults) {
  const existingCardIndex = existingCards.findIndex(
    (existing) =>
      existing.name === cardData.name && existing.set === cardData.set && !existing.processed
  );

  if (existingCardIndex !== -1) {
    const existing = existingCards[existingCardIndex];
    const cardEntry = {
      ...existing,
      quantity: (existing.quantity || 1) + 1,
      scanImageUrl: cardData.scanImageUrl || existing.scanImageUrl,
      timestamp: new Date().toISOString(),
    };
    const updated = [...existingCards];
    updated[existingCardIndex] = cardEntry;
    return { cardEntry, scannedCards: updated, merged: true };
  }

  const cardEntry = {
    ...cardData,
    id: createScanCardId(),
    name: cardData.name,
    set: cardData.set,
    quantity: 1,
    condition: scanDefaults.condition,
    isFoil: scanDefaults.isFoil,
    timestamp: new Date().toISOString(),
    processed: false,
  };

  return { cardEntry, scannedCards: [cardEntry, ...existingCards], merged: false };
}
