import type { AmountUnit } from './format';
import { useGlobal } from 'hooks/useGlobal';

// sats ⇄ BTC, shared across every wallet panel.
//
// A display preference, not a selection — it names no entity and belongs in no URL (see the audit's
// "view toggles over tiny fixed sets"). It lives in useGlobal so the nav and the view agree instantly,
// and is mirrored to localStorage so it survives a reload.

const STORAGE_KEY = 'wallet:amount-unit';

const initial = (): AmountUnit => {
  try {
    return localStorage.getItem(STORAGE_KEY) === 'btc' ? 'btc' : 'sats';
  } catch {
    return 'sats';
  }
};

export function useAmountUnit() {
  const [unit, setUnit] = useGlobal<AmountUnit>('WALLET_AMOUNT_UNIT', initial);

  const toggle = () => {
    const next: AmountUnit = unit === 'sats' ? 'btc' : 'sats';
    setUnit(next);
    try {
      localStorage.setItem(STORAGE_KEY, next);
    } catch {
      /* private mode — the preference just doesn't persist */
    }
  };

  return { unit, toggle };
}
