import { create } from 'zustand';
import type { CardColor } from '../types';

// Two ways to draw the suit marks on the (otherwise identical) cards: plain
// ♥♠♣♦ text glyphs ('classic') or the "sedmové" suit-icon artwork ('illustrated').
export type CardSkin = 'classic' | 'illustrated';

const STORAGE_KEY = 'bridzik.cardSkin';

function loadSkin(): CardSkin {
  try {
    return localStorage.getItem(STORAGE_KEY) === 'illustrated' ? 'illustrated' : 'classic';
  } catch {
    return 'classic';
  }
}

interface CardSkinStore {
  skin: CardSkin;
  setSkin: (skin: CardSkin) => void;
  toggle: () => void;
}

export const useCardSkin = create<CardSkinStore>((set) => ({
  skin: loadSkin(),
  setSkin: (skin) => {
    try {
      localStorage.setItem(STORAGE_KEY, skin);
    } catch {
      /* ignore — a private-mode failure just means the choice isn't persisted */
    }
    set({ skin });
  },
  toggle: () => set((s) => {
    const skin: CardSkin = s.skin === 'illustrated' ? 'classic' : 'illustrated';
    try {
      localStorage.setItem(STORAGE_KEY, skin);
    } catch {
      /* ignore */
    }
    return { skin };
  }),
}));

// Filenames in /public/cards use their own suit/value words, not the engine's
// enum names — map between the two here.
const SUIT_FILE: Record<CardColor, string> = {
  HEARTS: 'heart',
  LEAVES: 'leaf',
  ACORNS: 'acorn',
  BELLS: 'bell',
};

/** Path to a suit icon at a given resolution, e.g. `/cards/suit-icons/heart-icon@small.png`.
 *  Used to render the suit marks on the classic vector cards. */
export function suitIcon(color: CardColor, size: 'small' | 'medium' | 'large'): string {
  return `/cards/suit-icons/${SUIT_FILE[color]}-icon@${size}.png`;
}
