/* ── Currency Display — display-only conversion from CAD ── */

const CURRENCY_STORAGE_KEY = 'cc-currency';
const RATES_STORAGE_KEY = 'cc-exchange-rates';
const RATES_TTL = 24 * 60 * 60 * 1000;

const CURRENCY_OPTIONS = [
  { code: 'CAD', symbol: 'CA$', label: 'CAD' },
  { code: 'USD', symbol: 'US$', label: 'USD' },
  { code: 'EUR', symbol: '€',  label: 'EUR' },
  { code: 'GBP', symbol: '£',  label: 'GBP' },
  { code: 'AUD', symbol: 'A$',  label: 'AUD' },
];

function getStoredCurrency() {
  try {
    const v = localStorage.getItem(CURRENCY_STORAGE_KEY);
    if (v && CURRENCY_OPTIONS.some(c => c.code === v)) return v;
  } catch (e) {}
  return 'CAD';
}

function getStoredRates() {
  try {
    const raw = localStorage.getItem(RATES_STORAGE_KEY);
    if (!raw) return null;
    const parsed = JSON.parse(raw);
    if (Date.now() - parsed.ts < RATES_TTL && parsed.rates) return parsed.rates;
  } catch (e) {}
  return null;
}

function storeRates(rates) {
  try {
    localStorage.setItem(RATES_STORAGE_KEY, JSON.stringify({ ts: Date.now(), rates }));
  } catch (e) {}
}

function useCurrency() {
  const [currency, setCurrencyState] = React.useState(getStoredCurrency);
  const [rates, setRates] = React.useState(getStoredRates);

  const setCurrency = React.useCallback((code) => {
    setCurrencyState(code);
    try { localStorage.setItem(CURRENCY_STORAGE_KEY, code); } catch (e) {}
  }, []);

  React.useEffect(() => {
    if (rates) return;
    let cancelled = false;
    fetch('https://api.exchangerate-api.com/v4/latest/CAD')
      .then(r => r.json())
      .then(data => {
        if (cancelled || !data.rates) return;
        setRates(data.rates);
        storeRates(data.rates);
      })
      .catch(() => {});
    return () => { cancelled = true; };
  }, []);

  return { currency, setCurrency, rates };
}

function formatPrice(cadAmount, currency, rates) {
  if (!currency || currency === 'CAD' || !rates || !rates[currency]) {
    return '$' + cadAmount.toFixed(2);
  }
  const converted = cadAmount * rates[currency];
  const opt = CURRENCY_OPTIONS.find(c => c.code === currency);
  return (opt ? opt.symbol : '$') + converted.toFixed(2);
}

function CurrencySelector({ currency, setCurrency }) {
  return React.createElement('div', { className: 'cc-currency-selector' },
    React.createElement('select', {
      className: 'cc-currency-select',
      value: currency,
      onChange: e => setCurrency(e.target.value),
      'aria-label': 'Display currency',
    },
      CURRENCY_OPTIONS.map(c =>
        React.createElement('option', { key: c.code, value: c.code }, c.label)
      ),
    ),
  );
}

window.useCurrency = useCurrency;
window.formatPrice = formatPrice;
window.CurrencySelector = CurrencySelector;
window.CURRENCY_OPTIONS = CURRENCY_OPTIONS;
