import { useState, useEffect, useCallback, useRef } from 'react';
import { VOCAB } from './collection-vocabulary.js';

const STORAGE_KEY = 'deckhearth:scanner-session';

const DEFAULT_DESTINATION = { type: 'owned', id: null, label: VOCAB.MY_COLLECTION };
const DEFAULT_SCAN_DEFAULTS = { condition: 'NM', isFoil: false };

function readJson(key, fallback) {
  if (typeof window === 'undefined') return fallback;
  try {
    const raw = localStorage.getItem(key);
    return raw ? JSON.parse(raw) : fallback;
  } catch {
    return fallback;
  }
}

function writeJson(key, value) {
  if (typeof window === 'undefined') return;
  try {
    localStorage.setItem(key, JSON.stringify(value));
  } catch {
    /* quota exceeded — silently degrade */
  }
}

export function useScannerSession() {
  const [sessionDestination, setSessionDestination] = useState(() => {
    const saved = readJson(STORAGE_KEY, {});
    return saved.destination ?? DEFAULT_DESTINATION;
  });
  const [gameFilter, setGameFilter] = useState(() => {
    const saved = readJson(STORAGE_KEY, {});
    return saved.gameFilter ?? 'All';
  });
  const [scanDefaults, setScanDefaults] = useState(() => {
    const saved = readJson(STORAGE_KEY, {});
    return saved.scanDefaults ?? DEFAULT_SCAN_DEFAULTS;
  });
  const isInitialRender = useRef(true);

  useEffect(() => {
    if (isInitialRender.current) {
      isInitialRender.current = false;
      return;
    }
    writeJson(STORAGE_KEY, {
      destination: sessionDestination,
      gameFilter,
      scanDefaults,
    });
  }, [sessionDestination, gameFilter, scanDefaults]);

  const handleGameFilterChange = useCallback((nextFilter) => {
    setGameFilter(nextFilter);
    setSessionDestination((current) => {
      if (!current || current.type === 'owned') return current;
      return DEFAULT_DESTINATION;
    });
  }, []);

  const handleDestinationChange = useCallback((next) => {
    setSessionDestination(next);
  }, []);

  const handleScanDefaultsChange = useCallback((patch) => {
    setScanDefaults((current) => ({ ...current, ...patch }));
  }, []);

  return {
    sessionDestination,
    setSessionDestination: handleDestinationChange,
    gameFilter,
    setGameFilter: handleGameFilterChange,
    scanDefaults,
    setScanDefaults: handleScanDefaultsChange,
  };
}
