import { TourState } from '../types';

const TOUR_STATE_KEY = 'bakery_demo_tour_state';
const TOUR_VERSION = '1.0.0';

export const getTourState = (): TourState | null => {
  try {
    const stored = sessionStorage.getItem(TOUR_STATE_KEY);
    if (!stored) return null;

    const state = JSON.parse(stored) as TourState;

    if (state.tourVersion !== TOUR_VERSION) {
      clearTourState();
      return null;
    }

    return state;
  } catch (error) {
    console.error('Error reading tour state:', error);
    return null;
  }
};

export const saveTourState = (state: Partial<TourState>): void => {
  try {
    const currentState = getTourState() || {
      currentStep: 0,
      completed: false,
      dismissed: false,
      lastUpdated: Date.now(),
      tourVersion: TOUR_VERSION,
    };

    const newState: TourState = {
      ...currentState,
      ...state,
      lastUpdated: Date.now(),
      tourVersion: TOUR_VERSION,
    };

    sessionStorage.setItem(TOUR_STATE_KEY, JSON.stringify(newState));
  } catch (error) {
    console.error('Error saving tour state:', error);
  }
};

export const clearTourState = (): void => {
  try {
    sessionStorage.removeItem(TOUR_STATE_KEY);
  } catch (error) {
    console.error('Error clearing tour state:', error);
  }
};

export const shouldStartTour = (): boolean => {
  const tourState = getTourState();
  const shouldStart = sessionStorage.getItem('demo_tour_should_start') === 'true';

  // Only log in development to prevent excessive console output that might affect performance
  if (process.env.NODE_ENV === 'development') {
    console.log('[shouldStartTour] tourState:', tourState);
    console.log('[shouldStartTour] shouldStart flag:', shouldStart);
  }

  // If explicitly marked to start, always start (unless already completed)
  if (shouldStart) {
    if (tourState && tourState.completed) {
      if (process.env.NODE_ENV === 'development') {
        console.log('[shouldStartTour] Tour already completed, not starting');
      }
      return false;
    }
    if (process.env.NODE_ENV === 'development') {
      console.log('[shouldStartTour] Should start flag is true, starting tour');
    }
    return true;
  }

  // No explicit start flag, don't auto-start
  if (process.env.NODE_ENV === 'development') {
    console.log('[shouldStartTour] No start flag, not starting');
  }
  return false;
};

export const markTourAsStartPending = (): void => {
  sessionStorage.setItem('demo_tour_should_start', 'true');
};

export const clearTourStartPending = (): void => {
  sessionStorage.removeItem('demo_tour_should_start');
};
